Elasticsearch批处理

Bulk API


批处理API用于在单个API调用中执行大量的索引/删除操作,这样有效提高索引速度。

REST API端点为/_bulk,期待的输入格式为:

action_and_meta_data \n
optional_source \n

note:最后一行数据必须以换行符结尾。
note:向端点发送请求时,Content-Type首部应该被设置为application/x-ndjson。

行为可以设置为index、create、delete与update。
index与create行为需要在下一行设置与标准索引API的op_type参数具有相同的语义的源。
delete不需要在下一行设置与标准删除API具有相同语义的源。
update需要在下一行指定局部文档、更新插入、脚本以及选项。

curl -XPOST -H "Content-Type:application/x-ndjson" "http://localhost:9200/accounts/_bulk" --data-binary @accounts.json

note:使用–data-binary将accounts.json中的批命令进行传送。

批动作的响应是每个执行动作结果的集合构成的大JSON结构。
单个动作的失败不会影响剩余的动作。

Java 客户端

创建批处理请求

BulkRequest request = new BulkRequest();

添加批处理动作

request.add(new IndexRequest("kkk", "doc", "1").source(XContentType.JSON, "name", "foo"));
request.add(new IndexRequest("kkk", "doc", "2").source(XContentType.JSON, "name", "bar"));
request.add(new IndexRequest("kkk", "doc", "3").source(XContentType.JSON, "name", "baz"));

同步执行批处理

BulkResponse bulkResponse = client.bulk(request, RequestOptions.DEFAULT);

批处理响应处理

 for(BulkItemResponse bulkItemResponse : bulkResponse){
 	DocWriteResponse itemResponse = bulkItemResponse.getResponse();
 	if(bulkItemResponse.getOpType() == DocWriteRequest.OpType.INDEX) {
 		IndexResponse indexResponse = (IndexResponse) itemResponse;
 	}
 }

参考资料:
Elasticsearch 6.4 文档

Elasticsearch 6.4 Java REST 客户端文档

猜你喜欢

转载自blog.csdn.net/qq_32165041/article/details/83055172