本文主要介绍在Elasticsearch中实现商品搜索功能

中文分词器

  • Elasticsearch有默认的分词器,默认分词器只是将中文逐词分隔,并不符合我们的需求。

    get hanzo/_analyze
    {
      "text": "小米手机",
      "tokenizer": "standard"
    }
    
  • 需要安装与Elasticsearch版本相同的ik分词器,ik分词器将小米手机分为小米和手机,符合我们的要求。

get hanzo/_analyze
{
  "text": "小米手机",
  "tokenizer": "ik_max_word"
}

在SpringBoot中使用

在商品信息实体类中用@Document、@Field等注解。对于需要中文分词的字段,我们直接使用@Field注解属性设置为ik_max_word。

/**
 * @Author 皓宇QAQ
 * @Date 2020/6/4 20:49
 * @Description:搜索中的商品信息
 */
@Document(indexName = "hanzo", type = "product",shards = 1,replicas = 0)
@Data
public class EsProduct implements Serializable {
    private static final long serialVersionUID = -1L;
    @Id
    private Long goodsId;
    @Field(analyzer = "ik_max_word",type = FieldType.Text)
    private String goodsName;
    @Field(analyzer = "ik_max_word",type = FieldType.Text)
    private String goodsIntro;

    private Long goodsCategoryId;

    private String goodsCoverImg;

    private String goodsCarousel;

    private Integer originalPrice;

    private Integer sellingPrice;

    private Integer stockNum;

    private String tag;

    private Byte goodsSellStatus;

    private Integer createUser;

    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private Date createTime;

    private Integer updateUser;

    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private Date updateTime;
    @Field(type = FieldType.Keyword)
    private String goodsDetailContent;
}

简单商品搜索

先实现一个最简单的商品搜索功能,搜索包括商品名称,商品简介,商品标签中包含指定的关键字的商品和一个直接根据商品分类进行查询商品的功能

  • 在SpringBoot中实现,使用Elasticsearch Repositories的衍生查询来搜索;

    public interface EsProductRepository extends ElasticsearchRepository<EsProduct, Long> {
        /**
         * 衍生搜索关键字查询
         *
         * @param goodsName          商品名称
         * @param goodsIntro         商品简介
         * @param tag               商品标签
         * @param page              分页信息
         * @return
         */
        Page<EsProduct> findByGoodsNameOrGoodsIntroOrTag(String goodsName, String goodsIntro, String tag,Pageable page);
    
       /**
         * 衍生搜索商品分类定位查询
         *
         * @param goodsCategoryId   商品分类
         * @param page              分页信息
         * @return
         */
        Page<EsProduct> findByGoodsCategoryId(Long goodsCategoryId, Pageable page);
    
    }
    
  • 衍生查询其实原理很简单,就是将一定规则方法名称的方法转化为Elasticsearch的Query DSL语句,看完下面这张表你就懂了。

product_search_04.png

综合商品搜索

