【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 } } } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· 因为Apifox不支持离线,我果断选择了Apipost!
2021-07-26 【Nacos】Nacos源码分析(二):服务端和客户端实例注册
2020-07-26 Flyway-数据库迁移工具