ElasticSearch中 使用 LocalDateTime
es用的8.+的版本,只有索引没有type。
在字段上添加如下注解:
/**
* 创建时间
*/
@Field(type = FieldType.Date, format = DateFormat.custom, pattern = "yyyy-MM-dd HH:mm:ss")
@JsonSerialize(using = LocalDateTimeSerializer.class)
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
@JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd HH:mm:ss")
LocalDateTime createTime;
不加序列化的两个注解无法保存成功。
不加 @JsonFormat 格式化注解,默认存long类型。
提前设置mappings为date以及时间格式,保存后也是错误格式。如下:
"createTime" : [
2022,
11,
22,
22,
22,
34,
635000000
]
注解全加后,可以正常保存,格式正确。但是默认text类型。如下:
{
"took" : 0,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 1,
"relation" : "eq"
},
"max_score" : 1.0,
"hits" : [
{
"_index" : "user",
"_id" : "1",
"_score" : 1.0,
"_source" : {
"id" : 1,
"name" : "张三",
"age" : 18,
"adress" : "中国",
"createTime" : "2022-11-22 22:10:11"
}
}
]
}
}
映射关系如下:
{
"user" : {
"mappings" : {
"properties" : {
"createTime" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
}
}
}
}
}
需要创建索引时设置mappings为date以及时间格式
PUT user
{
"mappings": {
"properties": {
"createTime": {
"type": "date",
"format":"yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis"
}
}
}
}
最后就是想要的数据以及mappings
查询数据:
{
"took" : 0,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 1,
"relation" : "eq"
},
"max_score" : 1.0,
"hits" : [
{
"_index" : "user",
"_id" : "1",
"_score" : 1.0,
"_source" : {
"id" : 1,
"name" : "张三",
"age" : 18,
"adress" : "中国",
"createTime" : "2022-11-22 22:33:51"
}
}
]
}
}
映射关系:
{
"user" : {
"mappings" : {
"properties" : {
"adress" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
},
"age" : {
"type" : "long"
},
"createTime" : {
"type" : "date",
"format" : "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis"
},
"id" : {
"type" : "long"
},
"name" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
}
}
}
}
}