public class UpdateElasticAPI { private static RestClient restClient; static { restClient=RestClient.builder(new HttpHost("localhost",9200,"http")).build(); } /** * 1.創建文檔 * @throws Exception */ @Test public void CreateDocument()throws Exception{ String method = "PUT"; String endpoint = "/update_index/test/1"; HttpEntity entity = new NStringEntity( "{\n" + " \"counter\" : 1,\n" + " \"tags\" : [\"red\"]\n" + "}", ContentType.APPLICATION_JSON); Response response = restClient.performRequest(method,endpoint, Collections.<String, String>emptyMap(),entity); System.out.println(EntityUtils.toString(response.getEntity())); } /** *2. 獲取文檔 * @throws Exception */ @Test public void getDocument()throws Exception{ String method = "GET"; String endpoint = "/update_index/test/1"; Response response = restClient.performRequest(method,endpoint); System.out.println(EntityUtils.toString(response.getEntity())); } /** * 3.更新文檔,給counter字段加4 * @throws Exception */ @Test public void UpdateDocument()throws Exception{ String method = "POST"; String endpoint = "/update_index/test/1/_update"; HttpEntity entity = new NStringEntity( "{\n" + " \"script\" : {\n" + " \"source\": \"ctx._source.counter += params.count\",\n" + " \"lang\": \"painless\",\n" + " \"params\" : {\n" + " \"count\" : 4\n" + " }\n" + " }\n" + "}", ContentType.APPLICATION_JSON); Response response = restClient.performRequest(method,endpoint, Collections.<String, String>emptyMap(),entity); System.out.println(EntityUtils.toString(response.getEntity())); } /** * 4.部分文檔更新增加字段(不存在name字段),存在則覆蓋 * @throws Exception */ @Test public void SomeUpdateDocument()throws Exception{ String method = "POST"; String endpoint = "/update_index/test/1/_update"; HttpEntity entity = new NStringEntity( "{\n" + " \"doc\" : {\n" + " \"user\" : \"kimchy\"\n" + " }\n" + "}", ContentType.APPLICATION_JSON); Response response = restClient.performRequest(method,endpoint, Collections.<String, String>emptyMap(),entity); System.out.println(EntityUtils.toString(response.getEntity())); } /** * 5.按查詢API更新 */ }