为了提高性能,我希望将文档批量发送到Elasticsearch,而不是逐个发送。我在https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/java-docs-bulk.html上读到过有关elastic bulk API的文章
但是,我使用的是Elasticsearch rest-client (https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/index.html),找不到任何有关如何进行批量插入的示例或文档。我所能找到的就是关于通过传输客户端的批量请求。
我想我必须准备这里描述的请求体(https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-bulk.html),并将其传递给restclient的performRequest方法?是否有其他方法,例如,ES java rest-client库中的构建器机制,使用rest进行批量插入?
发布于 2017-04-11 16:13:09
是的,这是正确的,目前REST客户端只允许向ES发送原始的REST查询,但不允许太复杂。Elastic接下来正在开发一个高级客户端,它将工作在REST客户端之上,并允许您发送DSL查询等。
现在,这里有一个示例代码,您可以使用它将文档批量发送到ES服务器:
RestClient client = ...;
String actionMetaData = String.format("{ \"index\" : { \"_index\" : \"%s\", \"_type\" : \"%s\" } }%n", index, type);
List<String> bulkData = ...; // a list of your documents in JSON strings
StringBuilder bulkRequestBody = new StringBuilder();
for (String bulkItem : bulkData) {
bulkRequestBody.append(actionMetaData);
bulkRequestBody.append(bulkItem);
bulkRequestBody.append("\n");
}
HttpEntity entity = new NStringEntity(bulkRequestBody.toString(), ContentType.APPLICATION_JSON);
try {
Response response = client.performRequest("POST", "/your_index/your_type/_bulk", Collections.emptyMap(), entity);
return response.getStatusLine().getStatusCode() == HttpStatus.SC_OK;
} catch (Exception e) {
// do something
}发布于 2018-05-28 20:31:38
除了Val答案之外的另一个示例:http://web.archive.org/web/20180813044955/http://cscengineer.net/2016/10/22/elastic-search-bulk-api/
只需使用POST而不是PUT (在使用rest模板时要注意.exchange )
https://stackoverflow.com/questions/43339120
复制相似问题