水生的网络日志 水生的网络日志
首页
  • 前言
  • Java核心
  • 企业级开发
  • 数据库
  • 计算机基础
  • 求职面试
  • 技术文档
  • GitHub技巧
  • Nodejs
  • 博客搭建
  • 技术文档
  • GitHub技巧
  • Nodejs
  • 博客搭建
  • 分类
  • 标签
  • 归档
关于
GitHub (opens new window)

水生

记录我的所思、所学、所想
首页
  • 前言
  • Java核心
  • 企业级开发
  • 数据库
  • 计算机基础
  • 求职面试
  • 技术文档
  • GitHub技巧
  • Nodejs
  • 博客搭建
  • 技术文档
  • GitHub技巧
  • Nodejs
  • 博客搭建
  • 分类
  • 标签
  • 归档
关于
GitHub (opens new window)
  • 前言

  • Java核心

  • 企业级开发

    • Spring Boot开发

      • 创建Maven父子项目
      • Spring Boot整合MyBatis
      • Spring Boot整合Swagger
      • Spring Boot整合Redis实现缓存验证码
      • Spring Boot整合Spring Sercurity和JWT
      • Spring Boot整合Spring Task实现定时任务
      • Spring Boot整合ElasticSearch实现商品搜索
        • 项目使用框架介绍
          • Elasticsearch
          • Elasticsearch的安装和使用
          • Spring Data Elasticsearch
          • 常用注解
          • @Document
          • @Id
          • @Field
          • Sping Data方式的数据操作
          • 继承ElasticsearchRepository接口可以获得常用的数据操作方法
          • 可以使用衍生查询
          • 使用@Query注解可以用Elasticsearch的DSL语句进行查询
        • 项目使用表说明
        • 整合Elasticsearch实现商品搜索
          • 在pom.xml中添加相关依赖
          • 修改Elasticsearch版本
          • 添加商品文档对象EsProduct
          • 添加EsProductRepository接口用于操作Elasticsearch
          • 添加EsProductService接口
          • 添加EsProductService接口的实现类EsProductServiceImpl
          • 添加EsProductController定义接口
        • 进行接口测试
          • 将数据库中数据导入到Elasticsearch
          • 进行商品搜索
        • 思维导图
      • Spring Boot整合MongoDB实现文档操作
      • Spring Boot整合RabbitMQ实现延迟消息
    • Spring Cloud开发

  • 数据库

  • 计算机基础

  • 求职面试

  • 知识库
  • 企业级开发
  • Spring Boot开发
水生
2020-01-07
目录

Spring Boot整合ElasticSearch实现商品搜索

本文主要介绍商城业务中整合Elasticsearch的过程,以实现商品信息在Elasticsearch中的导入、查询、修改、删除为例。

# 项目使用框架介绍

Tips:本文ES环境主要通过Docker来安装和使用。

# Elasticsearch

Elasticsearch 是一个分布式、可扩展、实时的搜索与数据分析引擎。 它能从项目一开始就赋予你的数据以搜索、分析和探索的能力,可用于实现全文搜索和实时数据统计。

# Elasticsearch的安装和使用

  1. docker的安装和使用参考官网 (opens new window)吗,打开Docker Hub (opens new window)拉取需要版本的ES版本镜像
docker pull elasticsearch:7.14.2
1
  1. 启动ES,由于ES的启动后需要占用大量内存,因此需要使用参数-e ES_JAVA_OPTS="-Xms64m -Xmx512m"来限制内存大小,可以通过指令docker stats查看镜像内存使用情况
docker run -d --name elasticsearch -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" -e ES_JAVA_OPTS="-Xms64m -Xmx512m"  elasticsearch:7.14.2
1

通过crul localhost:9200出现以下界面,表示启动成功

image-20220110151548241
  1. 安装中文分词插件,启动镜像后,使用命令docker exec -it elasticsearch /bin/bash进入镜像,然后在\bin目录下执行以下命令:
elasticsearch-plugin install https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v7.14.2/elasticsearch-analysis-ik-7.14.2.zip
1

安装成功截图如下:

