使用REST客户端进行Elasticsearch批量插入

6
为了提高性能,我想批量发送文档到Elasticsearch,而不是一个接一个地发送。我阅读了elastic bulk API的相关内容,链接为:https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/java-docs-bulk.html 然而,我正在使用Elasticsearch rest-client(链接为:https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/index.html),但是找不到任何有关如何进行批量插入的示例或文档。我所能找到的都是通过transport client进行批量请求的说明。
我猜我需要按照此处描述的方式准备请求正文(链接为:https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-bulk.html),并将其传递给restclient的performRequest方法?是否还有其他方法,例如ES java rest-client库中的构建器机制,可以使用rest进行批量插入?
2个回答

19

是的,目前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
}

我有我的JSONArray,并试图将我的文档列表转换为JSON字符串。 我不确定如何转换。 我有一个关于这个问题的单独问题。 https://stackoverflow.com/questions/51868548/elasticsearch-indexing-100k-documents-with-bulkrequest-api-using-java-resthighle - Karthikeyan
我正在尝试这个,它显示成功状态,但数据没有被发布到弹性搜索中。在 Kibana 中找不到它们。那么如何调试此问题呢? - MansoorShaikh
@MansoorShaikh 请随意发布您的问题,并提供重现问题的方法。 - Val

-1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接