@CreatedDate 注释不适用于 spring-data-elasticsearch

@CreatedDate annotation does not work with spring-data-elasticsearch

我正在使用 spring-boot-data-elasticsearch 将文档保存到 elasticsearch 中。

下面是我的文档对象。

@Builder
@Document(indexName = "testidx", createIndex = false)
public class Book {
    @Id
    private final String _id;

    @NotNull
    @CreatedDate
    @Field(type = FieldType.Date, format = DateFormat.basic_date_time)
    private final Instant regTime;

    @NotNull
    @Field(type = FieldType.Text)
    private final String bookName;
}

但是,当我将对象保存到ElasticSearchRepository 时,regTime(必须由@CreatedDate 自动创建和保存)并没有被保存。

elasticRepository.save(
            Book.builder()
                .bookName("test")
                .build()
        );
GET /testidx/_search

{
        "_index" : "testidx",
        "_type" : "_doc",
        "_id" : "M3IS_XgBGpcXDVxetXXn",
        "_score" : 1.0,
        "_source" : {
          "_class" : "{test class Name}",
          "bookName" : "test",
        }
      }

你能告诉我我错过了什么吗?

我正在开发 spring-boot 2.4.5(以及 spring-boot-starter-data-elasticsearch 2.4.5)和 ElasticSearch 7.12.0。

不幸的是 spring-data-elasticsearch 不支持所有与持久性相关的注释,也不支持所有 mapping-annotations of JPA, nor the auditing-annotations of Spring-Data,其中 @CreatedDate 属于到.

解决方案

所以我会放弃它,只使用基本的 @Field 注释。 然后你的 属性 regTime 应该作为 bookName 上面的同级出现在 JSON 请求中,并按预期保留。

但是,如果没有Spring-Data@CreatedDate注释的特殊功能(方便审计),你有自己关心初始化,在持久化之前设置值,例如使用 regTime = Instant.now()(在字段定义中,在构造函数中,否则)。

背景

请参阅 元模型对象映射 的文档,6.1.1. Mapping Annotation Overview 目前(4.2 版)仅包含这些 字段注释 :

  • @Id
  • @Field
  • @GeoPoint

另见官方指南8. Elasticsearch Repositories

以前有一个枚举 SUPPORTED_ID_PROPERTY_NAMES in SimpleElasticsearchPersistentProperty 列出了这些字段注释。

查看类似问题:Does Spring Data Elasticsearch supports @Id annotation from JPA?

本教程帮助我介绍了 elasticsearch-data: Spring Boot Elastic Search Example - Java Developer Zone

请查看有关审核的文档 (https://docs.spring.io/spring-data/elasticsearch/docs/4.2.0/reference/html/#elasticsearch.auditing)。

您的实体需要实现 Persistable 接口并需要重新实现 isNew() 方法(参见第 9.2.1 节)。 注意:我刚刚看到在记录的实体示例中缺少 @CreatedDate@CreatedBy 注释。我会修复文档,当然需要注释。

那么您的 Spring 引导应用程序或任何其他配置 class 上是否有 @EnableElasticsearchAuditing?这也是需要的。