温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Spring Boot如何集成Elasticsearch模块实现简单查询功能

发布时间:2022-06-14 09:58:18 来源:亿速云 阅读:174 作者:iii 栏目:开发技术

这篇文章主要介绍“Spring Boot如何集成Elasticsearch模块实现简单查询功能”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“Spring Boot如何集成Elasticsearch模块实现简单查询功能”文章能帮助大家解决问题。

    背景

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

    系统集成

    引入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模块实现简单查询功能”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注亿速云行业资讯频道,小编每天都会为大家更新不同的知识点。

    向AI问一下细节

    免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

    AI