package com.leyou.search.service;
import com.leyou.item.pojo.Brand;
import com.leyou.item.pojo.Category;
import com.leyou.item.pojo.SpecParam;
import com.leyou.search.Repository.GoodsRepository;
import com.leyou.search.client.BrandClient;
import com.leyou.search.client.CategoryClient;
import com.leyou.search.client.SpecificationClient;
import com.leyou.search.pojo.Goods;
import com.leyou.search.pojo.SearchRequest;
import com.leyou.search.pojo.SearchResult;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.LongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.FetchSourceFilter;
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;
/**
* 聚合查询:根据页面请求的过滤条件被选项,动态显示 SearchResult 对象的数据(页面过滤可选项数据 和 分页商品搜索结果)
*/
@Service
public class SearchService {
@Autowired
private GoodsRepository goodsRepository;
@Autowired
private CategoryClient categoryClient;
@Autowired
private BrandClient brandClient;
@Autowired
private SpecificationClient specClient;
private Logger logger = LoggerFactory.getLogger(SearchService.class);
@Autowired
private ElasticsearchTemplate elasticsearchTemplate;
public SearchResult search(SearchRequest searchRequest) {
if(StringUtils.isBlank(searchRequest.getKey())){
return null;
}
//定义分类和品牌存放的集合
List<Category> categories = null;
List<Brand> brands = null;
List<Map<String, Object>> specs = null;
//1、创建原生查询过滤器
NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
//2、指定查询的字段,即指定结果集返回的字段
queryBuilder.withSourceFilter(new FetchSourceFilter(new String[]{"id", "skus", "subTitle", "price"}, null));
//3、加入请求中的过滤条件
queryBuilder.withQuery(getFilterQueryBuilder(searchRequest));
//3、加入分页,es的分页从1开始
queryBuilder.withPageable(PageRequest.of(searchRequest.getPage() - 1, searchRequest.getSize()));
//4、加入请求中的排序条件
String sortBy = searchRequest.getSortBy();
Boolean descending = searchRequest.getDescending();
if (StringUtils.isNotBlank(sortBy)) {
queryBuilder.withSort(SortBuilders.fieldSort(sortBy).order(descending ? SortOrder.DESC : SortOrder.ASC));
}
//5、构建聚合,品牌和分类都需要进行聚合,会得到2个聚合结果
String aggCname = "aggCname"; //聚合名称
String aggBname = "aggBname"; //聚合名称
queryBuilder.addAggregation(AggregationBuilders.terms(aggCname).field("cid3")); //field:聚合字段 ,根据最小的3级分类聚合
queryBuilder.addAggregation(AggregationBuilders.terms(aggBname).field("brandId")); //根据品牌id聚合,得到每个品牌在页面的过滤栏的信息
//进行聚合查询
AggregatedPage<Goods> resultPage = (AggregatedPage<Goods>) goodsRepository.search(queryBuilder.build());
//获得分类聚合结果
categories = getCategoryAggResult(aggCname, resultPage);
//获得品牌聚合结果
brands = getBrandAggResult(aggBname, resultPage);
//选中一个商品分类后才显示对应的规格参数过滤项,即仅当分类数为1时进行规格参数的聚合
if (categories != null && categories.size() == 1) {
//获取规格参数聚合结果
//specs = getSpecAggResult(categories);
specs=null;
}
return new SearchResult(resultPage.getTotalElements(), (long) resultPage.getTotalPages(), resultPage.getContent(), categories, brands, specs);
}
private QueryBuilder getFilterQueryBuilder(SearchRequest searchRequest) {
try {
//查询字段中包含布尔类型的查询构建器
BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
//获取searchRequest中的属性
String key = searchRequest.getKey();
Map<String, String> filter = searchRequest.getFilter();
//判断搜索条件是否为空
if (StringUtils.isBlank(key)) {
return null;
}
//构建搜索条件
// 添加must的条件 此处为匹配Goods中的all字段
queryBuilder.must(QueryBuilders.matchQuery("all", key));
BoolQueryBuilder filterQueryBuilder = QueryBuilders.boolQuery();
if (!filter.isEmpty()) {
for (Map.Entry<String, String> filterEntry : filter.entrySet()) {
String name = filterEntry.getKey();
String value = filterEntry.getValue();
//过滤条件中,分类和品牌传入的都是id,要进行额外的判断
if (name != "cid2" && name != "brandId") {
name = "specs." + name + ".keyword";
}
filterQueryBuilder.must(QueryBuilders.termQuery(name, value)); //分词精确查询
}
}
queryBuilder.filter(filterQueryBuilder);
return queryBuilder;
} catch (Exception e) {
logger.error("构建过滤参数出现异常:{}", e);
e.printStackTrace();
}
return null;
}
private List<Map<String, Object>> getSpecAggResult(List<Category> categories) {
try {
//传入的categories只有1个,查询该分类对应的所有规格参数
List<SpecParam> specParams = this.specClient.querySpecParam(null, categories.get(0).getId(), true, null);
//进行聚合之后将每一个SpecParam对象拼为Map集合以{k:specparam.name,options:同名聚合结果,即一个Aggregation中的所有桶信息}
NativeSearchQueryBuilder query = new NativeSearchQueryBuilder();
//对每一个规格参数都做聚合
specParams.forEach(specParam -> {
String key = specParam.getName();
query.addAggregation(AggregationBuilders.terms(key) //聚合名称
.field("specs." + key + ".keyword")); //聚合的字段
});
AggregatedPage<Goods> search = (AggregatedPage<Goods>) this.goodsRepository.search(query.build());
//解析聚合结果,封装成集合返回
List<Map<String, Object>> specs = new ArrayList<>();
//将所有的聚合转为map形式,方便获取,key为specs中的每一个规格参数名称
Map<String, Aggregation> aggMap = search.getAggregations().asMap();
for (SpecParam specParam : specParams) {
Map<String, Object> specMap = new HashMap<>();
String key = specParam.getName();
//根据key获取
没有合适的资源?快使用搜索试试~ 我知道了~
资源推荐
资源详情
资源评论
收起资源包目录
微服务商城,使用全套SpringCloud组件,使用JWT结合非对称密钥实现分布式 (931个子文件)
.babelrc 317B
SearchService.class 14KB
GoodsService.class 10KB
IndexService.class 8KB
Goods.class 7KB
Sku.class 7KB
OrderController.class 7KB
GoodsController.class 6KB
OrderService.class 6KB
Order.class 6KB
CartService.class 6KB
CookieUtils.class 5KB
SpecificationController.class 5KB
UserService.class 5KB
BrandService.class 5KB
ExceptionEnum.class 5KB
GoodsService.class 5KB
BrandController.class 5KB
AddressController.class 5KB
PayHelper.class 5KB
SpecificationService.class 4KB
Cart.class 4KB
User.class 4KB
AuthController.class 4KB
JsonUtils.class 4KB
IdWorker.class 4KB
SearchResult.class 4KB
AddressService.class 4KB
JwtUtils.class 4KB
UserController.class 3KB
Address.class 3KB
JwtProperties.class 3KB
SmsUtils.class 3KB
RsaUtils.class 3KB
SpecGroup.class 3KB
SpuBo.class 3KB
CartController.class 3KB
LoginFilter.class 3KB
SmsProperties.class 3KB
UploadService.class 3KB
Spu.class 3KB
NumberUtils.class 3KB
CategoryController.class 3KB
JwtTest.class 3KB
LoginInterceptor.class 2KB
LgoinInterceptor.class 2KB
SpecParam.class 2KB
UploadProperties.class 2KB
SmsListener.class 2KB
OrderDetail.class 2KB
GoodsHtmlService.class 2KB
OrderStatus.class 2KB
SwaggerConfig.class 2KB
SearchRequest.class 2KB
UploadController.class 2KB
FastDFSTest.class 2KB
CategoryService.class 2KB
JwtProperties.class 2KB
JwtProperties.class 2KB
JwtProperties.class 2KB
Brand.class 2KB
SearchController.class 2KB
PageResult.class 2KB
AuthService.class 2KB
SpuDetail.class 2KB
MvcConfig.class 2KB
Category.class 2KB
GlobalCorsConfig.class 2KB
GlobalCorsConfig.class 2KB
GoodsController.class 2KB
GoodsListener.class 2KB
Test.class 2KB
GoodsListener.class 1KB
PayProperties.class 1KB
GoodsApi.class 1KB
LeYouWebMvcConfiguration.class 1KB
CodecUtils.class 1KB
CodecUtils.class 1KB
PayConfig.class 1KB
Stock.class 1KB
ObjectUtils.class 1KB
PayState.class 1KB
BrandMapper.class 1KB
SpecApi.class 1KB
UserInfo.class 940B
LeyouOrderApplication.class 932B
FilterProperties.class 926B
IdWorkerConfig.class 909B
SpuApi.class 895B
LeyouItemApplication.class 890B
LeyouGoodsWebApplication.class 877B
LeyouCartApplication.class 875B
LeyouGatewayApplication.class 874B
LeyouSearchApplication.class 871B
UserApplication.class 870B
IdWorkerProperties.class 870B
LeyouAuthApplication.class 865B
LeyouRegisterApplication.class 816B
LeyouUploadApplication.class 808B
IndexService$2.class 795B
共 931 条
- 1
- 2
- 3
- 4
- 5
- 6
- 10
资源评论
2401_87496566
- 粉丝: 1091
- 资源: 5285
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
最新资源
- 基于SpringBoot框架和SaaS模式,立志为中小企业提供开源好用的ERP软件,目前专注进销存+财务+生产功能
- C#ASP.NET口腔门诊会员病历管理系统源码 门诊会员管理系统源码数据库 SQL2008源码类型 WebForm
- 灰狼优化算法(Grey Wolf Optimizer,GWO)是一种群智能优化算法
- 基于 promise 的网络请求库,可以运行 node.js 和浏览器中 本库基于Axios 原库v1.3.4版本进行适配
- JAVA的SpringBoot宠物医院管理系统源码数据库 MySQL源码类型 WebForm
- 基于Huawei LiteOS内核演进发展的新一代内核,Huawei LiteOS是面向IoT领域构建的轻量级物联网操作系统
- STM32Fxx英文参考手册 + Jlink下载教程
- 本仓提供了HarmonyOS NEXT开源组件市场工具,这是一个开源的插件,可以直接安装在DevEco Studio中
- 贪心算法 - 数据结构与算法
- C#ASP.NET网络进销存管理系统源码数据库 SQL2008源码类型 WebForm
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功