【ElasticSearch】ES与MySQL数据同步方案及Java实现
import org.apache.http.HttpHost;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import java.sql.*;
public class ElasticSearchMySQLSync {
// 连接Elasticsearch
private static RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http")));
// 连接MySQL
private static Connection connectMySQL() throws SQLException {
String url = "jdbc:mysql://localhost:3306/database_name";
String username = "your_username";
String password = "your_password";
return DriverManager.getConnection(url, username, password);
}
public static void main(String[] args) {
try (Connection conn = connectMySQL()) {
// 查询MySQL数据
String query = "SELECT * FROM your_table";
Statement statement = conn.createStatement();
ResultSet resultSet = statement.executeQuery(query);
// 遍历结果集并同步到Elasticsearch
while (resultSet.next()) {
// 从结果集中获取数据并构造为Elasticsearch文档
String id = resultSet.getString("id");
String data = resultSet.getString("data_field");
IndexRequest request = new IndexRequest("index_name").id(id).source(data, XContentType.JSON);
client.index(request, RequestOptions.DEFAULT);
}
} catch (SQLException | IOException e) {
e.printStackTrace();
}
}
}
这段代码展示了如何使用Java连接Elasticsearch和MySQL,并将MySQL中的数据同步到Elasticsearch中。需要注意的是,代码中的数据库连接信息(如数据库URL、用户名和密码)、索引名称、查询语句和字段映射需要根据实际情况进行修改。
评论已关闭