我看了一大堆博客和资料大多是说这个spring的bug, 然后通过一个.json的配置文件去加载,我也是真的笑了, 本来注解就是方便开发,取消配置文件的功能, 结果解决方案却是本末倒置, 这里我奉献出最正确的解决方案,
这是实体类代码,及其注解
package com.gupao.springbootdemo.bean;
import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
import java.util.List;
/**
功能描述:ES的用户
@Author: zhouzhou
@Date: 2020/7/30$ 9:57$
*/
@Data
@Document(indexName = “es_user”)
public class ESUser {
@Id
private Long id;
@Field(type = FieldType.Text)
private String name;
@Field(type = FieldType.Integer)
private Integer age;
@Field(type = FieldType.Keyword)
private List tags;
@Field(type = FieldType.Text, analyzer = “ik_max_word”)
private String desc;
}
这是创建索引的代码
boolean index = elasticsearchRestTemplate.createIndex(ESUser.class);
我们会发现,当执行后, 虽然执行成功, 但是我们去查看索引信息的时候发现没有mapping信息
1.(在createIndex方法后加putMapping方法)
boolean index = elasticsearchRestTemplate.createIndex(ESUser.class);
elasticsearchRestTemplate.putMapping(ESUser.class);
问题解决, 查看mapping信息就有了
项目启动的时候,自动创建索引,无需手动调用API创建!!!
笔者通过查看elasticsearcRestTemplate的源码才发现
@Override
public ElasticsearchPersistentEntity getPersistentEntityFor(Class clazz) {
Assert.isTrue(clazz.isAnnotationPresent(Document.class), "Unable to identify index name. " + clazz.getSimpleName()
+ " is not a Document. Make sure the document class is annotated with @Document(indexName="foo")");
return elasticsearchConverter.getMappingContext().getRequiredPersistentEntity(clazz);
}
创建索引前会通过getMappingContext方法获取mappingContext字段, 但是这个字段怎么赋值呢
没有头绪!!!
笔者又转念一想, 我们直接思考下, 我们找到@Field字段在哪里被解析, 这不就知道读取@Field的类和设置mappingContext的方法了!!!
妙 啊!!!
原来是
MappingBuilder这个类对@Field进行解析, 后来进去发现@Mapping解析.json,也就是网上的方法解析方法也在里面, 哈哈殊途同归, 对外提供的方法为:
看注释, 我就知道离真相不远了 ,继续查看调用链, 真相大白!!!下面方法我就不多做解释了
原来是这个putMapping这个方法啊, 找了你好久!!!
Done!