Search code examples
javaspring-bootspring-data-elasticsearch

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


I'm using spring-boot-data-elasticsearch to persist the documents into elasticsearch.

Below is my Document Object for it.

@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;
}

However, when I saved the object into the ElasticSearchRepository, the regTime(which has to be created and saved automatically by @CreatedDate), has not been saved.

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",
        }
      }

Could you please let me know what I have been missed?

I'm working on the spring-boot 2.4.5 (and spring-boot-starter-data-elasticsearch 2.4.5 also) and ElasticSearch 7.12.0.


Solution

  • Please check the documentation about auditing (https://docs.spring.io/spring-data/elasticsearch/docs/4.2.0/reference/html/#elasticsearch.auditing).

    Your entity needs to implement the Persistable interface and needs to reimplement the isNew() method (see section 9.2.1). Note: I just saw that in the documented entity sample the @CreatedDate and @CreatedBy annotations are missing. I will fix the docs, the annotation is needed of course.

    Then do you have @EnableElasticsearchAuditing on your Spring Boot application or any other configuration class? This is needed as well.