2)总数量
共 {{total}} 商品
{{ search.page }}/{{ totalPage }}
<a class=“btn-arrow” href=“#” @click.prevent=“prePage” style=“display: inline-block”><
<a class=“btn-arrow” href=“#” @click.prevent=“nextPage” style=“display: inline-block”>>
(3)(实现点击发送请求刷新数据)监控page的状态如果发生变化就发送请求
watch:{
search:{//page在search当中
deep:true,
handler(){
if(!oldVal || !oldVal.key){
return;
}
//把请求参数写到URL当中,防止页面刷新的时候page丢失
location.search = “?” + ly.stringify(this.search);
}
}
},
数据变换成功
1、对分类和品牌(进行聚合)
(1)拓展PageResult,创建SearchResult
package com.leyou.search.pojo;
import com.leyou.common.vo.PageResult;
import com.leyou.item.pojo.Brand;
import com.leyou.item.pojo.Category;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@Data
public class SearchResult extends PageResult {
private List categories;
private List brands;
public SearchResult(){
}
public SearchResult(Long total, Integer totalPage, List items, List categories, List brands) {
super(total, totalPage, items);
this.categories = categories;
this.brands = brands;
}
}
(2)修改SearchService的search方法(聚合分类和品牌)
@Autowired
private ElasticsearchTemplate template;
public PageResult search(SearchRequest request) {
Integer page = request.getPage() - 1;
Integer size = request.getSize();
//创建查询构建器SpringDataElasticSearch - NativeSearchQueryBuilder过滤聚合高亮查询
NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
//0 结果过滤
queryBuilder.withSourceFilter(new FetchSourceFilter(new String[]{“id”,“subTitle”,“skus”},null));
//1 分页
queryBuilder.withPageable(PageRequest.of(page,size));
//2 过滤
queryBuilder.withQuery(QueryBuilders.matchQuery(“all”,request.getKey()));
//3 聚合分类和品牌
//3.1集合分类
String categoryAggName = “category_agg”;
queryBuilder.addAggregation(AggregationBuilders.terms(categoryAggName).field(“cid3”));
//3.2对品牌进行聚合
String brandAggName = “brand_agg”;
queryBuilder.addAggregation(AggregationBuilders.terms(brandAggName).field(“brandId”));
//4 查询
AggregatedPage result = template.queryForPage(queryBuilder.build(), Goods.class);
//5 解析结果
//5.1解析分页结果
long total = result.getTotalElements();
int totalPage = result.getTotalPages();
List goodsList = result.getContent();
//5.2解析聚合结果
Aggregations aggs = result.getAggregations();
List categories = parseCategoryAgg(aggs.get(categoryAggName));
List brands = parseBrandAgg(aggs.get(brandAggName));
return new PageResult<>(total,totalPage,goodsList);
}
(3)完善上述两个方法
1)添加一个新的API接口对应的方法
@GetMapping(“brand/brands”)
List queryBrandByIds(@RequestParam(“ids”) List ids);
2)实现对应的控制层
3)实现brandService
完善前先让BrandMapper继承BaseMapper
完善BrandService当中的queryByIds方法
public List queryByIds(List ids) {
List brands = brandMapper.selectByIdList(ids);
if(CollectionUtils.isEmpty(brands)){
//查询失败抛出自定义的通用异常
throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
}
return brands;
}
4)继续完善ly-search当中的SearchService当中的两个方法
private List parseBrandAgg(LongTerms terms) {
try {
List ids = terms.getBuckets()
.stream().map(bucket -> bucket.getKeyAsNumber().longValue())
.collect(Collectors.toList());
List list = brandClient.queryBrandByIds(ids);
return list;
}catch (Exception e){
return null;
}
}
private List parseCategoryAgg(LongTerms terms) {
try {
List ids = terms.getBuckets()
.stream().map(bucket -> bucket.getKeyAsNumber().longValue())
.collect(Collectors.toList());
List categories = categoryClient.queryCategoryByIds(ids);
return categories;
}catch (Exception e){
return null;
}
}
5)修改search方法的返回值类型
return new SearchResult(total,totalPage,goodsList,categories,brands);
6)为了防止手残添加全都的代码
package com.leyou.search.service;
import com.fasterxml.jackson.core.type.TypeReference;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.JsonUtils;
import com.leyou.common.vo.PageResult;
import com.leyou.item.pojo.*;
import com.leyou.search.client.BrandClient;
import com.leyou.search.client.CategoryClient;
import com.leyou.search.client.GoodsClient;
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 com.leyou.search.repository.GoodsRepository;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.lucene.util.CollectionUtil;
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.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.LongTerms;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
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 org.springframework.util.CollectionUtils;
import java.util.*;
import java.util.stream.Collectors;
@Service
public class SearchService {
@Autowired
private CategoryClient categoryClient;
@Autowired
private BrandClient brandClient;
@Autowired
private GoodsClient goodsClient;
@Autowired
private SpecificationClient specClient;
@Autowired
private GoodsRepository repository;
@Autowired
private ElasticsearchTemplate template;
public Goods buildGoods(Spu spu){
//查询分类
List categories = categoryClient.queryCategoryByIds(
Arrays.asList(spu.getCid1(), spu.getCid2(), spu.getCid3()));
if(CollectionUtils.isEmpty(categories)){
throw new LyException(ExceptionEnum.CATEGORY_NOT_FOND);
}
//将categories集合当中所有的name取出来封装为一个字符串集合
List names = categories.stream().map(Category::getName).collect(Collectors.toList());
//查询品牌
Brand brand = brandClient.queryBrandById(spu.getBrandId());
if(brand == null){
throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
}
//搜索字段 将字符串集合变成一个字符串以空格为分隔拼接到后面
String all = spu.getTitle() + StringUtils.join(names," ") + brand.getName();
//查询sku
List skuList = goodsClient.querySkuBySpuId(spu.getId());
if(CollectionUtils.isEmpty(skuList)){
throw new LyException(ExceptionEnum.GOODS_SKU_NOT_FOND);
}
//对Sku进行处理
List<Map<String,Object>> skus = new ArrayList<>();
//价格集合
ArrayList priceList = new ArrayList();
for (Sku sku : skuList) {
Map<String,Object> map = new HashMap<>();
map.put(“id”,sku.getId());
map.put(“title”,sku.getTitle());
map.put(“price”,sku.getPrice());
//截取sku当中图片逗号之前的第一个
map.put(“images”,StringUtils.substringBefore(sku.getImages(),“,”));
skus.add(map);
//处理价格
priceList.add(sku.getPrice());
}
//查询规格参数
List params = specClient.queryParamList(null, spu.getCid3(), true);
if(CollectionUtils.isEmpty(params)){
throw new LyException(ExceptionEnum.SPEC_GROUP_NOT_FOND);
}
//查询商品详情
SpuDetail spuDetail = goodsClient.queryDetailById(spu.getId());
//获取通用规格参数,获取到通用规格参数的JSON字符串,将其转换为Map集合
Map<Long, String> genericSpec = JsonUtils.toMap(spuDetail.getGenericSpec(), Long.class, String.class);
//获取特有规格参数,获取到特有规格参数的JSON字符串,将其转换为Map集合,而Map集合当中的值是String,键为List集合
Map<Long, List> specailSpec =
JsonUtils.nativeRead(spuDetail.getSpecialSpec(),
new TypeReference<Map<Long, List>>(){});
//处理规格参数,key是规格参数的名称,值是规格参数的值
Map<String,Object> specs = new HashMap<>();
for (SpecParam param : params) {
//规格名称
String key = param.getName();
Object value = “”;
//判断是否是通过规格参数
if(param.getGeneric()){
value = genericSpec.get(param.getId());
//判断是否是数值类型
if(param.getNumeric()){
//处理成段
value = chooseSegment(value.toString(),param);
}
}else {
value = specailSpec.get(param.getId());
}
//存入map
specs.put(key,value);
}
//构建good对象
Goods goods = new Goods();
goods.setBrandId(spu.getBrandId());
goods.setCid1(spu.getCid1());
goods.setCid2(spu.getCid2());
goods.setCid3(spu.getCid3());
goods.setCreateTime(spu.getCreateTime());
goods.setId(spu.getId());
goods.setAll(all);//搜索字段,包含标题,分类,品牌,规格等信息
goods.setPrice(priceList);// 所有sku价格的集合
goods.setSkus(JsonUtils.toString(skus));// 所有sku的集合的JSON格式
goods.setSpecs(specs);// 所有可以搜索的规格参数
goods.setSubTitle(spu.getSubTitle());
return goods;
}
private String chooseSegment(String value, SpecParam p) {
double val = NumberUtils.toDouble(value);
String result = “其它”;
// 保存数值段
for (String segment : p.getSegments().split(“,”)) {
String[] segs = segment.split(“-”);
// 获取数值范围
double begin = NumberUtils.toDouble(segs[0]);
double end = Double.MAX_VALUE;
if(segs.length == 2){
end = NumberUtils.toDouble(segs[1]);
}
// 判断是否在范围内
if(val >= begin && val < end){
if(segs.length == 1){
result = segs[0] + p.getUnit() + “以上”;
}else if(begin == 0){
result = segs[1] + p.getUnit() + “以下”;
}else{
result = segment + p.getUnit();
}
break;
}
}
return result;
}
public PageResult search(SearchRequest request) {
Integer page = request.getPage() - 1;
Integer size = request.getSize();
//创建查询构建器SpringDataElasticSearch - NativeSearchQueryBuilder过滤聚合高亮查询
NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
//0 结果过滤
queryBuilder.withSourceFilter(new FetchSourceFilter(new String[]{“id”,“subTitle”,“skus”},null));
//1 分页
queryBuilder.withPageable(PageRequest.of(page,size));
//2 过滤
queryBuilder.withQuery(QueryBuilders.matchQuery(“all”,request.getKey()));
//3 聚合分类和品牌
//3.1集合分类
String categoryAggName = “category_agg”;
queryBuilder.addAggregation(AggregationBuilders.terms(categoryAggName).field(“cid3”));
//3.2对品牌进行聚合
String brandAggName = “brand_agg”;
queryBuilder.addAggregation(AggregationBuilders.terms(brandAggName).field(“brandId”));
//4 查询
AggregatedPage result = template.queryForPage(queryBuilder.build(), Goods.class);
//5 解析结果
//5.1解析分页结果
long total = result.getTotalElements();
int totalPage = result.getTotalPages();
List goodsList = result.getContent();
//5.2解析聚合结果
Aggregations aggs = result.getAggregations();
List categories = parseCategoryAgg(aggs.get(categoryAggName));
List brands = parseBrandAgg(aggs.get(brandAggName));
return new SearchResult(total,totalPage,goodsList,categories,brands);
}
private List parseBrandAgg(LongTerms terms) {
try {
List ids = terms.getBuckets()
.stream().map(bucket -> bucket.getKeyAsNumber().longValue())
.collect(Collectors.toList());
List list = brandClient.queryBrandByIds(ids);
return list;
}catch (Exception e){
return null;
}
}
private List parseCategoryAgg(LongTerms terms) {
try {
List ids = terms.getBuckets()
.stream().map(bucket -> bucket.getKeyAsNumber().longValue())
.collect(Collectors.toList());
List categories = categoryClient.queryCategoryByIds(ids);
return categories;
}catch (Exception e){
return null;
}
}
}
7)运行测试
http://www.leyou.com/search.html?key=手机&page=4#
显示分类和品牌
2、对分类和品牌页面渲染并显示
(1)完善search.html页面代码
filters:[],//过滤项
//商品分类
this.filters.push({
k:“cid3”,
options: resp.data.categories,
});
//品牌
this.filters.push({
k:“brandId”,
options: resp.data.brands,
});
(2)渲染品牌参数
删除部分div
通过观察一下div都是一样的所以删除其他的div只保留一个div
删除其他不是品牌的按照商品分类渲染,是品牌的按照品牌渲染
-
品牌
开启对应的样式
刷新页面
层渲染规格参数
1)完善SearchResult添加
List<Map<String,Object>>
,重新生成对应的构造函数package com.leyou.search.pojo;
import com.leyou.common.vo.PageResult;
import com.leyou.item.pojo.Brand;
import com.leyou.item.pojo.Category;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
import java.util.Map;
@Data
public class SearchResult extends PageResult {
private List categories;//父类的单选项
private List brands;//品牌集合
private List<Map<String,Object>> specs;//规格参数过滤条件,key以及待选项
public SearchResult(){
}
public SearchResult(Long total, Integer totalPage, List items, List categories, List brands, List<Map<String, Object>> specs) {
super(total, totalPage, items);
this.categories = categories;
this.brands = brands;
this.specs = specs;
}
}
2)修改当中的SearchService当中的search方法
//2 过滤
QueryBuilder baseQuery = QueryBuilders.matchQuery(“all”, request.getKey());
queryBuilder.withQuery(baseQuery);
List<Map<String,Object>> specs = null;
if(categories != null && categories.size() == 1){
//商品父类存在并且数量为1 ,可以聚合参数
specs = buildSpecificationAgg(categories.get(0).getId(),baseQuery);
}
3)完善buildSpecificationAgg方法
private List<Map<String, Object>> buildSpecificationAgg(Long cid, QueryBuilder baseQuery) {
List<Map<String, Object>> specs = new ArrayList<>();
//1、查询需要聚合的规格参数(通过商品类型id查询到对应商品的规格参数集合)
List params = specClient.queryParamList(null, cid, true);
//2、聚合
NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
//2.1带上查询条件
queryBuilder.withQuery(baseQuery);//将直接的条件添加到当前要查询的条件当中
//2.2带上查询条件
for (SpecParam param : params) {//聚合规格参数,通过"specs.“+name+”.keyword"
String name = param.getName();
queryBuilder.
addAggregation(
AggregationBuilders.terms(name).field(“specs.”+name+“.keyword”)
);
}
//3、获取结果,
AggregatedPage result = template.queryForPage(queryBuilder.build(), Goods.class);//得到对应的商品聚合
// 4、解析结果
Aggregations agss = result.getAggregations();
for (SpecParam param : params) {
//规格参数名称
String name = param.getName();
StringTerms terms = agss.get(name);//获取规格参数对应的聚合数据
List options = terms.getBuckets().stream()//将聚合的数据当中的KeyAsString()取出设置为集合
.map(b -> b.getKeyAsString()).collect(Collectors.toList());
//准备map(将上述得到的数据设置为map集合)
Map<String,Object> map = new HashMap<>();
map.put(“k”,name);
map.put(“options”,options);
specs.add(map);
}
return specs;
}
4)重新运行并测试
刷新页面查看结果
5)将数据渲染到页面上
//2.3其他规格
resp.data.specs.forEach(spec => this.filters.push(spec) );
刷新页面
6)完善数据为空的时候的
-
发现Vue当中数据没有空的了
(4)实现更多和收起的功能
1)定义控制变量
showMore: false //是否显示更多
2)设置点击按钮的时候显示或者隐藏
<v-btn small flat v-show=“!showMore” @click=“showMore=true”>
更多arrow_drop_downs
<v-btn small=“” flat v-show=“showMore” @click=“showMore=false”>
收起arrow_drop_up
3)设置渲染部分数据显示
-
刷新页面
1、完善SearchRequest设置添加搜索的过滤条件
package com.leyou.search.pojo;
import java.util.List;
import java.util.Map;
public class SearchRequest {
private String key;//搜索字段
private Integer page;//当前页
private static final Integer DEFAULT_SIZE = 20;//每页个数
private static final Integer DEFAULT_PAGE = 1;//默认页
//过滤条件
private Map<String,String> filter;
public Map<String, String> getFilter() {
return filter;
}
public void setFilter(Map<String, String> filter) {
this.filter = filter;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public Integer getPage() {
if(page == null){
return DEFAULT_PAGE;
}
//获取页码的时候进行校验,不能小于1
return Math.max(DEFAULT_PAGE,page);// Math.max返回DEFAULT_PAGE,page之间的最大值
}
public void setPage(Integer page) {
this.page = page;
}
public static Integer getSize() {
return DEFAULT_SIZE;
}
}
2、完善search.html
(1)设置对应初始化search的filter属性
search.filter = search.filter ? search.filter : {}; //初始化过滤条件
(2)设置点击事件
品牌 完善点击的方法
selectFilter(key,option){
//以下操作就是为了让Vue监控到filter当中值的变化
//从filter当中复制属性,到obj
const {… obj} = this.search.filter;//结构表达式 {… obj}安装this.search.filter的结果获取值
obj[key] = option;
//添加到search.filter当中
this.search.filter = obj;
}
3、实现后台
(1)完善SearchService对应的过滤条件的处理
1)将过滤条件封装到一个方法当中
2)完善buildBasicQuery方法
private QueryBuilder buildBasicQuery(SearchRequest request) {
//创建布尔查询
BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
//查询条件(设置通过关键字查询所有)
queryBuilder.must(QueryBuilders.matchQuery(“all”,request.getKey()));
//过滤条件,从请求当中得到过滤的条件,将请求当中的条件一个一个的添加到queryBuilder当中
Map<String, String> map = request.getFilter();//得到所有的过滤项
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();//
//处理key
if(!“cid3”.equals(key) && !“brandId”.equals(key)){//如果不是分类也不是品牌
//证明当前key是规格参数
key = “specs.”+key+“.keyword”;
}
String value = entry.getValue();
queryBuilder.filter(QueryBuilders.termQuery(key,value));
}
return queryBuilder;
}
3)修改common.js:
allowDots: true,
3)从新运行并测试
(2)设置点击过的不显示
总结
三个工作日收到了offer,头条面试体验还是很棒的,这次的头条面试好像每面技术都问了我算法,然后就是中间件、MySQL、Redis、Kafka、网络等等。
- 第一个是算法
关于算法,我觉得最好的是刷题,作死的刷的,多做多练习,加上自己的理解,还是比较容易拿下的。
而且,我貌似是将《算法刷题LeetCode中文版》、《算法的乐趣》大概都过了一遍,尤其是这本
《算法刷题LeetCode中文版》总共有15个章节:编程技巧、线性表、字符串、栈和队列、树、排序、查找、暴力枚举法、广度优先搜索、深度优先搜索、分治法、贪心法、动态规划、图、细节实现题
《算法的乐趣》共有23个章节:
- 第二个是Redis、MySQL、kafka(给大家看下我都有哪些复习笔记)
基本上都是面试真题解析、笔记和学习大纲图,感觉复习也就需要这些吧(个人意见)
- 第三个是网络(给大家看一本我之前得到的《JAVA核心知识整理》包括30个章节分类,这本283页的JAVA核心知识整理还是很不错的,一次性总结了30个分享的大知识点)
//img-blog.csdnimg.cn/4223303ede4d43d78d526315be7aa5cf.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_Q1NETiBA6JOd55uS5a2QYmx1ZWJveA==,size_19,color_FFFFFF,t_70,g_se,x_16)
(2)设置点击过的不显示
总结
三个工作日收到了offer,头条面试体验还是很棒的,这次的头条面试好像每面技术都问了我算法,然后就是中间件、MySQL、Redis、Kafka、网络等等。
- 第一个是算法
关于算法,我觉得最好的是刷题,作死的刷的,多做多练习,加上自己的理解,还是比较容易拿下的。
而且,我貌似是将《算法刷题LeetCode中文版》、《算法的乐趣》大概都过了一遍,尤其是这本
《算法刷题LeetCode中文版》总共有15个章节:编程技巧、线性表、字符串、栈和队列、树、排序、查找、暴力枚举法、广度优先搜索、深度优先搜索、分治法、贪心法、动态规划、图、细节实现题
[外链图片转存中…(img-oerKMbyo-1719274420124)]
《算法的乐趣》共有23个章节:
[外链图片转存中…(img-feMfsvFG-1719274420125)]
[外链图片转存中…(img-wUEII5Ni-1719274420125)]
- 第二个是Redis、MySQL、kafka(给大家看下我都有哪些复习笔记)
基本上都是面试真题解析、笔记和学习大纲图,感觉复习也就需要这些吧(个人意见)
[外链图片转存中…(img-DStBt6xQ-1719274420126)]
- 第三个是网络(给大家看一本我之前得到的《JAVA核心知识整理》包括30个章节分类,这本283页的JAVA核心知识整理还是很不错的,一次性总结了30个分享的大知识点)
[外链图片转存中…(img-pl1cODh2-1719274420126)]