Spring Data Elasticsearch:自动生成ID时如何将ID写入_source?
问题描述
我定义了如下实体类:
@Document(indexName = "my_index") public class MyDocument { @Id @Field(type = FieldType.Keyword) private String id; @Field(type = FieldType.Keyword) private String otherField; ... }
对应的仓库接口:
@Repository public interface MyRepository extends ElasticsearchRepository<MyDocument, String> { }
调用repository.save(document);(document的id为空,由ES自动生成,otherField设为'someValue')后,ES返回的文档_source中不包含id字段——虽然save方法返回的Java对象已填充id,通过仓库查询也能获取到id,但无法直接用id字段排序。尝试使用_id排序时收到控制台警告:
299 loading the fielddata on the _id field is deprecated and will be removed in future versions. If you require sorting or aggregating on this field you should also include the id in the body of the documents, and map this field as a keyword field that has [doc_values] enabled
若先查询文档再修改重新save,_source会包含id字段,但会导致ES操作次数翻倍,不是理想方案。
环境信息:
- springdata-elasticsearch版本:4.4.5
- Elasticsearch版本:7.17.7
解决方案
针对Spring Data Elasticsearch 4.x版本,提供两种无需额外ES操作的解决方法:
方法1:实体类添加序列化注解
在id字段上添加@JsonProperty注解,显式指定序列化时的字段名,确保Spring Data Elasticsearch将id写入_source:
@Document(indexName = "my_index") public class MyDocument { @Id @Field(type = FieldType.Keyword) @JsonProperty("id") private String id; @Field(type = FieldType.Keyword) private String otherField; ... }
修改后直接调用repository.save(document),ES自动生成id后会同时将id字段写入_source。
方法2:手动生成ID后保存
通过ElasticsearchOperations手动生成ES风格的ID,设置到实体后再保存,仅需一次写入操作:
@Autowired private ElasticsearchOperations elasticsearchOperations; public MyDocument saveWithIdInSource(MyDocument document) { // 生成ES自动ID String generatedId = elasticsearchOperations.indexOps(MyDocument.class).createId(); document.setId(generatedId); // 保存文档 return elasticsearchOperations.save(document); }
验证效果
保存完成后,查询es/my_index/_search?pretty会得到如下结果,_source中已包含id字段:
... "hits" : [ { "_index" : "my_index", "_type" : "_doc", "_id" : "AUTO_GENERATED_ID", "_score" : 1.0, "_source" : { "_class" : "a.b.c.MyDocument", "id": "AUTO_GENERATED_ID", "otherField": "someValue" } } ]
此时使用id字段排序不会再收到弃用警告。
内容的提问来源于stack exchange,提问作者Marius Manastireanu
相关产品推荐
相关产品推荐

