SpringBoot 整合 Elasticsearch 实现商品搜索

news2024/9/22 16:42:24

一、Spring Data Elasticsearch

Spring Data Elasticsearch 简介

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

常用注解

常用注解说明如下:

注解名称

作用

参数说明

@Document

用于标识映射到Elasticsearch文档上的领域对象

indexName:索引库的名字,MySQL中数据库的概念

@Setting

ES的配置注解

shards:默认分片数
replicas:默认副本数量

@Id

用于标识文档的ID,文档可以认为是MySQL中表行的概念

无参数

@Field

用于标识文档中的字段,可以认为是MySQL中列的概念

type:文档中字段的类型
index:是否建立倒排索引
store:是否进行存储
analyzer:分词器的名称

其中常用的FieldType类型有如下几种:

public enum FieldType {
	Auto("auto"), //自动判断字段类型
	Text("text"), //会进行分词并建了索引的字符类型
	Keyword("keyword"), //不会进行分词建立索引的类型
	Long("long"), //
	Integer("integer"), //
	Short("short"), //
	Byte("byte"), //
	Double("double"), //
	Float("float"), //
	Date("date"), //
	Boolean("boolean"), //
	Object("object"), //
	Nested("nested"), //嵌套对象类型
	Ip("ip"), //
}

 Spring Data方式的数据操作

  • 继承ElasticsearchRepository接口可以获得常用的数据操作方法;(Ctrl + F12)

  • 可以使用衍生查询,在接口中直接指定查询方法名称便可查询,无需进行实现,如商品表中有商品名称、标题和关键字,直接定义以下查询,就可以对这三个字段进行全文搜索。
/**
 * @description 商品ES操作类
 */
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);
}
  • 在编写衍生查询方法时,IDEA会提示对应字段,更多关键字可以参考衍生查询关键字对照表

衍生查询关键字对照表

Keyword

Sample

Elasticsearch Query String

And

findByNameAndPrice

{ "query" : { "bool" : { "must" : [ { "query_string" : { "query" : "?", "fields" : [ "name" ] } }, { "query_string" : { "query" : "?", "fields" : [ "price" ] } } ] } }}

Or

findByNameOrPrice

{ "query" : { "bool" : { "should" : [ { "query_string" : { "query" : "?", "fields" : [ "name" ] } }, { "query_string" : { "query" : "?", "fields" : [ "price" ] } } ] } }}

Is

findByName

{ "query" : { "bool" : { "must" : [ { "query_string" : { "query" : "?", "fields" : [ "name" ] } } ] } }}

Not

findByNameNot

{ "query" : { "bool" : { "must_not" : [ { "query_string" : { "query" : "?", "fields" : [ "name" ] } } ] } }}

Between

findByPriceBetween

{ "query" : { "bool" : { "must" : [ {"range" : {"price" : {"from" : ?, "to" : ?, "include_lower" : true, "include_upper" : true } } } ] } }}

LessThan

findByPriceLessThan

{ "query" : { "bool" : { "must" : [ {"range" : {"price" : {"from" : null, "to" : ?, "include_lower" : true, "include_upper" : false } } } ] } }}

LessThanEqual

findByPriceLessThanEqual

{ "query" : { "bool" : { "must" : [ {"range" : {"price" : {"from" : null, "to" : ?, "include_lower" : true, "include_upper" : true } } } ] } }}

GreaterThan

findByPriceGreaterThan

{ "query" : { "bool" : { "must" : [ {"range" : {"price" : {"from" : ?, "to" : null, "include_lower" : false, "include_upper" : true } } } ] } }}

GreaterThanEqual

findByPriceGreaterThan

{ "query" : { "bool" : { "must" : [ {"range" : {"price" : {"from" : ?, "to" : null, "include_lower" : true, "include_upper" : true } } } ] } }}

Before

findByPriceBefore

{ "query" : { "bool" : { "must" : [ {"range" : {"price" : {"from" : null, "to" : ?, "include_lower" : true, "include_upper" : true } } } ] } }}

After

findByPriceAfter

{ "query" : { "bool" : { "must" : [ {"range" : {"price" : {"from" : ?, "to" : null, "include_lower" : true, "include_upper" : true } } } ] } }}

Like

findByNameLike

{ "query" : { "bool" : { "must" : [ { "query_string" : { "query" : "?*", "fields" : [ "name" ] }, "analyze_wildcard": true } ] } }}

StartingWith

findByNameStartingWith

