包括分页,高亮,价格区间过滤,品牌锅炉,聚合查询,升序(降序),关键字搜索
package com.changgou.search.service.impl;
import com.alibaba.fastjson.JSON;
import com.changgou.search.pojo.SkuInfo;
import com.changgou.search.service.SearchService;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Component;
import java.util.*;
import java.util.stream.Collectors;
@Component
public class SearchServiceImpl implements SearchService {
@Autowired
private ElasticsearchTemplate elasticsearchTemplatel;
@Override
public Map search(Map<String, String> searchMap) {
Map<String, Object> map = new HashMap<>();
//构建条件封装对象
NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
//根据关键字进行查询
if (StringUtils.isNotBlank(searchMap.get("keywords"))) {
boolQuery.must(QueryBuilders.matchQuery("name", searchMap.get("keywords")).operator(Operator.AND));
}
//按照品牌过滤进行查询
if (StringUtils.isNotBlank(searchMap.get("brand"))) {
boolQuery.filter(QueryBuilders.termQuery("brandName", searchMap.get("brand")));
}
//按规格进行过滤查询
for (String key : searchMap.keySet()) {
if (key.startsWith("spec_")) {
String value = searchMap.get(key).replace("%2B", "+");
boolQuery.filter(QueryBuilders.termQuery("specMap." + key.substring(5) + ".keyword", value));
}
}
//根据价格区间进行过滤查询
if (StringUtils.isNotBlank(searchMap.get("price"))) {
String[] prices = searchMap.get("price").split("-");
if (prices.length == 2) {
boolQuery.filter(QueryBuilders.rangeQuery("price").lte(prices[1]));
}
boolQuery.filter(QueryBuilders.rangeQuery("price").gte(prices[0]));
}
nativeSearchQueryBuilder.withQuery(boolQuery);//开启布尔查询(布尔查新可以封装多个条件)
//对品牌进行分组(聚合查询)
String skuBrand = "skuBrand";
nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms(skuBrand).field("brandName"));
//对规格进行聚合查询
String skuSpec = "skuSpec";
nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms(skuSpec).field("spec.keyword"));
//开启分页
String pageIndex = searchMap.get("pageIndex");
String pageSize = searchMap.get("pageSize");
if (StringUtils.isEmpty(pageIndex)) {
pageIndex = "1";
}
if (StringUtils.isEmpty(pageSize)) {
pageSize = "30";
}
nativeSearchQueryBuilder.withPageable(PageRequest.of(Integer.parseInt(pageIndex) - 1, Integer.parseInt(pageSize)));
//根据相关字段进行排序 1.当前域 2.当前升序操作(升序ASC,降序DESC)
if (StringUtils.isNotBlank(searchMap.get("sortField")) && StringUtils.isNotBlank(searchMap.get("sortRule"))) {
if ("ASC".equals(searchMap.get("sortRule"))) {
//升序
nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort(searchMap.get("sortField")).order(SortOrder.ASC));
} else {
nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort(searchMap.get("sortField")).order(SortOrder.DESC));
}
}
//设置高亮域以及高亮样式
HighlightBuilder.Field field = new HighlightBuilder.Field("name")//高亮域
.preTags("<span style = 'color:red'>")//高亮前缀
.postTags("</span>");//高亮后缀
nativeSearchQueryBuilder.withHighlightFields(field);
AggregatedPage<SkuInfo> resultInfo = elasticsearchTemplatel.queryForPage(nativeSearchQueryBuilder.build(), SkuInfo.class, new SearchResultMapper() {
@Override
public <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> aClass, Pageable pageable) {
//查询结果操作
List<T> list = new ArrayList<>();
//获取查询命中结果数据
SearchHits hits = searchResponse.getHits();
if (hits != null) {
for (SearchHit hit : hits) {
//将SearchHit转为skuInfo
SkuInfo skuInfo = JSON.parseObject(hit.getSourceAsString(), SkuInfo.class);
Map<String, HighlightField> highlightFields = hit.getHighlightFields();
if (highlightFields != null && highlightFields.size() > 0) {
//替换数据
skuInfo.setName(highlightFields.get("name").getFragments()[0].toString());
}
list.add((T) skuInfo);
}
}
return new AggregatedPageImpl<T>(list, pageable, hits.getTotalHits(), searchResponse.getAggregations());
}
});
//总记录数
map.put("total", resultInfo.getTotalElements());
//总页数
map.put("totalPages", resultInfo.getTotalPages());
//数据集合
map.put("rows", resultInfo.getContent());
//封装品牌的分组结果
StringTerms brandTerms = (StringTerms) resultInfo.getAggregation(skuBrand);
List<String> brandList = brandTerms.getBuckets().stream().map(bucket -> bucket.getKeyAsString()).collect(Collectors.toList());
map.put("brandList", brandList);
//封装规格分组结果
StringTerms specTerms = (StringTerms) resultInfo.getAggregation(skuSpec);
List<String> specList = specTerms.getBuckets().stream().map(bucket -> bucket.getKeyAsString()).collect(Collectors.toList());
map.put("sepecList", specList);
//当前页
map.put("pageIndex", pageIndex);
map.put("pageSize", pageSize);
return map;
}
}