Elasticsearch Bulk批量操作

ElasticSearch-javaAPI-Bulk批量操作
脚本批量操作

{"delete":{"_index":"person","_id":"2"}}
{"create":{"_index":"person","_id":"5"}}
{"name":"田七","age":22,"address":"北京海淀区"}
{"update":{"_index":"person","_id":"3"}}

javaApi批量操作
/**

  • 批量操作
  • 删除5号记录
  • 添加8号记录
  • 修改4号记录,名称为赵六4号
    */
    @Test
    void bulkDoc() throws IOException {
    //创建bulkRequest,整合所有操作
    BulkRequest bulkRequest=new BulkRequest();
    //删除5号记录
    DeleteRequest deleteRequest=new DeleteRequest("person","5");
    bulkRequest.add(deleteRequest);

//添加8号记录
Map<String, Object> mapAdd=new HashMap<>();
mapAdd.put("name","tomas");
mapAdd.put("age",38);
mapAdd.put("address","北京");
IndexRequest indexRequest=new IndexRequest("person").id("8").source(mapAdd);
bulkRequest.add(indexRequest);

//修改4号记录
Map<String, Object> mapUpdate=new HashMap<>();
mapUpdate.put("name","赵六4号");
UpdateRequest updateRequest=new UpdateRequest("person","4").doc(mapUpdate);
bulkRequest.add(updateRequest);

//执行批量操作
BulkResponse bulkResponse = client.bulk(bulkRequest, RequestOptions.DEFAULT);
if (bulkResponse.hasFailures()) {
BulkItemResponse[] bulkItemResponse = bulkResponse.getItems();
for (int i = 0; i <bulkItemResponse.length ; i++) {
System.out.println(bulkItemResponse[i].getItemId()+":"+bulkItemResponse[i].getIndex()+":"+bulkItemResponse[i].getFailureMessage());
}
}
}

posted @ 2022-12-26 15:52  托马斯布莱克  阅读(126)  评论(0编辑  收藏  举报