废话不说,直接上代码。
private static final String GOODS_NAME = "goodsName";
private static final String SEARCH_NAME = "searchName";
/**
* 权重分求和模式 由于无相关性的分值默认为 1 ,设置权重分最小值为 10
*/
Float MIN_SCORE = 1F;
public PageUtils<EsDocument> findDocumentPage(Map<String, Object> params) {
int page = TryParse.parseInt(params.get("page"));
int limit = TryParse.parseInt(params.get("limit"));
BoolQueryBuilder builder = QueryBuilders.boolQuery();
String searchKey = TryParse.parseString(params.get("queryName"));
String searchValue = TryParse.parseString(params.get("queryValue"));
String hotSearchId = TryParse.parseString(params.get("hotSerachId"));
int sort = TryParse.parseInt(params.get("sort"));
String userId = TryParse.parseString(params.get("userId"));
if (StringUtils.isNotEmpty(searchKey) && StringUtils.isNotEmpty(searchValue)) {
if (GOODS_NAME.equals(searchKey)) {
builder.must(QueryBuilders.matchPhraseQuery(GOODS_NAME, searchValue));
}
if (SEARCH_NAME.equals(searchKey)) {
//matchPhraseQuery 搜索的词不会被分词器分词
//matchQuery 搜索的词会被分词器分词
builder.must(QueryBuilders.matchPhraseQuery(SEARCH_NAME, searchValue));
}
}
//权重分权计算
WeightBuilder weightBuilder = ScoreFunctionBuilders.weightFactorFunction(MIN_SCORE);
FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(builder, weightBuilder);
//降序
Pageable pageable = null;
//价格排序
if (sort == 0){
pageable = PageRequest.of(page - 1, limit, Direction.DESC, "_score");
}else if (sort == 1){
pageable = PageRequest.of(page - 1, limit, Direction.ASC, "minNormalPrice");
}else if (sort == 2){
pageable = PageRequest.of(page - 1, limit, Direction.DESC, "minNormalPrice");
}
/**
* 高亮条件
* highlightField高亮字段
* preTags高亮前段
* preTags高亮后段
* requireFieldMatch(false)支持多字段高亮,改为true只能高亮搜索的字段
*/
String highlightField = "goodsName";
String preTags = "<b class=\"dzgoodsName\">";
String postTags = "</b>";
HighlightBuilder.Field goodsField = new HighlightBuilder.Field(highlightField).preTags(preTags).postTags(postTags).requireFieldMatch(false);
//实例化查询对象
SearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(functionScoreQueryBuilder)
.withHighlightFields(goodsField)
.withPageable(pageable)
.build();
//查询并封装成page对象
//Page<EsDocument> result = esDao.search(query);
Page<EsDocument> result = elasticsearchTemplate.queryForPage(searchQuery, EsDocument.class, new HighlightResultMapper());
return new PageUtils<>(result.getContent(), result.getTotalElements(), limit, page);
}