这个问题也困扰了我很久,网上关于这方面的确实资料很少,不过还是解决了,官方文档还是靠谱。
主要原因是数据模型的配置,使用spring-data-elasticsearch时候我们一般都是默认配置,问题就出在这里,默认配置中的数据模型使用的是Jackson Object Mapping,在使用这种数据模型时候,@Field是不起作用的。
这时候就用到了另一种数据模型映射(Meta Model Object Mapping),这种映射支持字段的详细配置,具体配置参看官网链接 ,这里贴出@field的部分配置。
@Field: Applied at the field level and defines properties of the field, most of the attributes map to the respective Elasticsearch Mapping definitions:
name: The name of the field as it will be represented in the Elasticsearch document, if not set, the Java field name is used.
type: the field type, can be one of Text, Integer, Long, Date, Float, Double, Boolean, Object, Auto, Nested, Ip, Attachment, Keyword.
format and pattern custom definitions for the Date type.
store: Flag wether the original field value should be store in Elasticsearch, default value is false.
analyzer, searchAnalyzer, normalizer for specifying custom custom analyzers and normalizer.
copy_to: the target field to copy multiple document fields to.
最后总结解决方案:
1. 添加配置文件
@Configuration
public class Config extends AbstractElasticsearchConfiguration {
@Override
public RestHighLevelClient elasticsearchClient() {
return RestClients.create(ClientConfiguration.create("localhost:9200")).rest()
}
@Bean
@Override
public EntityMapper entityMapper() {
ElasticsearchEntityMapper entityMapper = new ElasticsearchEntityMapper(
elasticsearchMappingContext(), new DefaultConversionService()
);
entityMapper.setConversions(elasticsearchCustomConversions());
return entityMapper;
}
}
2. 在字段上使用注解
@Field(type = FieldType.Text, name="src_ip")
private String srcIp;