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"
}
}
请注意:
@JsonIgnore
注释用于确保我们不需要在_source
中有id
字段李>- 我们正在自己设置文档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"
}
}
问题
- 是否不再可以省略文档标识符的重复(即在
_id
和id
字段中)?如果是,怎么做?(注意,我们已经尝试了@org.springframework.data.annotation.Transient
,但它不起作用,因为SpringDataElastic认为我们的文档没有id)李> - 我们以前在
_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:
要从\u source中省略id字段,您通常会使用
@Transient
注释,但正如您所写的,这对id属性不起作用。在Spring数据模块中忽略瞬态特性(不仅仅是Spring数据Elasticsearch)但是您可以使用
org.springframework.data.annotation.ReadOnlyProperty
注释来实现以下目的:老实说,到目前为止我还不知道这个存在,它也来自Spring数据共享空间,当属性由
MappingElasticsearchConverter
编写时,它在属性的isWriteable()
方法中被检查问题2:
当然不是不正确,但正如你所发现的那样,这是有问题的。我们在存储它时总是考虑整个实体,所以我们从来没有想过不写ID。严格来说,这是不必要的,在那里你是对的,因为我们总是把ID返回到 ID IDEEM字段中,连同源> eEM>,这样我们就可以很容易地把实体重新组合起来。但我们从未认为这是必须具备的功能
注意:
当您查看ES索引中的数据时,您会发现
MappingElasticsearchConverter
会写入一个名为\u class的额外\u source字段,其中包含实体类(或定义的别名)的名称。这允许映射泛型;有关更多信息check the documentation-以防您想知道这是从哪里来的