【问题标题】:Spring-data-elasticsearch custom date format errorspring-data-elasticsearch 自定义日期格式错误
【发布时间】:2021-03-03 15:25:51
【问题描述】:

我正在使用 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”,但这也不起作用。

【问题讨论】:

  • 这不是我的家乡,所以只是猜测:尝试使用LocalDate 而不是Date

标签: java spring date elasticsearch spring-data-elasticsearch


【解决方案1】:

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

就像 Ole 在评论中写的那样,使用java.time.LocalDate。这个类正是针对那个用例:一年和一个月和一天。请停止使用旧的java.util.Date 类。从 Java 8 开始,java.time 包中有类。

【讨论】:

    【解决方案2】:

    Elasticsearch 7 使用modern date-time API。以下是https://docs.spring.io/spring-data/elasticsearch/docs/current/reference/html/#reference的摘录

    从 TemporalAccessor 派生的属性必须有一个 @Field FieldType.Date 类型的注释或自定义转换器必须是 注册了这个类型。如果您使用自定义日期格式,您 需要使用 uuuu 代替 yyyy 年份。这是由于一个变化 在 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

    【讨论】:

      【解决方案3】:

      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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-05-10
        • 2019-11-09
        • 2022-01-06
        • 2015-11-09
        • 1970-01-01
        • 1970-01-01
        • 2017-09-19
        • 2021-05-15
        相关资源
        最近更新 更多