• ES基本使用_2_整合SpringBoot


    1.整合SpringBoot

    1.1导入依赖

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
    </dependency>
    
    • 1
    • 2
    • 3
    • 4

    1.2配置客户端

    @Configuration
    @PropertySource("classpath:application.properties")
    public class ElasticSearchConfig {
    
        @Value("${es.host}")
        private String host; //绑定配置文件
    
        @Value("${es.port}")
        private int port;
    
        @Value("${es.scheme}")
        private String scheme;
    
        @Bean
        public RestHighLevelClient restHighLevelClient() {
            RestHighLevelClient client = new RestHighLevelClient(
                    RestClient.builder(
                            new HttpHost(host, port, scheme)));
            return client;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    application.propertie

    es.host=xx.xx.xx.xx
    es.port=9200
    es.scheme=http
    
    • 1
    • 2
    • 3

    1.3ElasticSearchOperations

    特点:始终使用面向对象的方式操作ES

    相关注解

    @Data
    @Document(indexName = "products")  //指定索引名 索引默认不存在时自动创建
    public class Product {
    
        //@Id注解 指定id属性为 文档的_id
        @Id
        private Integer id;
    
        @Field(type = FieldType.Keyword)
        private String title;
    
        @Field(type = FieldType.Double)
        private Double price;
    
        @Field(type = FieldType.Text, analyzer = "ik_max_word") //指定使用ik分词器
        private String description;
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    插入更新文档

        @Test
        void test(){
            Product product = new Product();
            product.setId(1);
            product.setPrice(1.23d);
            product.setTitle("xxx");
            product.setDescription("凯文杜兰特真帅");
            //当文档_id不存在时添加,存在时更新,注意:此更新不会保留原始字段,
            elasticsearchOperations.save(product);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    根据id查询文档

    Product res = elasticsearchOperations.get("1", Product.class);
    
    • 1

    删除文档

    //返回删除文档的id
    String delete = elasticsearchOperations.delete("1", Product.class);
    
    • 1
    • 2

    查询所有

     SearchHits<Product> searchHits = elasticsearchOperations.search(Query.findAll(), Product.class);
            searchHits.forEach(productSearchHit -> {
                System.out.println(productSearchHit.getContent()); //获取数据
            });
    
    • 1
    • 2
    • 3
    • 4

    1.4RestHighLevelClient*

    1.4.1创建索引和映射

    PUT /products/
    {
      "mappings": {
        "properties": {
          "id":{
            "type":"integer"
          },
          "title":{
            "type":"keyword"
          },
          "price":{
            "type":"double"
          },
          "created_at":{
            "type": "date"
          },
          "description":{
            "type": "text"
          }
        }
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    ||

    /

        @Test
        void test() throws IOException {
            CreateIndexRequest createIndexRequest = new CreateIndexRequest("products"); //索引名
            //映射
            createIndexRequest.mapping("{\n" +
                    "    \"properties\": {\n" +
                    "      \"id\":{\n" +
                    "        \"type\":\"integer\"\n" +
                    "      },\n" +
                    "      \"title\":{\n" +
                    "        \"type\":\"keyword\"\n" +
                    "      },\n" +
                    "      \"price\":{\n" +
                    "        \"type\":\"double\"\n" +
                    "      },\n" +
                    "      \"created_at\":{\n" +
                    "        \"type\": \"date\"\n" +
                    "      },\n" +
                    "      \"description\":{\n" +
                    "        \"type\": \"text\"\n" +
                    "      }\n" +
                    "    }\n" +
                    "  }", XContentType.JSON);
            
            CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
            System.out.println(createIndexResponse.isAcknowledged()); //是否创建成功
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    1.4.2删除索引

     	@Test
        void test() throws IOException {
            AcknowledgedResponse response = restHighLevelClient.indices().delete(new DeleteIndexRequest("products"), RequestOptions.DEFAULT);
            System.out.println(response.isAcknowledged()); //判断是否成功 
       }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    1.4.2插入文档

    ​ 插入文档也可以像创建索引一样,在kibana中语句写好,然后直接复制到程序中运行,但是我们一般不那样做,我们一般都是将对象进行JSON序列化,然后进行插入。

    定义实体类

    @JSONField注解,当序列化对象或者反序列化时,使用配置的属性名

    public class Product {
    
        private Integer id;
    
        private String title;
    
        private Double price;
    
        @JSONField(name = "create_at", format = "yyyy-MM-dd hh:mm:ss")
        private Date createAt;
    
        private String description;
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    插入文档

        @Test
        void x() throws IOException {
            //创建一个IndexRequest(),传入的是索引名
            IndexRequest request = new IndexRequest("products");
            
            Product product = new Product();
            product.setId(34);
            product.setDescription("速度");
            product.setPrice(12.32d);
            product.setCreateAt(new Date());
            
            //序列化对象为JSON
            String data = JSONObject.toJSONString(product);
            
            //指定_id进行插入,数据格式为JSON
            request.id("34").source(data, XContentType.JSON);
            IndexResponse response = restHighLevelClient.index(request, RequestOptions.DEFAULT);
            //获取响应结果
            System.out.println(response.getResult());
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    1.4.3根据_id删除文档

    	@Test
        void del() throws IOException {
            //操作products索引
            DeleteRequest deleteRequest = new DeleteRequest("products");
            deleteRequest.id("1"); //删除_id为1的
            DeleteResponse response = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
            //获取结果
            System.out.println(response.getResult());
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    1.4.4根据_id修改数据

       //有哪个字段就更新哪个字段,会保留原始字段
        @Test
        void update() throws IOException {
            UpdateRequest updateRequest = new UpdateRequest("products", "2");
            Product product = new Product();
            product.setDescription("凯文杜兰特");
            updateRequest.doc(JSONObject.toJSONString(product), XContentType.JSON);
            UpdateResponse response = restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);
            System.out.println(response.getResult());
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    1.4.5根据_id查询数据

        @Test
        void getById() throws IOException {
            GetRequest request = new GetRequest("products");
            request.id("2");
            GetResponse response = restHighLevelClient.get(request, RequestOptions.DEFAULT);
            String source = response.getSourceAsString(); //获取JSON数据
            //反序列化
            Product product = JSONObject.parseObject(source, Product.class);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    1.4.6批量插入数据

        @Test
        void batchInsert() throws IOException {
            //数据集合
            List<Product> products = new ArrayList();
    
            //批量请求
            BulkRequest bulkRequest = new BulkRequest();
    
            //遍历集合
            for (Product product : products) {
                IndexRequest request = new IndexRequest("products"); //添加请求
                request.id(product.getId().toString()); //指定id
                request.source(JSONObject.toJSONString(product), XContentType.JSON); //加入数据
                bulkRequest.add(request); //将配置好的添加请求加入到bulkRequest中
            }
    
            //发送请求
            BulkResponse responses = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
    
            //获取响应
            for (BulkItemResponse respons : responses) {
                BulkItemResponse.Failure failure = respons.getFailure();
                if (failure == null) {
                    //成功
                    System.out.println(respons.getId()); //成功的_id
                } else {
                    //失败
                    System.out.println(respons.getId()); //失败的id
                }
            }
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31

    1.4.7批量删除数据

        @Test
        void batchDel() throws IOException {
            List<Product> list = new ArrayList<>();
    
            BulkRequest bulkRequest = new BulkRequest();
    
            for (Product product : list) {
                DeleteRequest deleteRequest = new DeleteRequest("product"); //指定索引
                deleteRequest.id(product.getId().toString()); //指定删除的id
                bulkRequest.add(deleteRequest); //添加到批量请求中
            }
            //发送批量删除数据请求
            BulkResponse responses = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
    
            //获取响应
            for (BulkItemResponse respons : responses) {
                BulkItemResponse.Failure failure = respons.getFailure();
                if (failure == null) {
                    //成功
                    System.out.println(respons.getId()); //成功的_id
                } else {
                    //失败
                    System.out.println(respons.getId()); //失败的id
                }
            }
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    1.5高级查询

    1.5.1查询所有

        @Test
        void queryAll() throws IOException {
            //创建一个查询请求
            SearchRequest searchRequest = new SearchRequest();
            //查询的索引名
            searchRequest.indices("products");
            
            //构建一个查询条件
            SearchSourceBuilder builder = new SearchSourceBuilder();
            
            //构造条件
            builder.query(QueryBuilders.matchAllQuery());
            
            searchRequest.source(builder);
            
            //发送请求
            SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            
            //获取数据
            for (SearchHit hit : response.getHits().getHits()) {
                Product product = JSONObject.parseObject(hit.getSourceAsString(), Product.class);
                System.out.println(product);
            }
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    1.5.2term查询

        @Test
        void termQ() throws IOException {
            //创建一个查询请求
            SearchRequest searchRequest = new SearchRequest();
    
            //查询的索引名
            searchRequest.indices("products");
    
            //构建一个查询
            SearchSourceBuilder builder = new SearchSourceBuilder();
    
            //构造条件 term查询
            builder.query(QueryBuilders.termQuery("description", "杜兰特"));
            searchRequest.source(builder);
    
            //发送请求
            SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
    
            //获取数据
            for (SearchHit hit : response.getHits().getHits()) {
                Product product = JSONObject.parseObject(hit.getSourceAsString(), Product.class);
                System.out.println(product);
            }
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    1.5.3分页查询

         @Test
        void pageQ() throws IOException {
            //创建一个查询请求
            SearchRequest searchRequest = new SearchRequest();
    
            //查询的索引名
            searchRequest.indices("products");
    
            //构建一个查询
            SearchSourceBuilder builder = new SearchSourceBuilder();
    
            //构造条件
            builder.query(QueryBuilders.matchAllQuery());
            
            //需要第几页的数据
            int pageNo = 1;
            //一页的记录数
            int pageSize = 2;
            int from = (pageNo - 1) * pageSize;
            
            //构建分页
            builder.from(from);
            builder.size(pageSize);
    
            searchRequest.source(builder);
            
    
            //发送请求
            SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
    
            //获取数据
            for (SearchHit hit : response.getHits().getHits()) {
                Product product = JSONObject.parseObject(hit.getSourceAsString(), Product.class);
                System.out.println(product);
            }
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36

    1.5.4排序查询

    builder.sort("price", SortOrder.DESC);
    
    • 1

    1.5.5获取指定内容

    //如果需要的属性很少,那么就使用includes,excludes设为空
    //如果需要的属性很多,那么就使用excludes,includes设为空
    String[] includes = {"field1", "field2"};
    String[] excludes = {"field3", "field4"};
    builder.fetchSource(includes, excludes);
    
    • 1
    • 2
    • 3
    • 4
    • 5

    1.5.6should匹配

    	BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.should(QueryBuilders.matchQuery("price", 23.1));
        boolQueryBuilder.should(QueryBuilders.matchQuery("price", 22.3));
        builder.query(boolQueryBuilder);		
    
    • 1
    • 2
    • 3
    • 4

    1.5.7更多参考

    参考1

    参考2

  • 相关阅读:
    STM32的ADC用法-CubeMX
    Compose 官方课程启动!把握机会学习并成为 Android 专业开发者
    B+树索引(9)之索引应用排序的注意事项
    io流简单介绍
    【c++百日刷题计划】 ———— DAY20,刷题百天,养成刷题好习惯
    Linux安装Jenkins
    jvm06
    LeetCode 48题: 旋转图像
    C# I/O流: FileStream
    第一章 基础算法(二)
  • 原文地址:https://blog.csdn.net/qq_46312987/article/details/125471573