Spring-data-elasticsearch自定义日期格式错误

Spring-data-elasticsearch custom date format error

我正在使用 spring-data-elasticsearch 4.0.1 和 elastic cluster 7.6,当我使用“yyyy-MM-dd”定义具有自定义模式的属性并尝试检索日期时值“2014-06-11”会引发错误。

@Field(type = FieldType.Date, format = DateFormat.custom, pattern = "yyyy-MM-dd")
private Date startDate;

错误:

java.time.DateTimeException: Unable to obtain Instant from TemporalAccessor: {},ISO resolved to 2014-06-11 of type java.time.format.Parsed

我也试过这个但是又报错了:

@Field(type = FieldType.Date, format = DateFormat.date_optional_time)
private Date startDate;

我在文档中读到我应该为 elastic 7 版本使用模式“uuuu-MM-dd”,但这也不起作用。

一个java.util.Date不是由年月日组成的普通日期,而是UTC时区的一个时间点。无法将“2014-06-11”转换为即时时间。应该使用什么小时和分钟?在哪个时区?

就像 Ole 在评论中写的那样,为此使用 java.time.LocalDate。 class 正是针对该用例:一年有一个月和一天。请停止使用旧的 java.util.Date class。由于 Java 8,java.time 包中有 classes。

Elasticsearch 7 使用 modern date-time API. Given below is an excerpt from https://docs.spring.io/spring-data/elasticsearch/docs/current/reference/html/#reference

Properties that derive from TemporalAccessor must either have a @Field annotation of type FieldType.Date or a custom converter must be registered for this type. If you are using a custom date format, you need to use uuuu for the year instead of yyyy. This is due to a change in Elasticsearch 7.

按如下方式更改注释和类型:

@Field(type = FieldType.Date, format = DateFormat.date)
private LocalDate startDate;

Trail: Date Time.

了解有关现代日期时间 API 的更多信息

更多参考资料:

  1. Elasticsearch Built In Formats for date-time
  2. DateTimeFormatter

此问题已由 Spring Data Elasticsearch 4.0.5 解决。 Spring Boot 2.3.5 使用 Spring Data Elasticsearch 4.0.5。 (Spring Boot 2.3.5 将于 2020 年 10 月 29 日发布。)

https://github.com/spring-projects/spring-data-elasticsearch/pull/538 DATAES-953 - 将 Instant 或 Date 转换为 custo 时出现 DateTimeException…

https://github.com/spring-projects/spring-data-elasticsearch/releases/tag/4.0.5.RELEASE