Springdata Elasticsearch - 索引时如何填充 _source 中的 id 字段?

问题描述 投票:0回答:1

我有一份文件

@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);
时(其中文档 ID 为空,因此会生成一个新文档,并且“otherValue”设置为“someValue”),我会看到以下对
es/my_index/_search?pretty
的响应:

...
"hits" : [
{
 "_index" : "my_index",
 "_type" : "_doc",
 "_id" : "AUTO_GENERATED_ID",
 "_score" : 1.0,
 "_source" : {
    "_class" : "a.b.c.MyDocument",
    "otherField": "someValue"
 }
}
]

save
方法的结果是返回一个带有id字段集的java对象,当然,如果我通过存储库检索文档,id将被填充到java对象中,我可以访问它。

但是,文档本身在源代码中不包含“id”字段。 当我让 ES/Springdata 处理 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


PS:如果我对从存储库检索到的文档进行一些修改并再次

save

,该文档现在将填充“id”字段,但这意味着我在尝试执行以下操作时必须加倍对 ES 的操作索引文档。


    springdata-elasticsearch 版本:4.4.5
  • 版本:7.17.7
java elasticsearch spring-data-elasticsearch
1个回答
0
投票
Spring Data Elasticsearch 的行为是默认将 id 属性的值写入文档源,从版本 5.1 开始,可以通过将

storeIdInSource = false 添加到 @Document

 注释来显式
禁用

但是这个值只有在实体上设置时才会被写入Elasticsearch的源中。在您的情况下,您有一个

null

 id 属性,因此 Spring Data Elasticsearch 无法将任何内容写入我发送到 Elasticsearch 的文档中。 id 是由 Elasticsearch 在没有显式 id 的保存传入时创建的,并且仅在返回存储的值或稍后搜索实体的属性时才会填充从 Elasticsearch 返回的 id。 Elasticsearch 无法在保存时创建新的 ID 并将其存储在文档源中的某个位置。

顺便说一句,Spring Data Elasticsearch 4.4.5 是一个旧版本,已停止维护。

© www.soinside.com 2019 - 2024. All rights reserved.