elasticsearch实现增删改查操作restClient.performRequest

时间:2020-12-16 15:23:53   收藏:0   阅读:428

1、pom文件新增依赖

  1.  
    <dependency>
  2.  
    <groupId>org.elasticsearch.client</groupId>
  3.  
    <artifactId>elasticsearch-rest-client</artifactId>
  4.  
    <version>6.3.1</version>
  5.  
    </dependency>
  6.  
     
  7.  
    <!--阿里 FastJson依赖-->
  8.  
    <dependency>
  9.  
    <groupId>com.alibaba</groupId>
  10.  
    <artifactId>fastjson</artifactId>
  11.  
    <version>1.2.39</version>
  12.  
    </dependency>

2、编写代码

  1.  
    import com.alibaba.fastjson.JSONObject;
  2.  
    import com.example.demo.model.novel;
  3.  
    import org.apache.http.HttpEntity;
  4.  
    import org.apache.http.HttpHost;
  5.  
    import org.apache.http.entity.ContentType;
  6.  
    import org.apache.http.nio.entity.NStringEntity;
  7.  
    import org.apache.http.util.EntityUtils;
  8.  
    import org.elasticsearch.client.Response;
  9.  
    import org.elasticsearch.client.RestClient;
  10.  
    import org.springframework.web.bind.annotation.GetMapping;
  11.  
    import org.springframework.web.bind.annotation.RestController;
  12.  
    import java.io.IOException;
  13.  
    import java.util.Collections;
  14.  
    import java.util.Date;
  15.  
     
  16.  
    /**
  17.  
    * Created by Administrator on 2019/4/21.
  18.  
    */
  19.  
    @RestController
  20.  
    public class HelloController {
  21.  
     
  22.  
    RestClient restClient = RestClient.builder(
  23.  
    new HttpHost("localhost", 9200, "http")).build();
  24.  
     
  25.  
    /**
  26.  
    * 查看api信息
  27.  
    *
  28.  
    * @throws Exception
  29.  
    */
  30.  
    @GetMapping("/bookApi")
  31.  
    public void bookApi() throws Exception {
  32.  
    String method = "GET";
  33.  
    String endpoint = "/book";
  34.  
    Response response = restClient.performRequest(method, endpoint);
  35.  
    System.out.println(EntityUtils.toString(response.getEntity()));
  36.  
    }
  37.  
     
  38.  
    /**
  39.  
    * 新增索引
  40.  
    *
  41.  
    * @throws IOException
  42.  
    */
  43.  
    @GetMapping("/addIndex")
  44.  
    public void addIndex() throws IOException {
  45.  
    String method = "PUT";
  46.  
    String endpoint = "/book";
  47.  
    Response response = restClient.performRequest(method, endpoint);
  48.  
    System.out.println(EntityUtils.toString(response.getEntity()));
  49.  
    }
  50.  
     
  51.  
    /**
  52.  
    * 新增文档
  53.  
    *
  54.  
    * @throws Exception
  55.  
    */
  56.  
    @GetMapping("/createDocument")
  57.  
    public void createDocument() throws Exception {
  58.  
    String method = "PUT";
  59.  
    String endpoint = "/book/novel/1"; // 索引:图书【DB】 类型:小说【table】 文档:【表里的数据】
  60.  
    novel testNovel = new novel();
  61.  
    testNovel.setName("三国演义");
  62.  
    testNovel.setWriter("张飞");
  63.  
    testNovel.setCount(10);
  64.  
    testNovel.setPublishDate(new Date());
  65.  
    String jsonStr = JSONObject.toJSONString(testNovel);
  66.  
    // JSON格式字符串
  67.  
    HttpEntity entity = new NStringEntity(jsonStr, ContentType.APPLICATION_JSON);
  68.  
    Response response = restClient.performRequest(method, endpoint, Collections.emptyMap(), entity);
  69.  
    System.out.println(EntityUtils.toString(response.getEntity()));
  70.  
    System.out.println("新增文档结束!!!");
  71.  
    // 返回结果:
  72.  
    // {"_index":"book","_type":"novel","_id":"1","_version":1,"result":"created","_shards":{"total":2,"successful":1,"failed":0},"_seq_no":0,"_primary_term":1}
  73.  
    }
  74.  
     
  75.  
    /**
  76.  
    * 查询文档
  77.  
    *
  78.  
    * @throws Exception
  79.  
    */
  80.  
    @GetMapping("/queryDocument")
  81.  
    public void queryDocument() throws Exception {
  82.  
    String method = "GET";
  83.  
    String endpoint = "/book/novel/1";
  84.  
    Response response = restClient.performRequest(method, endpoint);
  85.  
    System.out.println(EntityUtils.toString(response.getEntity()));
  86.  
    System.out.println("查询文档结束!!!");
  87.  
    // 返回结果:
  88.  
    // {"_index":"book","_type":"novel","_id":"1","_version":1,"found":true,"_source":{"count":10,"name":"三国演义","publishDate":1555825698934,"writer":"张飞"}}
  89.  
     
  90.  
    }
  91.  
     
  92.  
    /**
  93.  
    * 查询所有数据
  94.  
    *
  95.  
    * @throws Exception
  96.  
    */
  97.  
    @GetMapping("/queryAll")
  98.  
    public void queryAll() throws Exception {
  99.  
    String method = "POST";
  100.  
    String endpoint = "/book/novel/_search";
  101.  
    HttpEntity entity = new NStringEntity("{\n" +
  102.  
    " \"query\": {\n" +
  103.  
    " \"match_all\": {}\n" +
  104.  
    " }\n" +
  105.  
    "}", ContentType.APPLICATION_JSON);
  106.  
     
  107.  
    Response response = restClient.performRequest(method, endpoint, Collections.emptyMap(), entity);
  108.  
    System.out.println(EntityUtils.toString(response.getEntity()));
  109.  
    System.out.println("查询所有数据:queryAll !!!");
  110.  
    // 返回结果
  111.  
    // {"took":140,"timed_out":false,"_shards":{"total":5,"successful":5,"skipped":0,"failed":0},"hits":{"total":1,"max_score":1.0,"hits":[{"_index":"book","_type":"novel","_id":"1","_score":1.0,"_source":{"count":10,"name":"三国演义","publishDate":1555825698934,"writer":"张飞"}}]}}
  112.  
    }
  113.  
     
  114.  
    /**
  115.  
    * 根据ID获取
  116.  
    *
  117.  
    * @throws Exception
  118.  
    */
  119.  
    @GetMapping("/queryByField")
  120.  
    public void queryByField() throws Exception {
  121.  
    String method = "POST";
  122.  
    String endpoint = "/book/novel/_search";
  123.  
    HttpEntity entity = new NStringEntity("{\n" +
  124.  
    " \"query\": {\n" +
  125.  
    " \"match\": {\n" +
  126.  
    " \"name\": \"三国\"\n" +
  127.  
    " }\n" +
  128.  
    " }\n" +
  129.  
    "}", ContentType.APPLICATION_JSON);
  130.  
     
  131.  
    Response response = restClient.performRequest(method, endpoint, Collections.emptyMap(), entity);
  132.  
    System.out.println(EntityUtils.toString(response.getEntity()));
  133.  
    // 返回结果
  134.  
    // {"took":3,"timed_out":false,"_shards":{"total":5,"successful":5,"skipped":0,"failed":0},"hits":{"total":1,"max_score":0.5753642,"hits":[{"_index":"book","_type":"novel","_id":"1","_score":0.5753642,"_source":{"count":10,"name":"三国演义","publishDate":1555825698934,"writer":"张飞"}}]}}
  135.  
    }
  136.  
     
  137.  
    /**
  138.  
    * 更新数据
  139.  
    *
  140.  
    * @throws Exception
  141.  
    */
  142.  
    @GetMapping("/updateDocument")
  143.  
    public void updateDocument() throws Exception {
  144.  
    // doc_as_upsert :使用doc_as_upsert可以在文档不存在的时候,把doc中的内容插入到文档中
  145.  
    String method = "POST";
  146.  
    String endpoint = "/book/novel/1/_update";
  147.  
    HttpEntity entity = new NStringEntity("{\n" +
  148.  
    " \"doc\": {\n" +
  149.  
    " \"name\":\"三国演义修改哈哈哈\"\n" +
  150.  
    " }\n" +
  151.  
    "}", ContentType.APPLICATION_JSON);
  152.  
    Response response = restClient.performRequest(method, endpoint, Collections.emptyMap(), entity);
  153.  
    System.out.println(EntityUtils.toString(response.getEntity()));
  154.  
    }
  155.  
     
  156.  
    /**
  157.  
    * 删除数据
  158.  
    *
  159.  
    * @throws Exception
  160.  
    */
  161.  
    @GetMapping("/deleteDocument")
  162.  
    public void deleteDocument() throws Exception {
  163.  
    String method = "DELETE";
  164.  
    String endpoint = "/book/novel/1";
  165.  
    HttpEntity entity = new NStringEntity("", ContentType.APPLICATION_JSON);
  166.  
    Response response = restClient.performRequest(method, endpoint, Collections.emptyMap(), entity);
  167.  
    System.out.println(EntityUtils.toString(response.getEntity()));
  168.  
    // 返回结果
  169.  
    // {"_index":"book","_type":"novel","_id":"1","_version":5,"result":"deleted","_shards":{"total":2,"successful":1,"failed":0},"_seq_no":4,"_primary_term":1}
  170.  
    }
  171.  
     
  172.  
    /**
  173.  
    * 按条件删除数据
  174.  
    *
  175.  
    * @throws Exception
  176.  
    */
  177.  
    @GetMapping("/deleteDocumentByCondition")
  178.  
    public void deleteDocumentByCondition() throws Exception {
  179.  
    String method = "DELETE";
  180.  
    String endpoint = "/book/novel/_delete_by_query ";
  181.  
    /* {
  182.  
    "query":{
  183.  
    "term":{
  184.  
    "author":"test2"
  185.  
    }
  186.  
    }
  187.  
    }*/
  188.  
     
  189.  
    /* HttpEntity entity = new NStringEntity("{\n" +
  190.  
    " \"query\": {\n" +
  191.  
    " \"term\":\"三国演义修改哈哈哈\"\n" +
  192.  
    " }\n" +
  193.  
    "}", ContentType.APPLICATION_JSON);*/
  194.  
    Response response = restClient.performRequest(method, endpoint, Collections.emptyMap(), entity);
  195.  
    System.out.println(EntityUtils.toString(response.getEntity()));
  196.  
    }
  197.  
    }

补充:

1、使用doc_as_upsert可以在文档不存在的时候,把doc中的内容插入到文档中。

  1.  
    curl -XPOST ‘localhost:9200/test/type1/1/_update‘ -d ‘{
  2.  
    "doc" : {
  3.  
    "name" : "new_name"
  4.  
    },
  5.  
    "doc_as_upsert" : true
  6.  
    }‘

2、retry_on_conflict

  1.  
    当执行索引和更新的时候,有可能另一个进程正在执行更新。这个时候就会造成冲突,
  2.  
    这个参数就是用于定义当遇到冲突时,再过多长时间执行操作。

原文:https://www.cnblogs.com/QuickSlow/p/14143472.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!