Springframework Data Elasticsearch 无法创建 class java.time.ZonedDateTime 的对象

Springframework Data Elasticsearch unable to create object of class java.time.ZonedDateTime

我正在使用推荐的 RestHightCLient 和 ElasticsearchRestTemplate。我正在尝试从 elasticsearch 检索 ZonedDateTime,但似乎 spring-data-elasticsearch 无法创建 class ZonedDateTime 的对象。下面的代码片段有什么问题,我需要添加哪些额外的配置。

此外,如果我不使用 ElasticsearchOperations 而直接使用 RestHighLevelClient,我需要做什么。

    @Bean
    @Override
    public RestHighLevelClient elasticsearchClient() {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("content-type", "application/json");
        ClientConfiguration clientConfiguration = ClientConfiguration
                .builder()
                .connectedTo("localhost:9200")
                .build();
        return RestClients.create(clientConfiguration).rest();
    }

    @Bean(name = {"elasticsearchTemplate"})
    public ElasticsearchOperations elasticsearhTemplate() {
        return new ElasticsearchRestTemplate(elasticsearchClient());
    }
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.data.elasticsearch.core.convert.ConversionException: could not create object of class java.time.ZonedDateTime] with root cause

java.time.DateTimeException: Unable to obtain LocalDate from TemporalAccessor: {YearOfEra=2020, DayOfMonth=25, OffsetSeconds=3600, MonthOfYear=8},ISO resolved to 16:46:47.891 of type java.time.format.Parsed
    at java.base/java.time.LocalDate.from(LocalDate.java:397) ~[na:na]
public class XXClass {
    ....

    @Field(type = FieldType.Date, format = DateFormat.custom, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS Z")
    private ZonedDateTime created = ZonedDateTime.now();
}

更改您的模式以使用 uuuu 而不是 yyyy;这个is documented here, the change in Elasticsearch responsible for this: https://www.elastic.co/guide/en/elasticsearch/reference/current/migrate-to-java-time.html#java-time-migration-incompatible-date-formats

顺便说一句,你不需要

httpHeaders.add("content-type", "application/json");

Spring Data Elasticsearch 不需要 @Json... 注释。