package es_01_document; import com.kwan.shuyu.SearchApplication; import lombok.extern.slf4j.Slf4j; import org.elasticsearch.action.DocWriteResponse; import org.elasticsearch.action.bulk.BulkItemResponse; import org.elasticsearch.action.bulk.BulkRequest; import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.action.delete.DeleteRequest; import org.elasticsearch.action.delete.DeleteResponse; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.action.update.UpdateRequest; import org.elasticsearch.action.update.UpdateResponse; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.common.xcontent.XContentType; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import java.io.IOException; /** * 批量操作 * * @author : qinyingjie * @version : 2.2.0 * @date : 2023/5/10 14:18 */ @Slf4j @SpringBootTest(classes = SearchApplication.class) @RunWith(SpringRunner.class) public class TestDocument_10_bulk { @Autowired RestHighLevelClient client; @Test public void testBulk() throws IOException { //创建请求 BulkRequest request = new BulkRequest(); request.add(new IndexRequest("post").id("1").source(XContentType.JSON, "field", "1")); request.add(new IndexRequest("post").id("2").source(XContentType.JSON, "field", "2")); request.add(new UpdateRequest("post", "1").doc(XContentType.JSON, "field", "3")); request.add(new DeleteRequest("post").id("2")); //执行 BulkResponse bulkResponse = client.bulk(request, RequestOptions.DEFAULT); //获取结果 for (BulkItemResponse itemResponse : bulkResponse) { DocWriteResponse response = itemResponse.getResponse(); switch (itemResponse.getOpType()) { case INDEX: IndexResponse indexResponse = (IndexResponse) response; log.info("INDEX:" + indexResponse.getResult()); break; case CREATE: IndexResponse createResponse = (IndexResponse) response; log.info("CREATE:" + createResponse.getResult()); break; case UPDATE: UpdateResponse updateResponse = (UpdateResponse) response; log.info("UPDATE:" + updateResponse.getResult()); break; case DELETE: DeleteResponse deleteResponse = (DeleteResponse) response; log.info("DELETE:" + deleteResponse.getResult()); break; } } } }