image-20220110151812750
  1. 在Docker Hub (opens new window)搜索Kibana,拉取Kibana镜像
docker pull kibana:7.14.2
1

⚠️注意:这里插件以及Kibana的版本都需要和ES的版本一致

  1. 启动Kibana,并连接到ES服务器上
docker run -d -p 5601:5601 --name kibana --link elasticsearch:elasticsearch docker.io/kibana:7.14.2
1
  1. 访问http://localhost:5601 (opens new window) 即可打开Kibana的用户界面

image-20220110151956546


# Spring Data Elasticsearch

Spring Data Elasticsearch是Spring提供的一种以Spring Data风格来操作数据存储的方式,它可以避免编写大量的样板代码。

# 常用注解

# @Document
//标示映射到Elasticsearch文档上的领域对象
public @interface Document {
  //索引库名次,mysql中数据库的概念
    String indexName();
  //文档类型,mysql中表的概念
    String type() default "";
  //默认分片数
    short shards() default 5;
  //默认副本数量
    short replicas() default 1;

}
1
2
3
4
5
6
7
8
9
10
11
12
# @Id
//表示是文档的id,文档可以认为是mysql中表行的概念
public @interface Id {
}Copy to clipboardErrorCopied
1
2
3
# @Field
public @interface Field {
  //文档中字段的类型
    FieldType type() default FieldType.Auto;
  //是否建立倒排索引
    boolean index() default true;
  //是否进行存储
    boolean store() default false;
  //分词器名次
    String analyzer() default "";
}Copy to clipboardErrorCopied
//为文档自动指定元数据类型
public enum FieldType {
    Text,//会进行分词并建了索引的字符类型
    Integer,
    Long,
    Date,
    Float,
    Double,
    Boolean,
    Object,
    Auto,//自动判断字段类型
    Nested,//嵌套对象类型
    Ip,
    Attachment,
    Keyword//不会进行分词建立索引的类型
}Copy to clipboardErrorCopied
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

# Sping Data方式的数据操作

# 继承ElasticsearchRepository接口可以获得常用的数据操作方法

img

# 可以使用衍生查询

在接口中直接指定查询方法名称便可查询,无需进行实现,如商品表中有商品名称、标题和关键字,直接定义以下查询,就可以对这三个字段进行全文搜索。

    /**
     * 搜索查询
     *
     * @param name              商品名称
     * @param subTitle          商品标题
     * @param keywords          商品关键字
     * @param page              分页信息
     * @return
     */
    Page<EsProduct> findByNameOrSubTitleOrKeywords(String name, String subTitle, String keywords, Pageable page);Copy to clipboardErrorCopied
1
2
3
4
5
6
7
8
9
10

在idea中直接会提示对应字段

img

# 使用@Query注解可以用Elasticsearch的DSL语句进行查询
@Query("{"bool" : {"must" : {"field" : {"name" : "?0"}}}}")
Page<EsProduct> findByName(String name,Pageable pageable);Copy to clipboardErrorCopied
1
2

# 项目使用表说明

  • pms_product:商品信息表
  • pms_product_attribute:商品属性参数表
  • pms_product_attribute_value:存储产品参数值的表

# 整合Elasticsearch实现商品搜索

# 在pom.xml中添加相关依赖

        <!--Elasticsearch相关依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>
1
2
3
4
5

# 修改Elasticsearch版本

修改application.yml文件,在spring节点下添加Elasticsearch相关配置。

        <!--自定义es版本依赖,保证和本地es版本一致,以防出现莫名奇妙的问题-->
        <elasticsearch.version>7.14.2</elasticsearch.version>
1
2

# 添加商品文档对象EsProduct

不需要中文分词的字段设置成@Field(type = FieldType.Keyword)类型,需要中文分词的设置成@Field(analyzer = "ik_max_word",type = FieldType.Text)类型。

package com.sds.elasticsearch.nosql.elasticsearch.document;

import com.sds.elasticsearch.entity.PmsProductAttributeValue;
import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.List;

/**
 * @description: 搜索商品中的信息
 * @author: shuds
 * @date: 2022/1/10
 **/