{ "query" : { "bool" : { "must" : [ { "query_string" : { "query" : "?*", "fields" : [ "name" ] }, "analyze_wildcard": true } ] } }}

EndingWith

findByNameEndingWith

{ "query" : { "bool" : { "must" : [ { "query_string" : { "query" : "*?", "fields" : [ "name" ] }, "analyze_wildcard": true } ] } }}

Contains/Containing

findByNameContaining

{ "query" : { "bool" : { "must" : [ { "query_string" : { "query" : "?", "fields" : [ "name" ] }, "analyze_wildcard": true } ] } }}

In (when annotated as FieldType.Keyword)

findByNameIn(Collectionnames)

{ "query" : { "bool" : { "must" : [ {"bool" : {"must" : [ {"terms" : {"name" : ["?","?"]}} ] } } ] } }}

In

findByNameIn(Collectionnames)

{ "query": {"bool": {"must": [{"query_string":{"query": ""?" "?"", "fields": ["name"]}}]}}}

NotIn (when annotated as FieldType.Keyword)

findByNameNotIn(Collectionnames)

{ "query" : { "bool" : { "must" : [ {"bool" : {"must_not" : [ {"terms" : {"name" : ["?","?"]}} ] } } ] } }}

NotIn

findByNameNotIn(Collectionnames)

{"query": {"bool": {"must": [{"query_string": {"query": "NOT("?" "?")", "fields": ["name"]}}]}}}

True

findByAvailableTrue

{ "query" : { "bool" : { "must" : [ { "query_string" : { "query" : "true", "fields" : [ "available" ] } } ] } }}

False

findByAvailableFalse

{ "query" : { "bool" : { "must" : [ { "query_string" : { "query" : "false", "fields" : [ "available" ] } } ] } }}

OrderBy

findByAvailableTrueOrderByNameDesc

{ "query" : { "bool" : { "must" : [ { "query_string" : { "query" : "true", "fields" : [ "available" ] } } ] } }, "sort":[{"name":{"order":"desc"}}] }

Exists

findByNameExists

{"query":{"bool":{"must":[{"exists":{"field":"name"}}]}}}

IsNull

findByNameIsNull

{"query":{"bool":{"must_not":[{"exists":{"field":"name"}}]}}}

IsNotNull

findByNameIsNotNull

{"query":{"bool":{"must":[{"exists":{"field":"name"}}]}}}

IsEmpty

findByNameIsEmpty

{"query":{"bool":{"must":[{"bool":{"must":[{"exists":{"field":"name"}}],"must_not":[{"wildcard":{"name":{"wildcard":"*"}}}]}}]}}}

IsNotEmpty

findByNameIsNotEmpty

{"query":{"bool":{"must":[{"wildcard":{"name":{"wildcard":"*"}}}]}}}

  • 通过@Query注解可以使用Elasticsearch的原生DSL语句进行查询;
/**
 * @description 商品ES操作类
 */
public interface EsProductRepository extends ElasticsearchRepository<EsProduct, Long> {
    @Query("{"bool" : {"must" : {"field" : {"name" : " ? 0"}}}}")
    Page<EsProduct> findByName(String name, Pageable pageable);
}

二、项目使用表结构说明

  • 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>
  • 修改application.yml配置文件,在spring节点下添加Elasticsearch相关配置;
spring:
  data:
    elasticsearch:
      repositories:
        enabled: true # 开启ES仓库配置,自动为仓库接口生成实现类
  elasticsearch:
    uris: http://localhost:9200 # ES的连接地址及端口号

运行后可以验证一下 

实现商品搜索功能

  • 添加商品文档对象EsProduct,不需要中文分词的字段设置成Keyword类型,需要中文分词的设置成Text类型,并设置分词器为ik_max_word
/**
 * @description 搜索商品的信息
 */
@Data
@EqualsAndHashCode
@Document(indexName = "pms")
@Setting(shards = 1,replicas = 0)
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<EsProductAttributeValue> attrValueList;
}
  • 继承ElasticsearchRepository接口,这样就拥有了一些基本的Elasticsearch数据操作方法,同时定义了一个衍生查询方法;
/**
 * @description 商品ES操作类
 */
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);

}
  • 添加EsProductService,定义好ES的操作方法;
/**
 * @description 商品搜索管理Service
 */
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);

}
  • 添加EsProductService接口的实现类EsProductServiceImpl;
/**
 * @description 搜索商品管理Service实现类
 */
