我正在创建将与我们的Java代码库集成的Elasticsearch集群。我想创建一个Elasticsearch索引并将SQL Query数据从多个数据库插入其中。来自所有数据库的查询结果应插入相同的索引中。为此,我正在使用Java高级Rest Client。 但是我不太确定如何执行此操作,因为不赞成使用旧API中的许多方法。 我也不太确定该如何处理createIndexResponse实例。 有人可以帮我吗?
public static void method_1(Connection con) throws Exception {
Statement statement = con.createStatement();
try {
ResultSet result = statement.executeQuery("SELECT Field_1, Field_2, Field_3 from Table_1");
int counter = 1;
CreateIndexRequest createIndexRequest = new CreateIndexRequest("index_name");
createIndexRequest.settings(new Settings.Builder()
.put("cluster.name", "my_cluster")
.put("http.enabled", true)
.put("node.data", true)
.put("index.number_of_shards", 3)
.put("index.number_of_replicas", 1)
.build());
CreateIndexResponse createIndexResponse = ElasticSearch.eclient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
BulkRequest bulkRequest = new BulkRequest();
while (result.next()) {
String field_1 = result.getString("Field_1");
int field_2 = result.getInt("Field_2");
String field_3 = result.getString("Field_3");
XContentBuilder builder = XContentFactory.jsonBuilder()
.startObject()
.field("Field 1", field_1)
.field("Field 2", field_2)
.field("Field 3", field_3)
.endObject();
UpdateRequest updateRequest = new UpdateRequest("index_name", "_doc", Integer.toString(counter));
updateRequest.doc(builder);
bulkRequest.add(updateRequest);
}
BulkResponse response = ElasticSearch.eclient.bulk(bulkRequest, RequestOptions.DEFAULT);
if (response.hasFailures()) {
for (BulkItemResponse item : response.getItems()) {
System.out.println(item.getFailureMessage());
}
}
counter++;
statement.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
答案 0 :(得分:1)
您没有提供正在使用的版本。无论如何,我正在考虑您使用的是7.0.0。
我想这是一个可以的例子:
try (RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(HttpHost.create("http://localhost:9200")))) {
CreateIndexRequest createIndexRequest = new CreateIndexRequest("index_name");
createIndexRequest.settings(Settings.builder()
.put("index.number_of_shards", 3)
.put("index.number_of_replicas", 1)
.build());
client.indices().create(createIndexRequest, RequestOptions.DEFAULT);
BulkRequest bulkRequest = new BulkRequest();
XContentBuilder builder = XContentFactory.jsonBuilder()
.startObject()
.field("foo", "bar")
.endObject();
IndexRequest indexRequest = new IndexRequest("index_name");
indexRequest.source(builder);
bulkRequest.add(indexRequest);
BulkResponse response = client.bulk(bulkRequest, RequestOptions.DEFAULT);
if (response.hasFailures()) {
for (BulkItemResponse item : response.getItems()) {
System.out.println(item.getFailureMessage());
}
}
} catch (IOException e) {
e.printStackTrace();
}
我建议使用BulkProcessor
类,它更易于处理IMO。我有a full demo repository,我将在每个新发行版中进行更新。它也可能对您有帮助。