向电商项目中添加ElasticSearch实现商品搜索
(一)使用框架
Elasticsearch 是一个分布式、可扩展、实时的搜索与数据分析引擎。 它能从项目一开始就赋予你的数据以搜索、分析和探索的能力,可用于实现全文搜索和实时数据统计。
我是安装在docker上的,首先安装一个docker具体安装参考如下
docker安装参考链接 https://www.jianshu.com/p/2b3924d71acd
https://www.jianshu.com/p/b5c36abbf61e
使用Spring data ElasticSearch整合ElasticSearch
Spring Data Elasticsearch是Spring提供的一种以Spring Data风格来操作数据存储的方式,它可以避免编写大量的样板代码。
SpringDataElasticSearch的常用注解
@Documet
//标示映射到Elasticsearch文档上的领域对象
public @interface Document {
//索引库名次,mysql中数据库的概念
String indexName();
//文档类型,mysql中表的概念
String type() default "";
//默认分片数
short shards() default 5;
//默认副本数量
short replicas() default 1;
//表示是文档的id,文档可以认为是mysql中表行的概念
public @interface Id {
@Field
public @interface Field {
//文档中字段的类型
FieldType type() default FieldType.Auto;
//是否建立倒排索引
boolean index() default true;
//是否进行存储
boolean store() default false;
//分词器名次
String analyzer() default "";
FieldType
//为文档自动指定元数据类型
public enum FieldType {
Text,//会进行分词并建了索引的字符类型
Integer,
Long,
Date,
Float,
Double,
Boolean,
Object,
Auto,//自动判断字段类型
Nested,//嵌套对象类型
Attachment,
Keyword//不会进行分词建立索引的类型
SpringData方式的数据操作
接口直接继承ElasticSearchRepository接口可以获得常用的数据操作方式
也可以是使用衍生查询,在接口中直接指定查询方法名称就可以查询,无需进行实现,例如对商品表进行搜索,商品表中包含的字段有商品名称,关键字,标题等,使用商品名称,关键字,标题三个字段作为维度去进行或的查询,就将商品名称,关键字,标题,三个字段作为方法名称例子为:
* 搜索查询
* @param name 商品名称
* @param subTitle 商品标题
* @param keywords 商品关键字
* @param page 分页信息
* @return
Page<EsProduct> findByNameOrSubTitleOrKeywords(String name, String subTitle, String keywords, Pageable page);
使用@Query注解可以进用ElasticSearch的DSL预计进行查询示例:
@Query("{"bool" : {"must" : {"field" : {"name" : "?0"}}}}")
Page<EsProduct> findByName(String name,Pageable pageable);
ElasticSearch的DSL语句相关内容参考链接
https://www.jianshu.com/p/b57140403b5f
(二)项目使用表说明
pms_product:商品信息表
pms_product_attribute:商品属性参数表
pms_product_attribute_value:存储产品参数值的表
(三)Springboot整合ElasticSearch实现商品搜索
1.修改pom.xml添加springboot关于ElasticSearch的相关依赖
<!--Elasticsearch相关依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch<artifactId>
</dependency>
2.修改Springboot的application.yml配置文件,增加关于ElasticSearch的相关配置
data:
elasticsearch:
repositories:
enabled: true
cluster-nodes: 192.168.1.150:9300 # es的连接地址及端口号
cluster-name: elasticsearch # es集群的名称
elasticsearch:
rest:
uris: ["http://192.168.1.150:9200"]
3.添加定义的商品文档对应类EsProduct
package com.mall.mallmybatis.nosql.elasticsearch.document;
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;
* 搜索中的商品信息
* Created by macro on 2018/6/19.
@Document(indexName = "pms", type = "product",shards = 1,replicas = 0)
public class EsProduct implements Serializable {
private static final long serialVersionUID = -1L;
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;
//省略了所有getter和setter方法
其中@Field(analyzer = "ik_max_word",type = FieldType.Text)表示在es中,字段为text格式使用ik_max_word分词方式进行查询
@Field(type = FieldType.Keyword)表示字段格式在es中字段格式为keyword,不能使用分词,只能完全匹配,这个是我们自定义的要生成到ElasticSearch中的
@Field(type =FieldType.Nested),表示对应字段使用es的nested类型,可以进行嵌套查询
nested相关信息参考链接
https://blog.csdn.net/laoyang360/article/details/82950393
4.添加ElasticsearchRepository接口用于操作ElasticSearch
package com.mall.mallmybatis.nosql.elasticsearch.repository;
import com.mall.mallmybatis.nosql.elasticsearch.document.EsProduct;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
* 商品ES操作类
* Created by macro on 2018/6/19.
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);
5.添加EsProductDao接口和mapper.xml,定义导入elasticSearch数据的方法
EsProductDao
package com.mall.mallmybatis.dao;
import com.mall.mallmybatis.nosql.elasticsearch.document.EsProduct;
import org.apache.ibatis.annotations.Param;
import java.util.List;
* 搜索系统中的商品管理自定义Dao
* @author wangxing
* @version 2020/6/23 10:49 Administrator
public interface EsProductDao {
* 获取全部的ES相关产品列表信息
* @param id
* @return
List<EsProduct> getAllEsProductList(@Param("id") Long id);
EsProductDao.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mall.mallmybatis.dao.EsProductDao">
<resultMap id="esProductListMap" type="com.mall.mallmybatis.nosql.elasticsearch.document.EsProduct" autoMapping="true">
<id column="id" jdbcType="BIGINT" property="id" />
<collection property="attrValueList" columnPrefix="attr_" ofType="com.mall.mallmybatis.nosql.elasticsearch.document.EsProductAttributeValue">
<id column="id" property="id" jdbcType="BIGINT"/>
<result column="product_attribute_id" property="productAttributeId" jdbcType="BIGINT"/>
<result column="value" property="value" jdbcType="VARCHAR"/>
<result column="type" property="type"/>
<result column="name" property="name"/>
</collection>
</resultMap>
<select id="getAllEsProductList" resultMap="esProductListMap">
select
p.id id,
p.product_sn productSn,
p.brand_id brandId,
p.brand_name brandName,
p.product_category_id productCategoryId,
p.product_category_name productCategoryName,
p.pic pic,
p.name name,
p.sub_title subTitle,
p.price price,
p.sale sale,
p.new_status newStatus,
p.recommand_status recommandStatus,
p.stock stock,
p.promotion_type promotionType,
p.keywords keywords,
p.sort sort,
pav.id attr_id,
pav.value attr_value,
pav.product_attribute_id attr_product_attribute_id,
pa.type attr_type,
pa.name attr_name
from pms_product p
left join pms_product_attribute_value pav on p.id = pav.product_id
left join pms_product_attribute pa on pav.product_attribute_id= pa.id
where delete_status = 0 and publish_status = 1
<if test="id!=null">
and p.id=#{id}
</select>
</mapper>
6.添加EsProductService接口,定义搜索商品的方法
package com.mall.mallmybatis.service;
import com.mall.mallmybatis.nosql.elasticsearch.document.EsProduct;
import org.springframework.data.domain.Page;
import java.util.List;
* 商品搜索管理Service
* @author wangxing
* @version 2020/6/23 10:44 Administrator
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);
7.添加EsProductService的接口实现EsProductServiceImpl
package com.mall.mallmybatis.service.impl;
import com.mall.mallmybatis.dao.EsProductDao;
import com.mall.mallmybatis.nosql.elasticsearch.document.EsProduct;
import com.mall.mallmybatis.nosql.elasticsearch.repository.EsProductRepository;
import com.mall.mallmybatis.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 javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
* @author wangxing
* @version 2020/6/23 10:48 Administrator
@Service
public class EsProductServiceImpl implements EsProductService {
private static final Logger LOGGER = LoggerFactory.getLogger(EsProductServiceImpl.class);
@Resource
private EsProductDao productDao;
@Autowired
private EsProductRepository productRepository;
* 从数据库中导入所有商品到ES
* @return
@Override
public int importAll() {
//获取产品信息
List<EsProduct> esProductList = productDao.getAllEsProductList(null);
//将产品信息保存到es中
Iterable<EsProduct> esProductIterable = productRepository.saveAll(esProductList);
//返回存入数据信息
Iterator<EsProduct> iterator = esProductIterable.iterator();
int result = 0;
while (iterator.hasNext()) {
result++;
iterator.next();
return result;
* 删除指定id的索引文档
* @param id
@Override
public void delete(Long id) {
productRepository.deleteById(id);
* 根据id创建商品
* @param id
* @return
@Override
public EsProduct create(Long id) {
EsProduct result = null;
//查询指定id对应的产品信息列表
List<EsProduct> esProductList = productDao.getAllEsProductList(id);
//将查询到的产品信息存入到es中
if (esProductList.size() > 0) {
EsProduct esProduct = esProductList.get(0);
result = productRepository.save(esProduct);
return result;
* 删除一组id对应的产品信息
* @param ids
@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);
* 根据关键字搜索名称或者副标题
* @param keyword
* @param pageNum
* @param pageSize
* @return
@Override
public Page<EsProduct> search(String keyword, Integer pageNum, Integer pageSize) {
Pageable pageable = PageRequest.of(pageNum, pageSize);
return productRepository.findByNameOrSubTitleOrKeywords(keyword, keyword, keyword, pageable);
8.添加EsProductController定义外部访问
package com.mall.mallmybatis.controller;
import com.mall.mallmybatis.common.api.CommonPage;
import com.mall.mallmybatis.common.api.CommonResult;
import com.mall.mallmybatis.nosql.elasticsearch.document.EsProduct;
import com.mall.mallmybatis.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.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
* @author wangxing
* @version 2020/6/23 11:38 Administrator
@Controller
@Api(tags = "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/batch", method = RequestMethod.POST)
@ResponseBody
public CommonResult<Object> delete(@PathVariable Long id) {
esProductService.delete(id);
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));
(四)启动项目进行测试
启动中遇到问题
项目无法启动,错误提示
2020-06-23 13:28:34.512 WARN 11900 --- [ restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'esProductController': Unsatisfied dependency expressed through field 'esProductService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'esProductServiceImpl': Unsatisfied dependency expressed through field 'productRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.mall.mallmybatis.nosql.elasticsearch.document.EsProductRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
EsProductDao.xml配置文件中维护的路径错误,调整后可以正常启动了
2.出现提醒无法链接到elasticsearch
2020-06-25 07:44:28.223 ERROR 8784 --- [ restartedMain] .d.e.r.s.AbstractElasticsearchRepository : failed to load elasticsearch nodes : org.elasticsearch.client.transport.NoNodeAvailableException: None of the configured nodes are available: [{#transport#-1}{lHG1RMxbTpaovEM39-jwZg}{192.168.1.150}{192.168.1.150:9300}]
错误原因elasticsearch没有正常启动,重新启动后恢复正常.
3.进行接口测试时发现搜索不到数据
原因,调用接口时翻页写入了1和5,而实际数据不足5条,导致被翻页过去了,翻页第一页是从0开始的不是1.