@Service
public class EsProductServiceImpl implements EsProductService {
    private static final Logger LOGGER = LoggerFactory.getLogger(EsProductServiceImpl.class);
    @Autowired
    private EsProductDao productDao;
    @Autowired
    private EsProductRepository productRepository;
    @Override
    public int importAll() {
        List<EsProduct> esProductList = productDao.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 = productDao.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);
    }

}
  • 添加EsProductController定义接口。
/**
 * @description 搜索商品管理Controller
 */
@Controller
@Api(tags = "EsProductController")
@Tag(name = "EsProductController", description = "搜索商品管理")
@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));
    }
}

商品导入与搜索演示

  • 运行项目,访问Swagger API文档,访问地址:http://localhost:8080/swagger-ui/

  • 通过/esProduct/importAll接口将数据库中的商品数据导入到Elasticsearch中;

  • 通过/esProduct/search/simple接口进行商品搜索。

得到的结果是:

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2037023.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Python面试宝典第34题:旋转图像

题目 给定一个n n的二维矩阵matrix表示一个图像&#xff0c;请你将图像顺时针旋转90度。 注意&#xff1a;你必须在原地旋转图像。这意味着&#xff0c;你需要直接修改输入的二维矩阵&#xff0c;而不能使用另一个矩阵来旋转图像。 示例 1&#xff1a; 输入&#xff1a;matri…

Spark SQL Catalyst工作流程

我们写的SQL语句&#xff0c;会经过一个优化器 (Catalyst)&#xff0c;转化为 RDD&#xff0c;交给集群执行。 而Catalyst在整个Spark 生态中的地位也是至关重要的。 SQL到RDD中间经过了一个Catalyst&#xff0c;它就是Spark SQL的核心&#xff0c;是针对Spark SQL语句执行过程…

【计算机网络】LVS四层负载均衡器

https://mobian.blog.csdn.net/article/details/141093263 https://blog.csdn.net/weixin_42175752/article/details/139966198 《高并发的哲学原理》 &#xff08;基本来自本书&#xff09; 《亿级流量系统架构设计与实战》 LVS 章文嵩博士创造 LVS(IPVS&#xff09; 章⽂嵩发…

Agile Modbus移植教程--基于GD32F103C8T6+RT-Thread+mdk5

主机移植 0.下载源码 开源地址:GitHub - loogg/agile_modbus 1.复制源码 1.2、目录结构 名称说明doc文档examples例子参考示例figures素材inc头文件移植需要src源代码移植需要util提供简单实用的组件移植需要 本次移植需要的有 参考demo 头文件 源码 从机辅助文件 2.添…

【中等】 猿人学web第一届 第5题 js混淆-乱码增强

请求流程 打开 调试工具&#xff0c;查看数据接口 https://match.yuanrenxue.cn/api/match/5 请求参数 请求参数携带了 page, m, f 3个字段&#xff0c; page为页数&#xff0c; m 为时间戳 像是 new Date().getTIme() 生成的 f 为时间戳 像是 Date.parse(new Date()) 生成的 …

Spring boot敏感参数加密配置

一&#xff0c;背景 在项目中很多参数会被配置到配置文件中&#xff0c;比如说密钥&#xff0c;用户名&#xff0c;数据库连接&#xff0c;账号密码之类的&#xff0c;如果用明文配置&#xff0c;会有一定的安全风险。为了减小风险&#xff0c;增加对敏感配置数据的加密配置。…

Gerrit 使用教程

一、Gerrit简介 Gerrit&#xff0c;一种开放源代码的代码审查软件&#xff0c;使用网页界面。利用网页浏览器&#xff0c;同一个团队的程序员&#xff0c;可以相互审阅彼此修改后的代码&#xff0c;决定是否能够提交&#xff0c;退回或是继续修改。它使用版本控制系统Git作为底…

LabVIEW光伏微网实验系统

开发了一个基于LabVIEW的光伏微网实验系统&#xff0c;系统主要服务于工程教育和技术研究&#xff0c;以提高学生对分布式电力系统的理解和操作能力。该实验系统能够模拟光伏微网的各种运行状态&#xff0c;包括能量的生成、存储和消费等&#xff0c;特别是在无电网状态下的独立…

Datawhale AI夏令营-大模型技术(微调)Task2打卡

1 输出结果要求 input&#xff1a;阅读文章本体与完成QAG的prompt target&#xff1a;题干、题目选项及答案 2 数据处理 2.1 Python 正则表达式 需要将文件中的数据读取出来&#xff0c;将语文数据与英语数据整理好后存储成可以微调的数据格式&#xff08;csv与jsonl类型&a…

