一、建立商品索引库
- 首先要分析商品的参数和页面上需要展示的内容来分析商品索引库字段,搜索出来的大图上展示的是每个spu部分信息以及每个spu下的各个sku部分信息,接着开始分析分词字段的内容,用户搜索的时候输入的是商品的标题、分类或是品牌,所以分词字段由商品的这三个属性拼接而成,选用的是ik_max_word分词器,接着设计用于过滤的字段,一些不适合作为索引的字段设置为index = false,再加入一些商品三级分类字段,价格字段便于页面的展示,最后调用创建索引库的api方法。
@Data
@Document(indexName = "goods", type = "docs", shards = 1, replicas = 0)
public class Goods implements Serializable {
@Id
private Long id;
@Field(type = FieldType.Text, analyzer = "ik_max_word")
private String all;
private Long brandId;
private Map<String,Object> specs;
@Field(type = FieldType.Keyword, index = false)
private String skus;
@Field(type = FieldType.Keyword, index = false)
private String subTitle;
private Long cid1;
private Long cid2;
private Long cid3;
private Date createTime;
private Set<Long> price;
}
- 下面很重要的一步就是往索引库中添加添加数据,需要远程调用商品微服务中的方法获取数据,获取到数据之后将Spu对象传入buildGoods方法中,每100个商品对象作为一个集合调用loadData方法,最后在loadData方法中调用存索引集合的api方法。
public Goods buildGoods(Spu spu){
List<Category> categoryList = categoryClient.queryCategoryListByIds(Arrays.asList(
spu.getCid1(),spu.getCid2(),spu.getCid3()
));
if (CollectionUtils.isEmpty(categoryList)){
throw new LyException(ExceptionEnum.CATEGORY_NOT_FOUND);
}
List<String> names = categoryList.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();
List<Sku> skuList = goodsClient.querySkusBySpuId(spu.getId());
if (CollectionUtils.isEmpty(skuList)){
throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
}
List<Map<String,Object>> skus = new ArrayList<>();
Set<Long> priceList