gpt4 book ai didi

java - 如何使 Spring Data Elasticsearch 使用 java.time.LocalDateTime 获取日期

转载 作者:行者123 更新时间:2023-11-29 02:49:32 24 4
gpt4 key购买 nike

我正在使用 Spring Data 对 Elasticsearch 的支持。这是时间戳字段映射:

@Field(type = FieldType.Date, index = FieldIndex.not_analyzed, store = true,
format = DateFormat.custom, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZZ")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern ="yyyy-MM-dd'T'HH:mm:ss.SSSZZ")
private LocalDateTime timestamp;

这导致字段在 Elasticsearch 中的映射如下:

"timestamp":{"type":"date","store":true,"format":"yyyy-MM-dd'T'HH:mm:ss.SSSZZ"}

当我改用 java.util.Date 时,一切正常。但是,当我如上所述切换到 java.time.LocalDateTime 时,发送到 Elasticsearch 的文档会导致异常。这是文档(时间戳字段仅为简洁起见):

"timestamp": {
"hour":7, "minute":56, "second":9, "nano":147000000, "year":2017, "month":"FEBRUARY",
"dayOfMonth":13, "dayOfWeek":"MONDAY", "dayOfYear":44, "monthValue":2, "chronology": {
"id":"ISO", "calendarType": "iso8601"
}
}

异常(exception)情况:

MapperParsingException[failed to parse [timestamp]]; nested: IllegalArgumentException[unknown property [hour]];
(...)
Caused by: java.lang.IllegalArgumentException: unknown property [hour]

在对文档进行 json 化处理时,似乎此处的模式被忽略了。任何可能的提示?或者您可能知道如何在 Spring Data 中使用“内置”_timestamp 字段?

最佳答案

检查 https://github.com/spring-projects/spring-data-elasticsearch/wiki/Custom-ObjectMapperJavaTimeModule 添加到您的 ObjectMapper

@Configuration
public class ElasticSearchConfiguration {

@Bean
public ElasticsearchTemplate elasticsearchTemplate(Client client) {
return new ElasticsearchTemplate(client, new CustomEntityMapper());
}

public static class CustomEntityMapper implements EntityMapper {

private final ObjectMapper objectMapper;

public CustomEntityMapper() {
objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
objectMapper.registerModule(new CustomGeoModule());
objectMapper.registerModule(new JavaTimeModule());
}

@Override
public String mapToString(Object object) throws IOException {
return objectMapper.writeValueAsString(object);
}

@Override
public <T> T mapToObject(String source, Class<T> clazz) throws IOException {
return objectMapper.readValue(source, clazz);
}
}
}

关于java - 如何使 Spring Data Elasticsearch 使用 java.time.LocalDateTime 获取日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42202929/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com