Java在ElasticSearch中使用LocalDatetime类型

问题

最近在开发一个搜索功能的需求的时候,遇到了LocalDatetime类型不能保存到ElasticSearch中的问题,报错如下:

1
2
ElasticsearchStatusException[Elasticsearch exception [type=mapper_parsing_exception, reason=failed to parse field [createTime] of type [date] in document with id '3000']
]; nested: ElasticsearchException[Elasticsearch exception [type=illegal_state_exception, reason=Can't get text on a START_OBJECT at 1:125]];

从网上查找尝试第一个办法:

将以下注解加到时间字段上,依然无效

1
2
3
4
@Field(type = FieldType.Date, index = FieldIndex.not_analyzed, store = true,
format = DateFormat.custom, pattern = "yyyy-MM-dd HH:mm:ss.SSS")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern ="yyyy-MM-dd HH:mm:ss.SSS")
private LocalDateTime createTime;

解决办法

在项目中添加以下依赖:

1
2
3
4
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>

在字段上加上以下注解

1
2
3
4
5
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
@JsonSerialize(using = LocalDateTimeSerializer.class)
@Field(type = FieldType.Date, store = true, format = DateFormat.custom, pattern = "yyyy-MM-dd HH:mm:ss.SSS")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss.SSS")
private LocalDateTime createTime;

完美解决

作者

StoneWu

发布于

2020-09-11

更新于

2023-02-14

许可协议

评论