Elasticsearch实现商品搜索(关键字查询 条件筛选 规格过滤 价格区间搜索 分页查询 排序查询 高亮查询)
Elasticsearch实现商品搜索商品搜索1、 根据关键字查询2、条件筛选商品搜索核心依赖<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-elasticsearch</artifactId></
Elasticsearch实现商品搜索
商品搜索
核心依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
1、根据关键字查询
(1) changgou_service_search项目创建SearchService接口
public interface SearchService {
/**
* 全文检索
* @param paramMap 查询参数
* @return
*/
public Map search(Map<String, String> paramMap) throws Exception;
}
(2) changgou_service_search项目创建SearchService接口实现类SearchServiceImpl
@Service
public class SearchServiceImpl implements SearchService {
@Autowired
private ElasticsearchTemplate esTemplate;
//设置每页查询条数据
public final static Integer PAGE_SIZE = 20;
@Override
public Map search(Map<String, String> searchMap) throws Exception {
Map<String, Object> resultMap = new HashMap<>();
//有条件才查询Es
if (null != searchMap) {
//组合条件对象
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
//0:关键词 模糊查询,相当于%关键词% 后面的and可用于多个拼接
if (!StringUtils.isEmpty(searchMap.get("keywords"))) {
boolQuery.must(QueryBuilders.matchQuery("name", searchMap.get("keywords")).operator(Operator.AND));
}
//4. 原生搜索实现类 把查询条件丢进去
NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
nativeSearchQueryBuilder.withQuery(boolQuery);
//10: 执行查询, 返回结果对象
AggregatedPage<SkuInfo> aggregatedPage = esTemplate.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 (null != hits) {
for (SearchHit hit : hits) {
//格式转换后放入集合中
SkuInfo skuInfo = JSON.parseObject(hit.getSourceAsString(), SkuInfo.class);
list.add((T) skuInfo);
}
}
return new AggregatedPageImpl<T>(list, pageable, hits.getTotalHits(), searchResponse.getAggregations());
}
});
//11. 总条数
resultMap.put("total", aggregatedPage.getTotalElements());
//12. 总页数
resultMap.put("totalPages", aggregatedPage.getTotalPages());
//13. 查询结果集合
resultMap.put("rows", aggregatedPage.getContent());
//查询的结果返回给前端
return resultMap;
}
return null;
}
}
(3) changgou_service_search项目创建SearchController
@RestController
@RequestMapping("/sku_search")
public class SearchController {
@Autowired
private EsManagerService esManagerService;
@Autowired
private SearchService searchService;
//对搜索入参带有特殊符号进行处理
public void handlerSearchMap(Map<String,String> searchMap){
if(null != searchMap){
Set<Map.Entry<String, String>> entries = searchMap.entrySet();
for (Map.Entry<String, String> entry : entries) {
if(entry.getKey().startsWith("spec_")){
searchMap.put(entry.getKey(),entry.getValue().replace("+","%2B"));
}
}
}
}
/**
* 全文检索
* @return
*/
@GetMapping
public Map search(@RequestParam Map<String, String> paramMap) throws Exception {
//特殊符号处理
handlerSearchMap(searchMap);
Map resultMap = searchService.search(paramMap);
return resultMap;
}
}
(4)测试的时候可以多拼接keywords=xxx来实现关键字的搜索
2、条件筛选
用户有可能会根据分类搜索、品牌搜索,还有可能根据规格搜索,以及价格搜索和排序操作。根据分类和品牌搜索的时候,可以直接根据指定域搜索,而规格搜索的域数据是不确定的,价格是一个区间搜索,所以我们可以分为三段实现,先实现分类、品牌搜素,再实现规格搜索,然后实现价格区间搜索。
2.1 品牌筛选
2.1.1 需求分析
页面每次向后台传入对应的分类和品牌,后台据分类和品牌进行条件过滤即可。
2.1.2 代码实现
修改搜索微服务com.changgou.service.SearchServiceImpl的搜索方法,添加品牌过滤,代码如下:
代码如下:
@Override
public Map search(Map<String, String> searchMap) throws Exception {
Map<String, Object> resultMap = new HashMap<>();
//有条件才查询Es
if (null != searchMap) {
//组合条件对象
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
//0:关键词
if (StringUtils.isNotEmpty(searchMap.get("keywords"))) {
boolQuery.must(QueryBuilders.matchQuery("name", searchMap.get("keywords")).operator(Operator.AND));
}
//1:条件 品牌 精准匹配条件 比如 苹果
if (StringUtils.isNotEmpty(searchMap.get("brand"))) {
boolQuery.filter(QueryBuilders.termQuery("brandName", searchMap.get("brand")));
}
//4. 原生搜索实现类
NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
nativeSearchQueryBuilder.withQuery(boolQuery);
//6. 品牌聚合(分组)查询 对于这个字段进行聚合查询,类似于group by
String skuBrand = "skuBrand";
nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms(skuBrand).field("brandName"));
//10: 执行查询, 返回结果对象
AggregatedPage<SkuInfo> aggregatedPage = esTemplate.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 (null != hits) {
for (SearchHit hit : hits) {
SkuInfo skuInfo = JSON.parseObject(hit.getSourceAsString(), SkuInfo.class);
list.add((T) skuInfo);
}
}
return new AggregatedPageImpl<T>(list, pageable, hits.getTotalHits(), searchResponse.getAggregations());
}
});
//11. 总条数
resultMap.put("total", aggregatedPage.getTotalElements());
//12. 总页数
resultMap.put("totalPages", aggregatedPage.getTotalPages());
//13. 查询结果集合
resultMap.put("rows", aggregatedPage.getContent());
//14. 获取品牌聚合结果
StringTerms brandTerms = (StringTerms) aggregatedPage.getAggregation(skuBrand);
List<String> brandList = brandTerms.getBuckets().stream().map(bucket -> bucket.getKeyAsString()).collect(Collectors.toList());
resultMap.put("brandList", brandList);
return resultMap;
}
return null;
}
测试时可多加入brand来实现品牌的指定查询
2.2 规格过滤
2.2.1 需求分析
规格这一部分,需要向后台发送规格名字以及规格值,我们可以按照一定要求来发送数据,例如规格名字以特殊前缀提交到后台:spec_网络制式:电信4G、spec_显示屏尺寸:4.0-4.9英寸
后台接到数据后,可以根据前缀spec_来区分是否是规格,如果以spec_xxx
开始的数据则为规格数据,需要根据指定规格找信息。
spechMap.规格名字.keyword
2.2.2 代码实现
修改com.changgou.service.SearchServiceImpl的搜索方法,增加规格查询操作,代码如下:
代码如下:
@Override
public Map search(Map<String, String> searchMap) throws Exception {
Map<String, Object> resultMap = new HashMap<>();
//有条件才查询Es
if (null != searchMap) {
//组合条件对象
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
//0:关键词
if (!StringUtils.isEmpty(searchMap.get("keywords"))) {
boolQuery.must(QueryBuilders.matchQuery("name", searchMap.get("keywords")).operator(Operator.AND));
}
//1:条件 品牌
if (!StringUtils.isEmpty(searchMap.get("brand"))) {
boolQuery.filter(QueryBuilders.termQuery("brandName", searchMap.get("brand")));
}
//2:条件 规格 和前端商量好指定传参的名称,spec_颜色=黑色 这样传递并做一个精准匹配
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));
}
}
//4. 原生搜索实现类
NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
nativeSearchQueryBuilder.withQuery(boolQuery);
//6. 品牌聚合(分组)查询
String skuBrand = "skuBrand";
nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms(skuBrand).field("brandName"));
//7. 规格聚合(分组)查询
String skuSpec = "skuSpec";
nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms(skuSpec).field("spec.keyword"));
//10: 执行查询, 返回结果对象
AggregatedPage<SkuInfo> aggregatedPage = esTemplate.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 (null != hits) {
for (SearchHit hit : hits) {
SkuInfo skuInfo = JSON.parseObject(hit.getSourceAsString(), SkuInfo.class);
list.add((T) skuInfo);
}
}
return new AggregatedPageImpl<T>(list, pageable, hits.getTotalHits(), searchResponse.getAggregations());
}
});
//11. 总条数
resultMap.put("total", aggregatedPage.getTotalElements());
//12. 总页数
resultMap.put("totalPages", aggregatedPage.getTotalPages());
//13. 查询结果集合
resultMap.put("rows", aggregatedPage.getContent());
//14. 获取品牌聚合结果
StringTerms brandTerms = (StringTerms) aggregatedPage.getAggregation(skuBrand);
List<String> brandList = brandTerms.getBuckets().stream().map(bucket -> bucket.getKeyAsString()).collect(Collectors.toList());
resultMap.put("brandList", brandList);
//15. 获取规格聚合结果
StringTerms specTerms = (StringTerms) aggregatedPage.getAggregation(skuSpec);
List<String> specList = specTerms.getBuckets().stream().map(bucket -> bucket.getKeyAsString()).collect(Collectors.toList());
resultMap.put("specList", specList(specList));
return resultMap;
}
return null;
}
//处理规格集合
public Map<String, Set<String>> specList(List<String> specList) {
Map<String, Set<String>> specMap = new HashMap<>();
if (null != specList && specList.size() > 0) {
for (String spec : specList) {
Map<String, String> map = JSON.parseObject(spec, Map.class);
Set<Map.Entry<String, String>> entries = map.entrySet();
for (Map.Entry<String, String> entry : entries) {
String key = entry.getKey();
String value = entry.getValue();
Set<String> specValues = specMap.get(key);
if (null == specValues) {
specValues = new HashSet<>();
}
specValues.add(value);
specMap.put(key, specValues);
}
}
}
return specMap;
}
可加入spec_颜色=红色
2.3 价格区间查询
2.3.1 需求分析
价格区间查询,每次需要将价格传入到后台,前端传入后台的价格大概是price=0-500
或者price=500-1000
依次类推,最后一个是price=3000
,后台可以根据-分割,如果分割得到的结果最多有2个,第1个表示x<price
,第2个表示price<=y
。
2.3.2 代码实现
修改com.changgou.service.impl.SearchServiceImpl的搜索方法,增加价格区间查询操作,代码如下:
代码如下:
@Override
public Map search(Map<String, String> searchMap) throws Exception {
Map<String, Object> resultMap = new HashMap<>();
//有条件才查询Es
if (null != searchMap) {
//组合条件对象
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
//0:关键词
if (!StringUtils.isEmpty(searchMap.get("keywords"))) {
boolQuery.must(QueryBuilders.matchQuery("name", searchMap.get("keywords")).operator(Operator.AND));
}
//1:条件 品牌
if (!StringUtils.isEmpty(searchMap.get("brand"))) {
boolQuery.filter(QueryBuilders.termQuery("brandName", searchMap.get("brand")));
}
//2:条件 规格
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));
}
}
//3:条件 价格 0-500 500-1000 5000 如有一个值就打大于,两个值为一个区间
if (StringUtils.isNotEmpty(searchMap.get("price"))) {
String[] p = searchMap.get("price").split("-");
if (p.length == 2) {
boolQuery.filter(QueryBuilders.rangeQuery("price").lte(p[1]));
}
boolQuery.filter(QueryBuilders.rangeQuery("price").gte(p[0]));
}
//4. 原生搜索实现类
NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
nativeSearchQueryBuilder.withQuery(boolQuery);
//6. 品牌聚合(分组)查询
String skuBrand = "skuBrand";
nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms(skuBrand).field("brandName"));
//7. 规格聚合(分组)查询
String skuSpec = "skuSpec";
nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms(skuSpec).field("spec.keyword"));
//10: 执行查询, 返回结果对象
AggregatedPage<SkuInfo> aggregatedPage = esTemplate.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 (null != hits) {
for (SearchHit hit : hits) {
SkuInfo skuInfo = JSON.parseObject(hit.getSourceAsString(), SkuInfo.class);
list.add((T) skuInfo);
}
}
return new AggregatedPageImpl<T>(list, pageable, hits.getTotalHits(), searchResponse.getAggregations());
}
});
//11. 总条数
resultMap.put("total", aggregatedPage.getTotalElements());
//12. 总页数
resultMap.put("totalPages", aggregatedPage.getTotalPages());
//13. 查询结果集合
resultMap.put("rows", aggregatedPage.getContent());
//14. 获取品牌聚合结果
StringTerms brandTerms = (StringTerms) aggregatedPage.getAggregation(skuBrand);
List<String> brandList = brandTerms.getBuckets().stream().map(bucket -> bucket.getKeyAsString()).collect(Collectors.toList());
resultMap.put("brandList", brandList);
//15. 获取规格聚合结果
StringTerms specTerms = (StringTerms) aggregatedPage.getAggregation(skuSpec);
List<String> specList = specTerms.getBuckets().stream().map(bucket -> bucket.getKeyAsString()).collect(Collectors.toList());
resultMap.put("specList", specList(specList));
return resultMap;
}
return null;
}
price=1-500
3 搜索分页
3.1 分页分析
页面需要实现分页搜索,所以我们后台每次查询的时候,需要实现分页。用户页面每次会传入当前页和每页查询多少条数据,当然如果不传入每页显示多少条数据,默认查询30条即可。
3.2 分页实现
分页使用PageRequest.of( pageNo- 1, pageSize);实现,第1个参数表示第N页,从0开始,第2个参数表示每页显示多少条,实现代码如下:
代码如下:
@Override
public Map search(Map<String, String> searchMap) throws Exception {
Map<String, Object> resultMap = new HashMap<>();
//有条件才查询Es
if (null != searchMap) {
//组合条件对象
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
//0:关键词
if (!StringUtils.isEmpty(searchMap.get("keywords"))) {
boolQuery.must(QueryBuilders.matchQuery("name", searchMap.get("keywords")).operator(Operator.AND));
}
//1:条件 品牌
if (!StringUtils.isEmpty(searchMap.get("brand"))) {
boolQuery.filter(QueryBuilders.termQuery("brandName", searchMap.get("brand")));
}
//2:条件 规格
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));
}
}
//3:条件 价格
if (!StringUtils.isEmpty(searchMap.get("price"))) {
String[] p = searchMap.get("price").split("-");
boolQuery.filter(QueryBuilders.rangeQuery("price").gte(p[0]));
if (p.length == 2) {
boolQuery.filter(QueryBuilders.rangeQuery("price").lte(p[1]));
}
}
//4. 原生搜索实现类
NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
nativeSearchQueryBuilder.withQuery(boolQuery);
//6. 品牌聚合(分组)查询
String skuBrand = "skuBrand";
nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms(skuBrand).field("brandName"));
//7. 规格聚合(分组)查询
String skuSpec = "skuSpec";
nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms(skuSpec).field("spec.keyword"));
//开启分页查询
String pageNum = searchMap.get("pageNum"); //当前页
String pageSize = searchMap.get("pageSize"); //每页显示多少条
if (StringUtils.isEmpty(pageNum)){
pageNum ="1";
}
if (StringUtils.isEmpty(pageSize)){
pageSize="30";
}
//设置分页
//第一个参数:当前页 是从0开始
//第二个参数:每页显示多少条
nativeSearchQueryBuilder.withPageable(PageRequest.of(Integer.parseInt(pageNum)-1,Integer.parseInt(pageSize)));
//10: 执行查询, 返回结果对象
AggregatedPage<SkuInfo> aggregatedPage = esTemplate.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 (null != hits) {
for (SearchHit hit : hits) {
SkuInfo skuInfo = JSON.parseObject(hit.getSourceAsString(), SkuInfo.class);
list.add((T) skuInfo);
}
}
return new AggregatedPageImpl<T>(list, pageable, hits.getTotalHits(), searchResponse.getAggregations());
}
});
//11. 总条数
resultMap.put("total", aggregatedPage.getTotalElements());
//12. 总页数
resultMap.put("totalPages", aggregatedPage.getTotalPages());
//13. 查询结果集合
resultMap.put("rows", aggregatedPage.getContent());
//14. 获取品牌聚合结果
StringTerms brandTerms = (StringTerms) aggregatedPage.getAggregation(skuBrand);
List<String> brandList = brandTerms.getBuckets().stream().map(bucket -> bucket.getKeyAsString()).collect(Collectors.toList());
resultMap.put("brandList", brandList);
//15. 获取规格聚合结果
StringTerms specTerms = (StringTerms) aggregatedPage.getAggregation(skuSpec);
List<String> specList = specTerms.getBuckets().stream().map(bucket -> bucket.getKeyAsString()).collect(Collectors.toList());
resultMap.put("specList", specList(specList));
//16. 返回当前页
resultMap.put("pageNum", pageNum);
return resultMap;
}
return null;
}
pageNum和pageSize可以指定
4 搜索排序
4.1 排序分析
排序这里总共有根据价格排序、根据评价排序、根据新品排序、根据销量排序,排序要想实现非常简单,只需要告知排序的域以及排序方式即可实现。
价格排序:只需要根据价格高低排序即可,降序价格高->低,升序价格低->高
评价排序:评价分为好评、中评、差评,可以在数据库中设计3个列,用来记录好评、中评、差评的量,每次排序的时候,好评的比例来排序,当然还要有条数限制,评价条数需要超过N条。
新品排序:直接根据商品的发布时间或者更新时间排序。
销量排序:销量排序除了销售数量外,还应该要有时间段限制。
.2 排序实现
这里我们不单独针对某个功能实现排序,我们只需要在后台接收2个参数,分别是排序域名字和排序方式,代码如下:
@Override
public Map search(Map<String, String> searchMap) throws Exception {
Map<String, Object> resultMap = new HashMap<>();
//有条件才查询Es
if (null != searchMap) {
//组合条件对象
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
//0:关键词
if (!StringUtils.isEmpty(searchMap.get("keywords"))) {
boolQuery.must(QueryBuilders.matchQuery("name", searchMap.get("keywords")).operator(Operator.AND));
}
//1:条件 品牌
if (!StringUtils.isEmpty(searchMap.get("brand"))) {
boolQuery.filter(QueryBuilders.termQuery("brandName", searchMap.get("brand")));
}
//2:条件 规格
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));
}
}
//3:条件 价格
if (!StringUtils.isEmpty(searchMap.get("price"))) {
String[] p = searchMap.get("price").split("-");
boolQuery.filter(QueryBuilders.rangeQuery("price").gte(p[0]));
if (p.length == 2) {
boolQuery.filter(QueryBuilders.rangeQuery("price").lte(p[1]));
}
}
//4. 原生搜索实现类
NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
nativeSearchQueryBuilder.withQuery(boolQuery);
//6. 品牌聚合(分组)查询
String skuBrand = "skuBrand";
nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms(skuBrand).field("brandName"));
//7. 规格聚合(分组)查询
String skuSpec = "skuSpec";
nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms(skuSpec).field("spec.keyword"));
//8: 排序 判断有无传过来值即可
if (!StringUtils.isEmpty(searchMap.get("sortField"))) {
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));
}
}
String pageNum = searchMap.get("pageNum");
if (null == pageNum) {
pageNum = "1";
}
//9: 分页
nativeSearchQueryBuilder.withPageable(PageRequest.of(Integer.parseInt(pageNum) - 1, Page.pageSize));
//10: 执行查询, 返回结果对象
AggregatedPage<SkuInfo> aggregatedPage = esTemplate.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 (null != hits) {
for (SearchHit hit : hits) {
SkuInfo skuInfo = JSON.parseObject(hit.getSourceAsString(), SkuInfo.class);
list.add((T) skuInfo);
}
}
return new AggregatedPageImpl<T>(list, pageable, hits.getTotalHits(), searchResponse.getAggregations());
}
});
//11. 总条数
resultMap.put("total", aggregatedPage.getTotalElements());
//12. 总页数
resultMap.put("totalPages", aggregatedPage.getTotalPages());
//13. 查询结果集合
resultMap.put("rows", aggregatedPage.getContent());
//14. 获取品牌聚合结果
StringTerms brandTerms = (StringTerms) aggregatedPage.getAggregation(skuBrand);
List<String> brandList = brandTerms.getBuckets().stream().map(bucket -> bucket.getKeyAsString()).collect(Collectors.toList());
resultMap.put("brandList", brandList);
//15. 获取规格聚合结果
StringTerms specTerms = (StringTerms) aggregatedPage.getAggregation(skuSpec);
List<String> specList = specTerms.getBuckets().stream().map(bucket -> bucket.getKeyAsString()).collect(Collectors.toList());
resultMap.put("specList", specList(specList));
//16. 返回当前页
resultMap.put("pageNum", pageNum);
return resultMap;
}
return null;
}
sortRule=ASC&sortField=price
5 高亮显示
5.1 高亮分析
高亮显示是指根据商品关键字搜索商品的时候,显示的页面对关键字给定了特殊样式,让它显示更加突出,如上图商品搜索中,关键字编程了红色,其实就是给定了红色样式。
5.2 高亮搜索实现步骤解析
将之前的搜索换掉,换成高亮搜索,我们需要做3个步骤:
1.指定高亮域,也就是设置哪个域需要高亮显示
设置高亮域的时候,需要指定前缀和后缀,也就是关键词用什么html标签包裹,再给该标签样式
2.高亮搜索实现
3.将非高亮数据替换成高亮数据
第1点,例如在百度中搜索数据的时候,会有2个地方高亮显示,分别是标题和描述,商城搜索的时候,只是商品名称高亮显示了。而高亮显示其实就是添加了样式,例如<span style="color:red;">笔记本</span>
,而其中span开始标签可以称为前缀,span结束标签可以称为后缀。
第2点,高亮搜索使用ElasticsearchTemplate实现。
第3点,高亮搜索后,会搜出非高亮数据和高亮数据,高亮数据会加上第1点中的高亮样式,此时我们需要将非高亮数据换成高亮数据即可。例如非高亮:华为笔记本性能超强悍
高亮数据:华为<span style="color:red;"笔记本</span>性能超强悍
,将非高亮的换成高亮的,到页面就能显示样式了。
5.3 高亮代码实现
删掉之前com.changgou.service.impl.SearchServiceImpl的搜索方法搜索代码,用下面高亮搜索代码替换:
代码如下:
@Override
public Map search(Map<String, String> searchMap) throws Exception {
Map<String, Object> resultMap = new HashMap<>();
//有条件才查询Es
if (null != searchMap) {
//组合条件对象
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
//0:关键词
if (!StringUtils.isEmpty(searchMap.get("keywords"))) {
boolQuery.must(QueryBuilders.matchQuery("name", searchMap.get("keywords")).operator(Operator.AND));
}
//1:条件 品牌
if (!StringUtils.isEmpty(searchMap.get("brand"))) {
boolQuery.filter(QueryBuilders.termQuery("brandName", searchMap.get("brand")));
}
//2:条件 规格
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));
}
}
//3:条件 价格
if (!StringUtils.isEmpty(searchMap.get("price"))) {
String[] p = searchMap.get("price").split("-");
boolQuery.filter(QueryBuilders.rangeQuery("price").gte(p[0]));
if (p.length == 2) {
boolQuery.filter(QueryBuilders.rangeQuery("price").lte(p[1]));
}
}
//4. 原生搜索实现类
NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
nativeSearchQueryBuilder.withQuery(boolQuery);
//5:高亮
HighlightBuilder.Field field = new HighlightBuilder
.Field("name")
.preTags("<span style='color:red'>")
.postTags("</span>");
nativeSearchQueryBuilder.withHighlightFields(field);
//6. 品牌聚合(分组)查询
String skuBrand = "skuBrand";
nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms(skuBrand).field("brandName"));
//7. 规格聚合(分组)查询
String skuSpec = "skuSpec";
nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms(skuSpec).field("spec.keyword"));
//8: 排序
if (!StringUtils.isEmpty(searchMap.get("sortField"))) {
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));
}
}
String pageNum = searchMap.get("pageNum");
if (null == pageNum) {
pageNum = "1";
}
//9: 分页
nativeSearchQueryBuilder.withPageable(PageRequest.of(Integer.parseInt(pageNum) - 1, Page.pageSize));
//设置高亮域以及高亮的样式 自己定义前后标签和颜色即可 加完后会在这个nativeSearchQueryBuilder中新的属性
HighlightBuilder.Field field = new HighlightBuilder.Field("name")//高亮域
.preTags("<span style='color:red'>")//高亮样式的前缀
.postTags("</span>");//高亮样式的后缀
nativeSearchQueryBuilder.withHighlightFields(field);
//开启查询
/**
* 第一个参数: 条件构建对象
* 第二个参数: 查询操作实体类
* 第三个参数: 查询结果操作对象
*/
//封装查询结果
AggregatedPage<SkuInfo> resultInfo = elasticsearchTemplate.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());
}
});
//11. 总条数
resultMap.put("total", aggregatedPage.getTotalElements());
//12. 总页数
resultMap.put("totalPages", aggregatedPage.getTotalPages());
//13. 查询结果集合
resultMap.put("rows", aggregatedPage.getContent());
//14. 获取品牌聚合结果
StringTerms brandTerms = (StringTerms) aggregatedPage.getAggregation(skuBrand);
List<String> brandList = brandTerms.getBuckets().stream().map(bucket -> bucket.getKeyAsString()).collect(Collectors.toList());
resultMap.put("brandList", brandList);
//15. 获取规格聚合结果
StringTerms specTerms = (StringTerms) aggregatedPage.getAggregation(skuSpec);
List<String> specList = specTerms.getBuckets().stream().map(bucket -> bucket.getKeyAsString()).collect(Collectors.toList());
resultMap.put("specList", specList(specList));
//16. 返回当前页
resultMap.put("pageNum", pageNum);
return resultMap;
}
return null;
}
name=手机
6、最终代码
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.Aggregation;
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.Page;
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.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Service
public class SearchServiceImpl implements SearchService {
@Autowired
private ElasticsearchTemplate elasticsearchTemplate;
@Override
public Map search(Map<String, String> searchMap) {
Map<String,Object> resultMap = new HashMap<>();
//构建查询
if (searchMap != null){
//构建查询条件封装对象
NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
//构建查询对象
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
//按照关键字查询
if (StringUtils.isNotEmpty(searchMap.get("keywords"))){
//模糊匹配,类似于%内容%,and做拼接 想买啥
boolQuery.must(QueryBuilders.matchQuery("name",searchMap.get("keywords")).operator(Operator.AND));
}
//按照品牌进行过滤查询
if (StringUtils.isNotEmpty(searchMap.get("brand"))){
//过滤精准匹配,用作查询具体的品牌 指定具体牌子苹果手机
boolQuery.filter(QueryBuilders.termQuery("brandName",searchMap.get("brand")));
}
//按照规格进行过滤查询
for (String key : searchMap.keySet()) {
//和前端商量好前缀的格式,加入规格,传过来的参数比如spec_64GB或者颜色等等 比如买64GB大小的,用精准匹配 浏览器地址栏+号会自动转换成%2B
if (key.startsWith("spec_")){
String value = searchMap.get(key).replace("%2B","+");
//spec_网络制式
boolQuery.filter(QueryBuilders.termQuery(("specMap."+key.substring(5)+".keyword"),value));
}
}
//按照价格进行区间过滤查询
if (StringUtils.isNotEmpty(searchMap.get("price"))){
String[] prices = searchMap.get("price").split("-");
// 0-500 500-1000 如果长度为2加个小于
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 pageNum = searchMap.get("pageNum"); //当前页
String pageSize = searchMap.get("pageSize"); //每页显示多少条
if (StringUtils.isEmpty(pageNum)){
pageNum ="1";
}
if (StringUtils.isEmpty(pageSize)){
pageSize="30";
}
//设置分页
//第一个参数:当前页 是从0开始
//第二个参数:每页显示多少条
nativeSearchQueryBuilder.withPageable(PageRequest.of(Integer.parseInt(pageNum)-1,Integer.parseInt(pageSize)));
//按照相关字段进行排序查询
// 1.当前域 2.当前的排序操作(升序ASC,降序DESC)
if (StringUtils.isNotEmpty(searchMap.get("sortField")) && StringUtils.isNotEmpty(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));
}
}
//设置高亮域以及高亮的样式 自己定义前后标签和颜色即可 加完后会在这个nativeSearchQueryBuilder中新的属性
HighlightBuilder.Field field = new HighlightBuilder.Field("name")//高亮域
.preTags("<span style='color:red'>")//高亮样式的前缀
.postTags("</span>");//高亮样式的后缀
nativeSearchQueryBuilder.withHighlightFields(field);
//开启查询
/**
* 第一个参数: 条件构建对象
* 第二个参数: 查询操作实体类
* 第三个参数: 查询结果操作对象
*/
//封装查询结果
AggregatedPage<SkuInfo> resultInfo = elasticsearchTemplate.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());
}
});
//封装最终的返回结果
//总记录数
resultMap.put("total",resultInfo.getTotalElements());
//总页数
resultMap.put("totalPages",resultInfo.getTotalPages());
//数据集合
resultMap.put("rows",resultInfo.getContent());
//封装品牌的分组结果
StringTerms brandTerms = (StringTerms) resultInfo.getAggregation(skuBrand);
List<String> brandList = brandTerms.getBuckets().stream().map(bucket -> bucket.getKeyAsString()).collect(Collectors.toList());
resultMap.put("brandList",brandList);
//封装规格分组结果
StringTerms specTerms= (StringTerms) resultInfo.getAggregation(skuSpec);
List<String> specList = specTerms.getBuckets().stream().map(bucket -> bucket.getKeyAsString()).collect(Collectors.toList());
resultMap.put("specList",specList);
//当前页
resultMap.put("pageNum",pageNum);
return resultMap;
}
return null;
}
}
开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!
更多推荐
所有评论(0)