【ElasticSearch】SpringDataElasticSearch通过@Document注解自动创建索引
背景
主要介绍在使用spring-data-elasticsearch依赖作为ElasticSearch客户端时需要的问题以及对应的问题的总结
项目依赖
SpringBoot2.x
ElasticSearch相关依赖
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-elasticsearch</artifactId>
</dependency>
相关注解
@Document
属性
indexName:索引名
type:类型
shards:主分片 (创建索引时生效)
replicas:副分片 (创建索引时生效)
refreshInterval:刷新间隔 (创建索引时生效)
createIndex:是否自动创建索引 (依赖于repository文件)
@Field (声明对应的字段类型)
@Id (声明该字段为主键)
示例如下:
@Data @Document(indexName = "demo_index11", type = "demo_index_type", shards = 1, replicas = 0) public class Demo { @Field(type = FieldType.Long) private Long dbId; @Field(type = FieldType.Long) @Id private Long userId; @Field(type = FieldType.Long) private Long nnNumber; @Field(type = FieldType.Text) private String nickName; @Field(type = FieldType.Text) private String nickName1; @Field(type = FieldType.Text) private String nickNamePingYin; @Field(type = FieldType.Integer) private Integer countryCode; @Field(type = FieldType.Keyword) private String telNum; @Field(type = FieldType.Keyword) private String userType; @Field(type = FieldType.Keyword) private String userUrl; @Field(type = FieldType.Keyword) private String userUrlNn; @Field(type = FieldType.Long) private Long vipExpire;
对应的repository文件
public interface DemoRepository extends ElasticsearchRepository<Demo, Long> { //...... }
注意事项
1.如果没有声明对应的repository文件,即使指定了属性createIndex=true,项目启动,也不会在elasticsearch中创建自动索引
2.如果对应的字段没有加上@Filed属性去声明索引的字段类型,且声明了自动创建索引,项目启动,则该字段会被elasticsearch默认映射为对应的类型
例如:Java中的String 类型 被映射为elasticsearch中的Text字段,Date类型 被映射为elasticsearch中的long类型
3.@Document 自动映射失败的问题可能有以下原因
3.1.如注意事项1所示,没有对应的repository文件
3.2 在索引的任何一个字段上加上@Field(index = false),就会导致整个索引字段初始化失败,参考 https://www.cnblogs.com/z-coding/p/14252541.html
4.@Document 自动创建索引,不支持对Text类型的字段添加关联的keyword属性,如果要添加keyword属性,可以使用如下方式
4.1. 手动添加一条数据,例如
PUT demo_index11/demo_index_type/1 { "nickName":"sss" }
这样会为demo_index11索引添加nickName字段,并且动态映射为以下类型
"nickName" : { "type" : "text", "fields" : { "keyword" : { "type" : "keyword", "ignore_above" : 256 } } }
4.2. 手动指定字段类型
POST demo_index11/demo_index_type/_mapping { "properties": { "nickName2":{ "type" : "text", "fields" : { "keyword" : { "type" : "keyword", "ignore_above" : 256 } } } } }

浙公网安备 33010602011771号