@Data
@Document(indexName = "pms")
public class EsProduct implements Serializable {
    private static final long serialVersionUID = -1L;
    @Id
    private Long id;
    @Field(type = FieldType.Keyword)
    private String productSn;
    private Long brandId;
    @Field(type = FieldType.Keyword)
    private String brandName;
    private Long productCategoryId;
    @Field(type = FieldType.Keyword)
    private String productCategoryName;
    private String pic;
    @Field(analyzer = "ik_max_word",type = FieldType.Text)
    private String name;
    @Field(analyzer = "ik_max_word",type = FieldType.Text)
    private String subTitle;
    @Field(analyzer = "ik_max_word",type = FieldType.Text)
    private String keywords;
    private BigDecimal price;
    private Integer sale;
    private Integer newStatus;
    private Integer recommandStatus;
    private Integer stock;
    private Integer promotionType;
    private Integer sort;
    @Field(type =FieldType.Nested)
    private List<PmsProductAttributeValue> attrValueList;
}

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
37
38
39
40
41
42
43
44
45
46
47
48
49
50

# 添加EsProductRepository接口用于操作Elasticsearch

继承ElasticsearchRepository接口,这样就拥有了一些基本的Elasticsearch数据操作方法,同时定义了一个衍生查询方法。

package com.sds.elasticsearch.nosql.elasticsearch.repository;

import com.sds.elasticsearch.nosql.elasticsearch.document.EsProduct;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

/**
 * @description: 商品ES操作类
 * @author: shuds
 * @date: 2022/1/12
 **/
public interface EsProductRepository extends ElasticsearchRepository<EsProduct, Long> {
    /**
     * 搜索查询
     *
     * @param name              商品名称
     * @param subTitle          商品标题
     * @param keywords          商品关键字
     * @param page              分页信息
     * @return
     */
    Page<EsProduct> findByNameOrSubTitleOrKeywords(String name, String subTitle, String keywords, Pageable page);
}

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

# 添加EsProductService接口

package com.sds.elasticsearch.service;

import org.springframework.data.domain.Page;
import com.sds.elasticsearch.nosql.elasticsearch.document.EsProduct;

import java.util.List;

/**
 * @description: 商品搜索管理Service
 * @author: shuds
 * @date: 2022/1/12
 **/
public interface EsProductService {
    /**
     * 从数据库中导入所有商品到ES
     */
    int importAll();

    /**
     * 根据id删除商品
     */
    void delete(Long id);

    /**
     * 根据id创建商品
     */
    EsProduct create(Long id);

    /**
     * 批量删除商品
     */
    void delete(List<Long> ids);

    /**
     * 根据关键字搜索名称或者副标题
     */
    Page<EsProduct> search(String keyword, Integer pageNum, Integer pageSize);
}

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
37
38
39

# 添加EsProductService接口的实现类EsProductServiceImpl

package com.sds.elasticsearch.service.impl;

import com.sds.elasticsearch.mapper.PmsProductMapper;
import com.sds.elasticsearch.nosql.elasticsearch.document.EsProduct;
import com.sds.elasticsearch.nosql.elasticsearch.repository.EsProductRepository;
import com.sds.elasticsearch.service.EsProductService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @description: 商品搜索管理Service实现类
 * @author: shuds
 * @date: 2022/1/12
 **/
@Service
public class EsProductServiceImpl implements EsProductService {
    private static final Logger LOGGER = LoggerFactory.getLogger(EsProductServiceImpl.class);
    @Autowired
    private PmsProductMapper productMapper;
    @Autowired
    private EsProductRepository productRepository;

    @Override
    public int importAll() {
        List<EsProduct> esProductList = productMapper.getAllEsProductList(null);
        Iterable<EsProduct> esProductIterable = productRepository.saveAll(esProductList);
        Iterator<EsProduct> iterator = esProductIterable.iterator();
        int result = 0;
        while (iterator.hasNext()) {
            result++;
            iterator.next();
        }
        return result;
    }

    @Override
    public void delete(Long id) {
        productRepository.deleteById(id);
    }

