有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Spring数据Elasticsearch(4.x)使用@Id强制使用源代码中的Id字段

总结

最近我们升级到Spring Data Elasticsearch 4。x、 这个主要版本的一部分意味着Jackson不再用于将我们的域对象转换为json(而是使用MappingElasticsearchConverter)[1]。这意味着我们现在必须在所有文档中添加一个新的id字段

以前我们有这样的域对象:

import org.springframework.data.annotation.Id;

public ESDocument {
    @Id
    private String id;

    private String field1;

    @JsonIgnore
    public String getId() {
        return id;
    }

    public String getField1() {
        return field1;
    }

在ES中产生了如下文件:

{
  "_index" : "test_index",
  "_type" : "_doc",
  "_id" : "d5bf7b5c-7a44-42f9-94d6-d59fe3988482",
  "_score" : 1.0,
  "_source" : {
    "field1" : "blabla"
  }
}

请注意:

  1. @JsonIgnore注释用于确保我们不需要在_source中有id字段
  2. 我们正在自己设置文档id,它最终位于_id

问题

与弹簧数据弹性4。x不再尊重@JsonIgnore注释,这意味着我们现在必须在_source中有一个id字段,如下所示:

{
  "_index" : "test_index",
  "_type" : "_doc",
  "_id" : "d5bf7b5c-7a44-42f9-94d6-d59fe3988482",
  "_score" : 1.0,
  "_source" : {
    "id": "d5bf7b5c-7a44-42f9-94d6-d59fe3988482",
    "field1" : "blabla"
  }
}

问题

  1. 是否不再可以省略文档标识符的重复(即在_idid字段中)?如果是,怎么做?(注意,我们已经尝试了@org.springframework.data.annotation.Transient,但它不起作用,因为SpringDataElastic认为我们的文档没有id)
  2. 我们以前在_source中抑制id字段的方法是错误的还是有问题的

版本

java:1.8.0_252
弹性搜索:7.6.2
弹簧靴:2.3.1。释放
弹簧数据弹性:4.0.1。释放

参考资料

[1]-https://spring.io/blog/2020/05/27/what-s-new-in-spring-data-elasticsearch-4-0


共 (1) 个答案

  1. # 1 楼答案

    问题1:

    要从\u source中省略id字段,您通常会使用@Transient注释,但正如您所写的,这对id属性不起作用。在Spring数据模块中忽略瞬态特性(不仅仅是Spring数据Elasticsearch)

    但是您可以使用org.springframework.data.annotation.ReadOnlyProperty注释来实现以下目的:

    @Id
    @ReadOnlyProperty
    private String id;
    

    老实说,到目前为止我还不知道这个存在,它也来自Spring数据共享空间,当属性由MappingElasticsearchConverter编写时,它在属性的isWriteable()方法中被检查

    问题2:

    当然不是不正确,但正如你所发现的那样,这是有问题的。我们在存储它时总是考虑整个实体,所以我们从来没有想过不写ID。严格来说,这是不必要的,在那里你是对的,因为我们总是把ID返回到 ID IDEEM字段中,连同源> eEM>,这样我们就可以很容易地把实体重新组合起来。但我们从未认为这是必须具备的功能

    注意:

    当您查看ES索引中的数据时,您会发现MappingElasticsearchConverter会写入一个名为\u class的额外\u source字段,其中包含实体类(或定义的别名)的名称。这允许映射泛型;有关更多信息check the documentation-以防您想知道这是从哪里来的