Elasticsearch索引字段与Java实体类字段映射异常问题求助
问题分析与解决方案
看起来你遇到的问题确实是字段映射不匹配导致的——你的Java实体类字段名和Elasticsearch文档里的字段名没有对应上,Spring Data Elasticsearch没法自动映射这些字段,所以返回了null。
我们逐个对比你的实体类和ES样本数据里的字段:
- 实体类的
timeStamp→ ES文档里的是全小写的timestamp podName→ ES里的是podname(全小写,没有驼峰)iporHost→ ES里的是iporhost(全小写)connectionCount→ ES里的是connectionscount(全小写,注意是连写的scount不是sCount)
而command字段能正常获取,就是因为它的名字在两边完全一致。
解决方法
给每个不匹配的字段显式指定Elasticsearch中的字段名,用@Field注解的name属性。修改后的实体类代码如下:
@Document(indexName = "netstat*") @Setting(settingPath = "static/es-settings.json") public class NetworkStats { @Id @Field(type = FieldType.Keyword) private String id; @Field(name = "timestamp", type = FieldType.Text) private String timeStamp ; @Field(name = "podname", type = FieldType.Text) private String podName ; @Field(name = "iporhost", type = FieldType.Text) private String iporHost ; @Field(name = "connectionscount", type = FieldType.Text) private String connectionCount ; @Field(type = FieldType.Text) private String command ; // 已定义上述字段的getter和setter方法 }
额外提醒
- 把
connectionCount的FieldType.Auto改成Text或者Keyword更稳妥——因为ES里这个字段是字符串类型,Auto类型推断可能会出现意外问题。 - 确保你的getter/setter方法和字段名对应正确(IDE自动生成的一般没问题)。
修改后重新运行项目,应该就能正确获取这些字段的值了。
内容的提问来源于stack exchange,提问作者vr3w3c9
相关产品推荐
相关产品推荐