接下来我们来实现一个复杂的商品搜索,涉及到过滤、不同字段匹配权重不同以及可以进行排序。

  • 首先来说下我们的需求,按输入的关键字搜索商品名称、商品简介和 商品标签,默认按相关度进行排序;
  • 这里我们有一点特殊的需求,比如商品名称匹配关键字的的商品我们认为与搜索条件更匹配,其次是商品简介和商品标签,这时就需要用到function_score查询了;
  • 在Elasticsearch中搜索到文档的相关性由_score字段来表示的,文档的_score字段值越高,表示与搜索条件越匹配,而function_score查询可以通过设置权重来影响_score字段值,使用它我们就可以实现上面的需求了;
  • 在SpringBoot中实现,使用Elasticsearch Repositories的search方法来实现,但需要自定义查询条件QueryBuilder;
 @Override
    public Page<EsProduct> sortSearch(String keyword, Integer pageNum, Integer pageSize, Integer sort) {
        Pageable pageable = PageRequest.of(pageNum, pageSize);
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        //分页
        nativeSearchQueryBuilder.withPageable(pageable);
        //过滤
        
        //搜索
        if (StringUtils.isEmpty(keyword)) {
            nativeSearchQueryBuilder.withQuery(QueryBuilders.matchAllQuery());
        } else {
            List<FunctionScoreQueryBuilder.FilterFunctionBuilder> filterFunctionBuilders = new ArrayList<>();
            filterFunctionBuilders.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.matchQuery("goodsName", keyword),
                    ScoreFunctionBuilders.weightFactorFunction(10)));
            filterFunctionBuilders.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.matchQuery("goodsIntro", keyword),
                    ScoreFunctionBuilders.weightFactorFunction(5)));
            filterFunctionBuilders.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.matchQuery("tag", keyword),
                    ScoreFunctionBuilders.weightFactorFunction(2)));
            FunctionScoreQueryBuilder.FilterFunctionBuilder[] builders = new FunctionScoreQueryBuilder.FilterFunctionBuilder[filterFunctionBuilders.size()];
            filterFunctionBuilders.toArray(builders);
            FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(builders)
                    .scoreMode(FunctionScoreQuery.ScoreMode.SUM)
                    .setMinScore(2);
            nativeSearchQueryBuilder.withQuery(functionScoreQueryBuilder);
        }
        //排序
        if(sort==1){
            //按新品从新到旧
            nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("goodsId").order(SortOrder.DESC));
        }else if(sort==2){
            //按库存从高到低
            nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("stockNum").order(SortOrder.DESC));
        }else if(sort==3){
            //按价格从低到高
            nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("sellingPrice").order(SortOrder.ASC));
        }else if(sort==4){
            //按价格从高到低
            nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("sellingPrice").order(SortOrder.DESC));
        }else{
            //按相关度
            nativeSearchQueryBuilder.withSort(SortBuilders.scoreSort().order(SortOrder.DESC));
        }
        nativeSearchQueryBuilder.withSort(SortBuilders.scoreSort().order(SortOrder.DESC));
        NativeSearchQuery searchQuery = nativeSearchQueryBuilder.build();
        log.info("DSL:{}", searchQuery.getQuery().toString());
        return productRepository.search(searchQuery);
    }

相关商品推荐

当我们查看相关商品的时候,一般底部会有一些商品推荐,这里使用Elasticsearch来简单实现下。

  • 首先来说下我们的需求,可以根据指定商品的ID来查找相关商品;

  • 这里我们的实现原理是这样的:首先根据ID获取指定商品信息,然后以指定商品的名称、商品简介、商品标签和分类来搜索商品,并且要过滤掉当前商品,调整搜索条件中的权重以获取最好的匹配度;

  • 在SpringBoot中实现,使用Elasticsearch Repositories的search方法来实现,但需要自定义查询条件QueryBuilder;

    @Override
        public Page<EsProduct> recommend(Long id, Integer pageNum, Integer pageSize) {
            Pageable pageable = PageRequest.of(pageNum, pageSize);
            List<EsProduct> esProductList = productDao.getAllEsProductList(id);
            if (esProductList.size() > 0) {
                EsProduct esProduct = esProductList.get(0);
                String keyword = esProduct.getGoodsName();
                Long goodsCategoryId = esProduct.getGoodsCategoryId();
                //根据商品名称、商品简介,商品标签,分类进行搜索
                List<FunctionScoreQueryBuilder.FilterFunctionBuilder> filterFunctionBuilders = new ArrayList<>();
                filterFunctionBuilders.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.matchQuery("goodsName", keyword),
                        ScoreFunctionBuilders.weightFactorFunction(8)));
                filterFunctionBuilders.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.matchQuery("goodsIntro", keyword),
                        ScoreFunctionBuilders.weightFactorFunction(2)));
                filterFunctionBuilders.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.matchQuery("tag", keyword),
                        ScoreFunctionBuilders.weightFactorFunction(2)));
                filterFunctionBuilders.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.matchQuery("goodsCategoryId", goodsCategoryId),
                        ScoreFunctionBuilders.weightFactorFunction(6)));
                FunctionScoreQueryBuilder.FilterFunctionBuilder[] builders = new FunctionScoreQueryBuilder.FilterFunctionBuilder[filterFunctionBuilders.size()];
                filterFunctionBuilders.toArray(builders);
                FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(builders)
                        .scoreMode(FunctionScoreQuery.ScoreMode.SUM)
                        .setMinScore(2);
                NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
                builder.withQuery(functionScoreQueryBuilder);
                builder.withPageable(pageable);
                NativeSearchQuery searchQuery = builder.build();
                log.info("DSL:{}", searchQuery.getQuery().toString());
                return productRepository.search(searchQuery);
            }
            return new PageImpl<>(null);
        }
    

参考代码以及接口文档

Github

Swagger UI 文档

总结

知识只有分享出来才有价值。如果有问题的话,可以在关于我的页面,通过我的邮箱联系我进行探讨。

Q.E.D.


Remain true to our original aspiration.