ES 日期类型使用
问题
- ES存储日期格式是否应该带时区?
- JAVA应用是东八区,spring elasticsearch 的PO的对象是Date/LocalDateTime类型。 往索引写会丢失时区信息吗?
ES date类型存储原理
- 如果写入的时间字段没有时区偏移量标识 (比如Spring Elastic Search Document的属性是Date或者LocalDateTime),elasticsearch 就会默认它为UTC时间,即0时区时间,并且转为(epoch time millisecond)毫秒值保存
- es中的date类型字段有映射属性format未指定时默认为"format": "strict_date_optional_time||epoch_millis", 其中strict_date_optional_time格式对应的java中的时间日期格式为: yyyy-MM-dd'T'HH:mm:ss.SSSZ 或 yyyy-MM-dd。这个也是最常见的时间日期格式, 其中时区偏移量标识为Z, 0时区
所以 JAVA应用是东八区,spring elasticsearch 的PO的对象是Date/LocalDateTime类型。 往索引写会丢失时区信息。
最佳实践
es中的date类型字段映射属性format 需要指定带时区的格式 "strict_date_optional_time||epoch_millis"
为了避免丢失时区信息,建议使用 Java 8 引入的 java.time 包中的日期时间类,如 ZonedDateTime 或 OffsetDateTime,它们包含了时区信息。同时,需要调整 Elasticsearch 索引的日期格式,使其能够处理时区信息。
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
import java.time.ZonedDateTime;
@Document(indexName = "your_index_name")
public class YourDocument {
@Id
private String id;
@Field(type = FieldType.Date, format = {}, pattern = "yyyy-MM-dd HH:mm:ssXXX")
private ZonedDateTime createTime;
public YourDocument() {
}
public YourDocument(String id, ZonedDateTime createTime) {
this.id = id;
this.createTime = createTime;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public ZonedDateTime getCreateTime() {
return createTime;
}
public void setCreateTime(ZonedDateTime createTime) {
this.createTime = createTime;
}
}
如果历史代码spring elasticsearch 的PO的对象是LocalDateTime,并且应用是0时区,ES 索引的date类型的可以定义为(因应用时区是0时区,写入ES不带时区也不丢时区信息)
"create_time": {
"type": "date",
"format": "yyyy-MM-dd HH:mm:ss||strict_date_optional_time||epoch_millis"
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南