目录
  • 背景
  • 系统集成
    • 引入jar包
    • application.yml文件中添加ES配置
    • 创建文档实体
  • 接口实现
    • 具体实现
      • 基础查询
      • 新增文档
      • 请求参数
      • Controller实现
      • 返回结果
      • 修改文档
      • 通过id查询文档信息
      • Controller实现
      • 删除文档
      • Controller实现
      • 分页查询
      • Controller实现
      • 返回结果
      • 模糊查询
      • Controller实现
      • 范围查询
      • Controller实现
    • 总结

      背景

      项目中我们经常会用搜索功能,普通的搜索我们可以用一个SQL的like也能实现匹配,但是搜索的核心需求是全文匹配,对于全文匹配,数据库的索引是根本派不上用场的,那只能全表扫描。全表扫描的速度已经非常慢了,还需要在每条记录上做全文匹配,一个字一个字的比对,导致查询的数据更慢。所以,使用数据来做搜索,性能上完全没法满足要求。所以我们需要采用Elasticsearch来实现检索,本文将介绍SpringBoot如何集成Elasticsearch?

      系统集成

      引入jar包

      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-web</artifactId>
      </dependency>
      
       <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>

      application.yml文件中添加ES配置

        elasticsearch:
          rest:
            uris: http://localhost:9200 

      注意:不同的ES版本,引入jar包和配送属性文件的方式不同,本文采用的是Spring Boot 2.2+Elasticsearch7.0的版本。

      创建文档实体

      @Document(indexName = "product", createIndex = true)
      public class Product implements Serializable
      {
          private static final long serialVersionUID = -2408117939493050954L;
      
          @Id
          @Field(type = FieldType.Text)
          private String id;
      
          @Field(type = FieldType.Text)
          private String skuNo;
      
          @Field(type = FieldType.Text)
          private String tilte;
      
          @Field(type = FieldType.Double)
          private BigDecimal price;
          
          @Field(type = FieldType.Date, format = DateFormat.basic_date_time)
          private Date createDate;
        }  

      说明:

      • indexName:索引的名称
      • createIndex:ture表示如果不存在,则创建
      • @Id:索引id
      • @Field:type字段的类型,format:查询出时间格式化类型。

      接口实现

      public interface EsProductRepository extends ElasticsearchRepository<Product,String>
      {
          List<Product> findByskuNoAndTilte(String sku,String title);
      }

      说明:集成ElasticsearchRepository接口,采用的是JPA的方式实现,JPA默认提供了相关的接口实现。

      具体实现

      Elasticsearch的实现分为基础查询和DSL查询。

      基础查询

      基础查询主要包含的CRUD查询,以及一些模糊、范围查询等。

      新增文档

      请求参数

      {
           "id":"5",
           "skuNo":"sku0005",
           "tilte":"红楼梦",
            "price":"93.37",
            "createDate":"1514736000000"
      }

      说明:date类型传入的参数为long类型。

      Controller实现

       @PostMapping("/addProduct")
          public Result addProduct(@RequestBody Product product) 
          {
              esProductRepository.save(product);
              Result result = new Result();
              result.setCode(200);
              result.setData(product);
              return result;
          }

      返回结果

      {
          "data": {
              "id": "5",
              "skuNo": "sku0005",
              "tilte": "红楼梦",
              "price": 93.37,
              "createDate": "2017-12-31T16:00:00.000+00:00"
          },
          "code": 200,
          "msg": null
      }

      修改文档

      修改与新增基本相同,唯一区别为:请求参数传入的Id,如果存在则为修改,否则为新增。

      通过id查询文档信息

      Controller实现

         @GetMapping("/getProductById")
          public Result getProductById(@RequestParam String id) {
              Optional<Product> product = esProductRepository.findById(id);
              return Result.success(product);
          }

      删除文档

      Controller实现

          @PostMapping("/deleteById")
          public Result deleteById(@RequestParam String id) 
          {
              return  Result.success(null);
          }

      分页查询

      Controller实现

       @GetMapping("/getPageList")
          public Result getPageList(@RequestParam int pageNum,@RequestParam int pageSize)
          {
              Pageable pageable = PageRequest.of(pageNum, pageSize);
              Page<Product> pageList= esProductRepository.findAll(pageable);
              return Result.success(pageList);
          }

      返回结果

      {
          "data": {
              "content": [
                  {
                      "id": "1",
                      "skuNo": "p0001",
                      "tilte": null,
                      "price": 99.9,
                      "createDate": null
                  },
                  {
                      "id": "3",
                      "skuNo": "p0002",
                      "tilte": null,
                      "price": 99.8,
                      "createDate": null
                  },
                  {
                      "id": "4",
                      "skuNo": "p0004",
                      "tilte": null,
                      "price": 110,
                      "createDate": null
                  },
                  {
                      "id": "L1zuVYEBuycvlc7eiQ7_",
                      "skuNo": "sku0001",
                      "tilte": "水浒传",
                      "price": 93.37,
                      "createDate": "1970-01-01T05:37:00.611+00:00"
                  },
                  {
                      "id": "5",
                      "skuNo": "sku0005",
                      "tilte": "红楼梦",
                      "price": 93.37,
                      "createDate": "2017-12-31T16:00:00.000+00:00"
                  }
              ],
              "pageable": {
                  "sort": {
                      "sorted": false,
                      "unsorted": true,
                      "empty": true
                  },
                  "offset": 0,
                  "pageSize": 5,
                  "pageNumber": 0,
                  "paged": true,
                  "unpaged": false
              },
              "aggregations": null,
              "scrollId": null,
              "maxScore": 1.0,
              "totalPages": 1,
              "totalElements": 5,
              "number": 0,
              "size": 5,
              "sort": {
                  "sorted": false,
                  "unsorted": true,
                  "empty": true
              },
              "numberOfElements": 5,
              "first": true,
              "last": true,
              "empty": false
          },
          "code": 200,
          "msg": null
      }

      说明:

      • totalPages:总页数
      • totalElements:总记录数

      模糊查询

      Controller实现

         @GetMapping("/findByTilteLike")
          public Result findByTilteLike(@RequestParam String key) {
              List<Product> products = esProductRepository.findByTilteLike(key);
              return Result.success(products);
          }

      说明:模糊查询通过findByxxlike

      范围查询

      范围查询通常是指>、< >= <=等

      Controller实现

        @GetMapping("/findByPriceGreaterThanEqual")
          public Result findByPriceGreaterThanEqual(@RequestParam Double price) {
              List<Product> products = esProductRepository.findByPriceGreaterThanEqual(price);
              return Result.success(products);
          }

      说明:范围查询通过findByxxGreaterThanEqual

      • 大于:GreaterThan
      • 大于等于:GreaterThanEqual
      • 小于:LessThan
      • 小于等于:LessThanEqual

      总结

      本文讲解了Spring Boot集成Elasticsearch采用的是ES模板的方式实现基础查询,关于相关的高级查询将在一下章进行讲解,如有疑问请随时反馈。

      声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。