使用过Spring Data操作ES的小伙伴应该有所了解,它只能实现一些非常基本的数据管理工作,一旦遇到稍微复杂点的查询,基本都要依赖ES官方提供的RestHighLevelClient,Spring Data只是在其基础上进行了简单的封装。最近发现一款更优雅的ES ORM框架Easy-Es,使用它能像MyBatis-Plus一样操作ES,今天就以mall项目中的商品搜索功能为例,来聊聊它的使用!
Easy-Es(简称EE)是一款基于Elasticsearch(简称ES)官方提供的RestHighLevelClient打造的ORM开发框架,在RestHighLevelClient的基础上,只做增强不做改变,为简化开发、提高效率而生。EE和Mybatis-Plus(简称MP)的用法非常相似,如果你之前使用过MP的话,应该能很快上手EE。EE的理念是:把简单、易用、方便留给用户,把复杂留给框架。
EE的主要特性如下:
首先我们来对MySQL、Easy-Es和RestHighLevelClient的语法做过对比,来快速学习下Easy-Es的语法。
MySQLEasy-Eses-DSL/es JAVA apiandandmustororshould=eqterm!=neboolQueryBuilder.mustNot(queryBuilder)>gtQueryBuilders.rangeQuery('es field').gt()>=ge.rangeQuery('es field').gte()<lt.rangeQuery('es field').lt()<=le.rangeQuery('es field').lte()like '%field%'likeQueryBuilders.wildcardQuery(field,value)not like '%field%'notLikemust not wildcardQuery(field,value)like '%field'likeLeftQueryBuilders.wildcardQuery(field,*value)like 'field%'likeRightQueryBuilders.wildcardQuery(field,value*)betweenbetweenQueryBuilders.rangeQuery('es field').from(xx).to(xx)notBetweennotBetweenmust not QueryBuilders.rangeQuery('es field').from(xx).to(xx)is nullisNullmust not QueryBuilders.existsQuery(field)is notNullisNotNullQueryBuilders.existsQuery(field)ininQueryBuilders.termsQuery(" xx es field", xx)not innotInmust not QueryBuilders.termsQuery(" xx es field", xx)group bygroupByAggregationBuilders.terms()order byorderByfieldSortBuilder.order(ASC/DESC)minminAggregationBuilders.minmaxmaxAggregationBuilders.maxavgavgAggregationBuilders.avgsumsumAggregationBuilders.sumorder by xxx ascorderByAscfieldSortBuilder.order(SortOrder.ASC)order by xxx descorderByDescfieldSortBuilder.order(SortOrder.DESC)-matchmatchQuery-matchPhraseQueryBuilders.matchPhraseQuery-matchPrefixQueryBuilders.matchPhrasePrefixQuery-queryStringQueryQueryBuilders.queryStringQueryselect *matchAllQueryQueryBuilders.matchAllQuery()-highLightHighlightBuilder.Field.........
接下来把Easy-Es集成到项目中配置下就可以使用了。
<dependency>
<groupId>cn.easy-es</groupId>
<artifactId>easy-es-boot-starter</artifactId>
<version>1.0.2</version>
</dependency>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.14.0</version>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.14.0</version>
</dependency>
</dependencies>
</dependencyManagement>
easy-es:
# 是否开启EE自动配置
enable: true
# ES连接地址+端口
address: localhost:9200
# 关闭自带banner
banner: false
/**
* EasyEs配置类
* Created by macro on 2022/9/16.
*/
@Configuration
@EsMapperScan("com.macro.mall.tiny.easyes")
public class EasyEsConfig {
}
Easy-Es集成和配置完成后,就可以开始使用了。这里还是以mall项目的商品搜索功能为例,聊聊Easy-Es的使用,Spring Data的实现方式可以参考Elasticsearch项目实战,商品搜索功能设计与实现! 。
下面我们来学习下Easy-Es中注解的使用。
/**
* 搜索商品的信息
* Created by macro on 2018/6/19.
*/
@Data
@EqualsAndHashCode
@IndexName(value = "pms", shardsNum = 1, replicasNum = 0)
public class EsProduct implements Serializable {
private static final long serialVersionUID = -1L;
@IndexId(type = IdType.CUSTOMIZE)
private Long id;
@IndexField(fieldType = FieldType.KEYword)
private String productSn;
private Long brandId;
@IndexField(fieldType = FieldType.KEYWORD)
private String brandName;
private Long productCategoryId;
@IndexField(fieldType = FieldType.KEYWORD)
private String productCategoryName;
private String pic;
@IndexField(fieldType = FieldType.TEXT, analyzer = "ik_max_word")
private String name;
@IndexField(fieldType = FieldType.TEXT, analyzer = "ik_max_word")
private String subTitle;
@IndexField(fieldType = FieldType.TEXT, analyzer = "ik_max_word")
private String keywords;
private BigDecimal price;
private Integer sale;
private Integer newStatus;
private Integer recommandStatus;
private Integer stock;
private Integer promotionType;
private Integer sort;
@IndexField(fieldType = FieldType.NESTED, nestedClass = EsProductAttributeValue.class)
private List<EsProductAttributeValue> attrValueList;
@Score
private Float score;
}
注解名称用途参数@IndexName索引名注解value:指定索引名;shardsNum:分片数;replicasNum:副本数@IndexIdES主键注解type:指定注解类型,CUSTOMIZE表示自定义@IndexFieldES字段注解fieldType:字段在索引中的类型;analyzer:索引文档时用的分词器;nestedClass:嵌套类@Score得分注解decimalPlaces:得分保留小数位,实体类中被作为ES查询得分返回的字段使用
/**
* 搜索商品的属性信息
* Created by macro on 2018/6/27.
*/
@Data
@EqualsAndHashCode
public class EsProductAttributeValue implements Serializable {
private static final long serialVersionUID = 1L;
@IndexField(fieldType = FieldType.LONG)
private Long id;
@IndexField(fieldType = FieldType.KEYWORD)
private Long productAttributeId;
//属性值
@IndexField(fieldType = FieldType.KEYWORD)
private String value;
//属性参数:0->规格;1->参数
@IndexField(fieldType = FieldType.INTEGER)
private Integer type;
//属性名称
@IndexField(fieldType=FieldType.KEYWORD)
private String name;
}
下面我们来实现几个简单的商品信息维护接口,包括商品信息的导入、创建和删除。
/**
* 商品ES操作类
* Created by macro on 2018/6/19.
*/
public interface EsProductMapper extends BaseEsMapper<EsProduct> {
}
/**
* 搜索商品管理Service实现类
* Created by macro on 2018/6/19.
*/
@Service
public class EsProductServiceImpl implements EsProductService {
@Autowired
private EsProductDao productDao;
@Autowired
private EsProductMapper esProductMapper;
@Override
public int importAll() {
List<EsProduct> esProductList = productDao.getAllEsProductList(null);
return esProductMapper.insertBatch(esProductList);
}
@Override
public void delete(Long id) {
esProductMapper.deleteById(id);
}
@Override
public EsProduct create(Long id) {
EsProduct result = null;
List<EsProduct> esProductList = productDao.getAllEsProductList(id);
if (esProductList.size() > 0) {
result = esProductList.get(0);
esProductMapper.insert(result);
}
return result;
}
@Override
public void delete(List<Long> ids) {
if (!CollectionUtils.isEmpty(ids)) {
esProductMapper.deleteBatchIds(ids);
}
}
}
下面我们来实现一个最简单的商品搜索,分页搜索商品名称、副标题、关键词中包含指定关键字的商品。
/**
* 搜索商品管理Service实现类
* Created by macro on 2018/6/19.
*/
@Service
public class EsProductServiceImpl implements EsProductService {
@Autowired
private EsProductMapper esProductMapper;
@Override
public PageInfo<EsProduct> search(String keyword, Integer pageNum, Integer pageSize) {
LambdaEsQueryWrapper<EsProduct> wrapper = new LambdaEsQueryWrapper<>();
if(StrUtil.isEmpty(keyword)){
wrapper.matchAllQuery();
}else{
wrapper.multiMatchQuery(keyword,EsProduct::getName,EsProduct::getSubTitle,EsProduct::getKeywords);
}
return esProductMapper.pageQuery(wrapper, pageNum, pageSize);
}
}
下面我们来实现一个复杂的商品搜索,涉及到过滤、不同字段匹配权重不同以及可以进行排序。
/**
* 搜索商品管理Service实现类
* Created by macro on 2018/6/19.
*/
@Service
public class EsProductServiceImpl implements EsProductService {
@Autowired
private EsProductMapper esProductMapper;
@Override
public PageInfo<EsProduct> search(String keyword, Long brandId, Long productCategoryId, Integer pageNum, Integer pageSize,Integer sort) {
LambdaEsQueryWrapper<EsProduct> wrapper = new LambdaEsQueryWrapper<>();
//过滤
if (brandId != null || productCategoryId != null) {
if (brandId != null) {
wrapper.eq(EsProduct::getBrandId,brandId);
}
if (productCategoryId != null) {
wrapper.eq(EsProduct::getProductCategoryId,productCategoryId).enableMust2Filter(true);
}
}
//搜索
if (StrUtil.isEmpty(keyword)) {
wrapper.matchAllQuery();
} else {
wrapper.and(i -> i.match(EsProduct::getName, keyword, 10f)
.or().match(EsProduct::getSubTitle, keyword, 5f)
.or().match(EsProduct::getKeywords, keyword, 2f));
}
//排序
if(sort==1){
//按新品从新到旧
wrapper.orderByDesc(EsProduct::getId);
}else if(sort==2){
//按销量从高到低
wrapper.orderByDesc(EsProduct::getSale);
}else if(sort==3){
//按价格从低到高
wrapper.orderByAsc(EsProduct::getPrice);
}else if(sort==4){
//按价格从高到低
wrapper.orderByDesc(EsProduct::getPrice);
}else{
//按相关度
wrapper.sortByScore(SortOrder.DESC);
}
return esProductMapper.pageQuery(wrapper, pageNum, pageSize);
}
}
当我们查看相关商品的时候,一般底部会有一些商品推荐,这里简单来实现下。
/**
* 搜索商品管理Service实现类
* Created by macro on 2018/6/19.
*/
@Service
public class EsProductServiceImpl implements EsProductService {
@Autowired
private EsProductMapper esProductMapper;
@Override
public PageInfo<EsProduct> recommend(Long id, Integer pageNum, Integer pageSize) {
LambdaEsQueryWrapper<EsProduct> wrapper = new LambdaEsQueryWrapper<>();
List<EsProduct> esProductList = productDao.getAllEsProductList(id);
if (esProductList.size() > 0) {
EsProduct esProduct = esProductList.get(0);
String keyword = esProduct.getName();
Long brandId = esProduct.getBrandId();
Long productCategoryId = esProduct.getProductCategoryId();
//用于过滤掉相同的商品
wrapper.ne(EsProduct::getId,id);
//根据商品标题、品牌、分类进行搜索
wrapper.and(i -> i.match(EsProduct::getName, keyword, 8f)
.or().match(EsProduct::getSubTitle, keyword, 2f)
.or().match(EsProduct::getKeywords, keyword, 2f)
.or().match(EsProduct::getBrandId, brandId, 5f)
.or().match(EsProduct::getProductCategoryId, productCategoryId, 3f));
return esProductMapper.pageQuery(wrapper, pageNum, pageSize);
}
return esProductMapper.pageQuery(wrapper, pageNum, pageSize);
}
}
在搜索商品时,经常会有一个筛选界面来帮助我们找到想要的商品,这里我们来简单实现下。
/**
* 搜索商品管理Service实现类
* Created by macro on 2018/6/19.
*/
@Service
public class EsProductServiceImpl implements EsProductService {
@Autowired
private EsProductMapper esProductMapper;
@Override
public EsProductRelatedInfo searchRelatedInfo(String keyword) {
SearchRequest searchRequest = new SearchRequest();
searchRequest.indices("pms_*");
SearchSourceBuilder builder = new SearchSourceBuilder();
//搜索条件
if (StrUtil.isEmpty(keyword)) {
builder.query(QueryBuilders.matchAllQuery());
} else {
builder.query(QueryBuilders.multiMatchQuery(keyword, "name", "subTitle", "keywords"));
}
//聚合搜索品牌名称
builder.aggregation(AggregationBuilders.terms("brandNames").field("brandName"));
//集合搜索分类名称
builder.aggregation(AggregationBuilders.terms("productCategoryNames").field("productCategoryName"));
//聚合搜索商品属性,去除type=1的属性
AbstractAggregationBuilder<NestedAggregationBuilder> aggregationBuilder = AggregationBuilders.nested("allAttrValues", "attrValueList")
.subAggregation(AggregationBuilders.filter("productAttrs", QueryBuilders.termQuery("attrValueList.type", 1))
.subAggregation(AggregationBuilders.terms("attrIds")
.field("attrValueList.productAttributeId")
.subAggregation(AggregationBuilders.terms("attrValues")
.field("attrValueList.value"))
.subAggregation(AggregationBuilders.terms("attrNames")
.field("attrValueList.name"))));
builder.aggregation(aggregationBuilder);
searchRequest.source(builder);
try {
SearchResponse searchResponse = esProductMapper.search(searchRequest, RequestOptions.DEFAULT);
return convertProductRelatedInfo(searchResponse);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 将返回结果转换为对象
*/
private EsProductRelatedInfo convertProductRelatedInfo(SearchResponse response) {
EsProductRelatedInfo productRelatedInfo = new EsProductRelatedInfo();
Map<String, Aggregation> aggregationMap = response.getAggregations().asMap();
//设置品牌
Aggregation brandNames = aggregationMap.get("brandNames");
List<String> brandNameList = new ArrayList<>();
for(int i = 0; i<((Terms) brandNames).getBuckets().size(); i++){
brandNameList.add(((Terms) brandNames).getBuckets().get(i).getKeyAsString());
}
productRelatedInfo.setBrandNames(brandNameList);
//设置分类
Aggregation productCategoryNames = aggregationMap.get("productCategoryNames");
List<String> productCategoryNameList = new ArrayList<>();
for(int i=0;i<((Terms) productCategoryNames).getBuckets().size();i++){
productCategoryNameList.add(((Terms) productCategoryNames).getBuckets().get(i).getKeyAsString());
}
productRelatedInfo.setProductCategoryNames(productCategoryNameList);
//设置参数
Aggregation productAttrs = aggregationMap.get("allAttrValues");
List<? extends Terms.Bucket> attrIds = ((ParsedStringTerms) ((ParsedFilter) ((ParsedNested) productAttrs).getAggregations().get("productAttrs")).getAggregations().get("attrIds")).getBuckets();
List<EsProductRelatedInfo.ProductAttr> attrList = new ArrayList<>();
for (Terms.Bucket attrId : attrIds) {
EsProductRelatedInfo.ProductAttr attr = new EsProductRelatedInfo.ProductAttr();
attr.setAttrId(Long.parseLong((String) attrId.getKey()));
List<String> attrValueList = new ArrayList<>();
List<? extends Terms.Bucket> attrValues = ((ParsedStringTerms) attrId.getAggregations().get("attrValues")).getBuckets();
List<? extends Terms.Bucket> attrNames = ((ParsedStringTerms) attrId.getAggregations().get("attrNames")).getBuckets();
for (Terms.Bucket attrValue : attrValues) {
attrValueList.add(attrValue.getKeyAsString());
}
attr.setAttrValues(attrValueList);
if(!CollectionUtils.isEmpty(attrNames)){
String attrName = attrNames.get(0).getKeyAsString();
attr.setAttrName(attrName);
}
attrList.add(attr);
}
productRelatedInfo.setProductAttrs(attrList);
return productRelatedInfo;
}
}
今天将之前的使用Spring Data的商品搜索案例使用Easy-Es改写了一下,确实使用Easy-Es更简单,但是对于复杂的聚合搜索功能,两者都需要使用原生的RestHighLevelClient用法来实现。使用Easy-Es来操作ES确实足够优雅,它类似MyBatis-Plus的用法能大大降低我们的学习成本,快速完成开发工作!
官方文档:https://www.easy-es.cn/
https://Github.com/macrozheng/mall-learning/tree/master/mall-tiny-easyes