package es_01_document; import com.kwan.shuyu.SearchApplication; import lombok.extern.slf4j.Slf4j; import org.elasticsearch.action.DocWriteResponse; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.action.support.replication.ReplicationResponse; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestHighLevelClient; 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; import java.util.HashMap; import java.util.Map; @Slf4j @SpringBootTest(classes = SearchApplication.class) @RunWith(SpringRunner.class) public class TestDocument_04_add { @Autowired RestHighLevelClient client; @Test public void testAdd() throws IOException { //构建请求 IndexRequest request = new IndexRequest("test_post"); request.id("6"); //构建文档数据 Map jsonMap = new HashMap(); jsonMap.put("user", "tomas"); jsonMap.put("postDate", "2019-07-18"); jsonMap.put("message", "trying out es1"); request.source(jsonMap); //同步执行 IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT); //获取结果 log.info(indexResponse.getIndex()); log.info(indexResponse.getId()); log.info(String.valueOf(indexResponse.getResult())); if (indexResponse.getResult() == DocWriteResponse.Result.CREATED) { DocWriteResponse.Result result = indexResponse.getResult(); log.info("CREATE" + result); } else if (indexResponse.getResult() == DocWriteResponse.Result.UPDATED) { DocWriteResponse.Result result = indexResponse.getResult(); log.info("UPDATED" + result); } ReplicationResponse.ShardInfo shardInfo = indexResponse.getShardInfo(); if (shardInfo.getTotal() != shardInfo.getSuccessful()) { log.info("处理成功的分片数少于总分片!"); } if (shardInfo.getFailed() > 0) { for (ReplicationResponse.ShardInfo.Failure failure : shardInfo.getFailures()) { String reason = failure.reason();//每一个错误的原因 log.info(reason); } } } }