spring data elasticsearch手动定义mapping
测试版本:
ES版本:6.7.2
spring boot版本:2.1.1
本文参考了这个的文章,但是不一样,因为我复现不了它那样,如果复现得了,我就不用花那么多时间了,参考文章
实体类
@Data
// 指定根据文件构建映射
@Mapping(mappingPath = "SpuDocMapping.json")
// indexName一般为项目名,type为实体类名,注解的createIndex属性默认为ture,
// SpringBoot启动时会自动创建映射,但要注意如果已经存在相同的index,必须先删除
@Document(indexName = "ynec", type = "spu")
public class SpuDoc implements Serializable {
private static final long serialVersionUID = -593773981413702898L;
// 注意一定要加id注解
@Id
private Long id;
private String name;
private List<String> cat_list;
private List<String> prop_list;
}
Repository层
@Component
public interface SpuDocRepo extends ElasticsearchRepository<SpuDoc, Long> {
}
service层
public interface SearchService {
List<Long> searchSpu(String keyword, Integer page, Integer size);
}
service实现层
@Service
public class SearchServiceImpl implements SearchService{
// 刚刚创建的数据访问层
@Autowired
SpuDocRepo spuDocRepo;
@Override
public List<Long> searchSpu(String keyword, Integer page, Integer size) {
// queryStringQuery是匹配_all的全文搜索
QueryBuilder queryBuilder = QueryBuilders.queryStringQuery(keyword);
// 构建分页对象
Pageable pageable = PageRequest.of(page, size);
Page<SpuDoc> spuDocPage = spuDocRepo.search(queryBuilder, pageable);
// 此处我返回的是商品的id列表,可以根据业务自定义
return spuDocPage.getContent().stream().map(SpuDoc::getId).collect(Collectors.toList());
}
}
我没有对它的service层进行测试,,而且在我印象中_all字段是在不知道哪个版本后就取消了的,需要使用"copy_to": "xxx"
来自定义一个字段,存储多个字段的索引(表达好像不够准确),就是以前的_all是可以全文检索,现在的可以定义一个检索指定范围的字段。
SpuDocMapping文件为
{
// "mappings": {
"spu": {
"properties": {
"id": {
"type": "long"
},
"name": {
"type": "text"
},
"cat_list": {
"type": "text"
},
"prop_list": {
"type": "text"
}
}
}
}
//}
至于为什么要注释掉mapping呢,因为不注释掉会报错,如下图
具体原因未知,个人认为是因为在程序运行实体类已经根据@Document(indexName = "ynec", type = "spu")
创建了一个mapping,然后实体类上的@Mapping(mappingPath = "SpuDocMapping.json")
才生效,结果就是mapping已经存在,而这个json文件又是创建mapping,所以才报错,将其改掉,变成更新mapping则不会报错。