DB数据导入ES
要求:了解SpringDataElasticSearch提供的ElasticsearchRepository,了解创建mapping使用的 动态模板的作用,完成导入的代码。
基本步骤如下:
- 查询商品数据
- 根据spu等信息,构建goods对象
- 把goods存入索引库
1.创建GoodsRepository
java代码:
public interface GoodsRepository extends ElasticsearchRepository<Goods, Long> {
}
2.使用Restful或Kibana创建索引和Mapping
我们可以通过kibana来创建索引库及映射:
PUT /goods
{
"settings": {
"number_of_shards": 1,
"number_of_replicas": 1
},
"mappings": {
"docs":{
"properties": {
"id":{
"type": "keyword"
},
"subTitle":{
"type": "keyword",
"index": false
},
"skus":{
"type": "keyword",
"index": false
},
"all":{
"type": "text",
"analyzer": "ik_max_word"
}
},
"dynamic_templates": [
{
"strings": {
"match_mapping_type": "string",
"mapping": {
"type": "keyword"
}
}
}
]
}
}
}
3.导入数据代码
导入数据其实就是查询数据,然后把查询到的Spu转变为Goods来保存,因此我们先编写一个SearchService,然后在里面定义一个方法, 把Spu转为Goods
@Service
public class SearchService {
@Autowired
private ItemClient itemClient;
/**
* 把一个Spu转为一个Goods对象
*
* @param spu
* @return
*/
public Goods buildGoods(SpuDTO spu) {
// 1 商品相关搜索信息的拼接:名称、分类、品牌、规格信息等
// 1.1 分类
String categoryNames = itemClient.queryCategoryByIds(spu.getCategoryIds())
.stream().map(CategoryDTO::getName).collect(Collectors.joining(","));
// 1.2 品牌
BrandDTO brand = itemClient.queryBrandById(spu.getBrandId());
// 1.3 名称