    @Override
    public EsProduct create(Long id) {
        EsProduct result = null;
        List<EsProduct> esProductList = productMapper.getAllEsProductList(id);
        if (esProductList.size() > 0) {
            EsProduct esProduct = esProductList.get(0);
            result = productRepository.save(esProduct);
        }
        return result;
    }

    @Override
    public void delete(List<Long> ids) {
        if (!CollectionUtils.isEmpty(ids)) {
            List<EsProduct> esProductList = new ArrayList<>();
            for (Long id : ids) {
                EsProduct esProduct = new EsProduct();
                esProduct.setId(id);
                esProductList.add(esProduct);
            }
            productRepository.deleteAll(esProductList);
        }
    }

    @Override
    public Page<EsProduct> search(String keyword, Integer pageNum, Integer pageSize) {
        Pageable pageable = PageRequest.of(pageNum, pageSize);
        return productRepository.findByNameOrSubTitleOrKeywords(keyword, keyword, keyword, pageable);
    }

}

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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82

# 添加EsProductController定义接口

package com.sds.elasticsearch.controller;

import com.sds.elasticsearch.common.api.CommonPage;
import com.sds.elasticsearch.common.api.CommonResult;
import com.sds.elasticsearch.nosql.elasticsearch.document.EsProduct;
import com.sds.elasticsearch.service.EsProductService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @description: 搜索商品管理Controller
 * @author: shuds
 * @date: 2022/1/12
 **/

@Api(tags = "EsProductController", description = "搜索商品管理")
@RestController
@RequestMapping("/esProduct")
public class EsProductController {
    @Autowired
    private EsProductService esProductService;

    @ApiOperation(value = "导入所有数据库中商品到ES")
    @RequestMapping(value = "/importAll", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<Integer> importAllList() {
        int count = esProductService.importAll();
        return CommonResult.success(count);
    }

    @ApiOperation(value = "根据id删除商品")
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<Object> delete(@PathVariable Long id) {
        esProductService.delete(id);
        return CommonResult.success(null);
    }

    @ApiOperation(value = "根据id批量删除商品")
    @RequestMapping(value = "/delete/batch", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<Object> delete(@RequestParam("ids") List<Long> ids) {
        esProductService.delete(ids);
        return CommonResult.success(null);
    }

    @ApiOperation(value = "根据id创建商品")
    @RequestMapping(value = "/create/{id}", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<EsProduct> create(@PathVariable Long id) {
        EsProduct esProduct = esProductService.create(id);
        if (esProduct != null) {
            return CommonResult.success(esProduct);
        } else {
            return CommonResult.failed();
        }
    }

    @ApiOperation(value = "简单搜索")
    @RequestMapping(value = "/search/simple", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<CommonPage<EsProduct>> search(@RequestParam(required = false) String keyword,
                                                      @RequestParam(required = false, defaultValue = "0") Integer pageNum,
                                                      @RequestParam(required = false, defaultValue = "5") Integer pageSize) {
        Page<EsProduct> esProductPage = esProductService.search(keyword, pageNum, pageSize);
        return CommonResult.success(CommonPage.restPage(esProductPage.toList()));
    }
}
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73

# 进行接口测试

# 将数据库中数据导入到Elasticsearch

image-20220112194724449

image-20220112194740604

# 进行商品搜索

image-20220112194836211

image-20220112194819449

# 思维导图

image-20220110153106267 使用客户端整合Spring Boot,参考[[【框架学习-ES】Spring Boot整合ElasticSearch 7.14.X]]

编辑 (opens new window)
#Spring Boot#Elasticsearch
上次更新: 2022/11/26, 22:18:38
Spring Boot整合Spring Task实现定时任务
Spring Boot整合MongoDB实现文档操作

← Spring Boot整合Spring Task实现定时任务 Spring Boot整合MongoDB实现文档操作→

最近更新
01
基于微服务案例的Maven实战
05-08
02
使用Seata彻底解决Spring Cloud中的分布式事务问题
11-26
03
Spring Boot整合RabbitMQ实现延迟消息
11-26
更多文章>
Theme by Vdoing | Copyright © 2019-2022 水生 | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式