es商品模糊查询案例
1,需求及背景:
根据商品编码或者名称模糊查询,之前走数据库,根据名称查询较慢,现在走es
2,代码逻辑:
先判断编码查询还是名称查询,查询逻辑不一样
2.1,编码查询:
查询商品编码或条码,termQuery全量匹配,prefiexQuery前缀匹配,should类似or,四个条件满足一个就行,过滤部类
minimumShouldMatch:详解:https://www.cnblogs.com/ljhdo/p/4577065.html,这个要先分词,有点类似fuzzy编码查询,如:535908,可以分成53,59,08,商品编码只要包含其中一个即匹配
2.2,名称查询:
must相当于and关联,使用queryStringQuery,这个类似分词查询,如查询条件:奥地利,会分成三个词,商品名称只要包含其中一个就会被匹配到
3,代码
@Override
public List<ReqProductInfoEsVo> searchProductInfoByKey(ReqProductSearchVO vo) {
SearchRequest searchRequest = new SearchRequest(EsOperateTables.BASE_PRODUCT_INFO_SAP.getValue());
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//sourceBuilder.fetchSource(PRODUCT_STATUS_FIELDS, null);
BoolQueryBuilder searchBuilder = QueryBuilders.boolQuery();//创建多条件查询BoolQueryBuilder
if(StringUtils.isNumeric(vo.getSearchKey())){
searchBuilder.should(QueryBuilders.prefixQuery("product_code",vo.getSearchKey()))
.should(QueryBuilders.termQuery("product_code",vo.getSearchKey()))
.should(QueryBuilders.prefixQuery("bar_code",vo.getSearchKey()))
.should(QueryBuilders.termQuery("bar_code",vo.getSearchKey()));
if(StringUtils.isNotEmpty(vo.getRootCategoryCode())){
searchBuilder.filter(QueryBuilders.termQuery("root_category_code", vo.getRootCategoryCode()));//过滤部类
}
searchBuilder.minimumShouldMatch(1);
}else if (StringUtils.isNotEmpty(vo.getSearchKey())){
searchBuilder.must(QueryBuilders.queryStringQuery("product_name:"+vo.getSearchKey()).defaultOperator(QueryStringQueryBuilder.DEFAULT_OPERATOR));
//searchBuilder.must(QueryBuilders.queryStringQuery(vo.getSearchKey()).field("product_name"));
if(StringUtils.isNotEmpty(vo.getRootCategoryCode())){
searchBuilder.must(QueryBuilders.termQuery("root_category_code", vo.getRootCategoryCode()));
}
}else{
return Collections.emptyList();
}
sourceBuilder.query(searchBuilder);
sourceBuilder.timeout(new TimeValue(120, TimeUnit.SECONDS));
sourceBuilder.from(0);//分页起始位置
sourceBuilder.size(vo.getSize());//分页每页
searchRequest.source(sourceBuilder);
log.info("terms查询DSL语句:" + searchRequest.toString());
return returnSearchShopProductStatusAsyncByLocation(searchRequest);
}