el-checkbox 状态不更新

文章目录 数据处理代码片段 &#x1f330; 大概举例原因解决方法 - 深拷贝forceUpdate - 强制更新 今天遇到了checkbox不更新的问题&#xff0c;相同的功能在其他地方正常使用&#xff0c;有些地方不能用。数据处理代码片段 &#x1f330; 大概举例 从现有数据中过滤出新的数据…

MySQL学习[4] ——MySQL锁

四、MySQL锁 4.1 MySQL有哪些锁&#xff1f; 4.1.1 全局锁 全局锁就是**对整个数据库实例加锁&#xff0c;主要用于全库逻辑备份**等场景。 flush tables with read lock # 加全局锁unlock tables # 解锁加上全局&#xff08;读&#xff09;锁后&#xff0c;整个数据库都…

网络安全-第二阶段-linux操作系统01

一. linux介绍: windows,mac,linux都是由unix系统发展而来。 linux:类unix系统; 二. Centos系统的安装: 可以去清华大学开源软件镜像站下载: 输入ip addr: 可以看到自己电脑的ip地址; 1. ssh远程连接linux: 使用windows或者linux的物理机或者虚拟机都可以连接上它,…

MPU6050+OLED读取姿态角(超级细讲)

STM32F103C8T6读取陀螺仪MPU6050的角度数据&#xff0c;使用6050自带DMP库姿态解算出各个方向的角度&#xff0c;并使用OLED实时刷新显示&#xff0c;同时可以将数据通过串口发送到计算机&#xff0c;每一组数据50ms。本操作过程简单&#xff0c;方便移植&#xff0c;显示屏接P…

ppt中添加页码(幻灯片编号)及问题解决方案

在幻灯片母版中&#xff0c;选择插入 幻灯片编号 右下角显示幻灯片编号 问题一&#xff1a;母版中没有显示编号 原因可能是母版版式中没有设置显示&#xff0c;勾选即可。 问题二&#xff1a;子母版中没有显示幻灯片 将母版中的编号复制到子母版中。 问题三&#xff1a;应用…

Element-UI自学实践

概述 Element-UI 是由饿了么前端团队推出的一款基于 Vue.js 2.0 的桌面端 UI 组件库。它为开发者提供了一套完整、易用、美观的组件解决方案&#xff0c;极大地提升了前端开发的效率和质量。本文为自学实践记录&#xff0c;详细内容见 &#x1f4da; ElementUI官网 1. 基础组…

2024年7月文章一览

2024年7月编程人总共更新了5篇文章&#xff1a; 1.2024年6月文章一览 2.《Programming from the Ground Up》阅读笔记&#xff1a;p19-p48 3.《Programming from the Ground Up》阅读笔记&#xff1a;p49-p74 4.《Programming from the Ground Up》阅读笔记&#xff1a;p75…

深入理解Kafka核心设计与实践原理_03

深入理解Kafka核心设计与实践原理_03 03_消费者3.1消费者与消费者组3.2客户端开发3.2.1 必要的参数配置3.2.2 订阅主题与分区 草稿 03_消费者 与生产者对应的是消费者&#xff0c;应用程序可以通过KafkaConsumer来订阅主题&#xff0c;并从订阅的主题中拉取消息。不过在使用Ka…

Redis17-服务端优化

目录 持久化配置 慢查询 什么是慢查询 如何查看慢查询 命令及安全配置 内存配置 集群优化 持久化配置 Redis的持久化虽然可以保证数据安全&#xff0c;但也会带来很多额外的开销&#xff0c;因此持久化请遵循下列建议&#xff1a; 用来做缓存的Redis实例尽量不要开启持…

springboot项目打包jar 并打包为exe启动

springboot项目打包jar 并打包为exe启动&#xff08;在无jdk环境下运行&#xff09; 环境 SpringBoot Windows IDEA 实现 1.springboot打包为可执行jar&#xff08;这里使用maven install&#xff09; maven工具栏选择项目->Plugins ->install 注&#xff1a;如果…

Golang | Leetcode Golang题解之第332题重新安排行程

题目&#xff1a; 题解&#xff1a; func findItinerary(tickets [][]string) []string {var (m map[string][]string{}res []string)for _, ticket : range tickets {src, dst : ticket[0], ticket[1]m[src] append(m[src], dst)}for key : range m {sort.Strings(m[key])…