Elasticsearch的date类型和后端时间类型的转换

参考:https://www.cnblogs.com/koushr/p/9498888.html

1. ES中date类型的表现形式

JSON中没有date类型,ES中的date可以由下面3种方式表示:

  1. 格式化的date字符串,例如 "2018-01-01" 或者 "2018-01-01 12:00:00"

  2. 一个long型的数字,代表从1970年1月1号0点到现在的毫秒数

  3. 一个integer型的数字,代表从1970年1月1号0点到现在的秒数

2. ES中date类型的存储形式

在ES内部,date被转为UTC(UTC是世界统一之间,中国与该时间存在8小时时差)并被存储为一个长整型数字,代表从1970年1月1号0点到现在的毫秒数

date类型字段上的查询会在内部被转为对long型值的范围查询查询的结果类型是字符串

假如插入的时候,值是"2018-01-01",则返回"2018-01-01"

假如插入的时候,值是"2018-01-01 12:00:00",则返回"2018-01-01 12:00:00"

假如插入的时候,值是1514736000000,则返回"1514736000000"。(进去是long型,出来是String型)

3. ES中对date类型格式化

date 格式可以在 put mapping 的时候用 format 参数指定,如果不指定的话,则启用默认格式。

默认格式是"strict_date_optional_time||epoch_millis"。这表明只接受符合"strict_date_optional_time"格式的字符串值,或者long型数字

strict_date_optional_timedate_optional_time的严格级别,这个严格指的是年份、月份、天必须分别以4位、2位、2位表示,不足两位的话第一位需用0补齐。不满足这个格式的日期字符串是放不进es中的。

date-opt-time = date-element ['T' [time-element] [offset]]
date-element = std-date-element | ord-date-element | week-date-element
std-date-element = yyyy ['-' MM ['-' dd]]
ord-date-element = yyyy ['-' DDD]
week-date-element = xxxx '-W' ww ['-' e]
time-element = HH [minute-element] | [fraction]
minute-element = ':' mm [second-element] | [fraction]
second-element = ':' ss [fraction]
fraction = ('.' | ',') digit+

实测后:

仅支持"yyyy-MM-dd"、"yyyyMMdd"、"yyyyMMddHHmmss"、"yyyy-MM-dd HH:mm:ss"、"yyyy-MM-ddTHH:mm:ss"、"yyyy-MM-ddTHH:mm:ss.SSS"、"yyyy-MM-ddTHH:mm:ss.SSSZ"格式。

epoch_millis约束值必须大于等于Long.MIN_VALUE,小于等于Long.MAX_VALUE

date类型字段除了type参数必须指定为date外,还有一个常用的参数 format 。可以通过该参数来显式指定ES接受的date格式,如果有多个的话,多个date格式需用||分隔。之后index/create/update操作时,将依次匹配,如果匹配到合适的格式,则会操作成功,并且查询时,该文档该字段也会以该格式展示。否则,操作不成功。如

PUT my_index
{
  "mappings": {
    "_doc": {
      "properties": {
        "updated_date": {
          "type":   "date",
          "format": "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis"
        }
      }
    }
  }
}

4. Java操作ES date类型

  1. 创建索引时指定date类型format为"yyyy-MM-dd HH:mm:ss",限制只能接受"yyyy-MM-dd HH:mm:ss"格式的date字符串

  2. 在代码中把Date实例或者LocalDateTime实例先转化为 "yyyy-MM-dd HH:mm:ss"格式的字符串后再存进去,这样取出来时也是"yyyy-MM-dd HH:mm:ss"格式。

使用Springboot注解实操:

@Field(type = FieldType.Date, 
       format = DateFormat.custom, 
       pattern = "yyyy-MM-dd HH:mm:ss")

@JsonFormat(shape = JsonFormat.Shape.STRING, 
            pattern = "yyyy-MM-dd HH:mm:ss", 
            timezone = "GMT+8")
private LocalDateTime createdTime;

将对象实例存入ES中:

CustomFile customFile = new CustomFile();
……
customFile.setCreatedTime(LocalDateTime.now());
……
fileRepository.save(customFile);	// 将该对象保存到ES中

在Kibana中查询插入结果:

{
    "_index" : "custom_file",
    "_type" : "_doc",
    "_id" : "1",
    "_score" : 1.0,
    "_source" : {
        "id" : "1",
        "fileName" : "第一个文件.doc",
        "fileContent" : "##########",
        "createdTime" : "2020-10-06 17:20:21",
        "deleted" : false
    }
}
原文地址:https://www.cnblogs.com/code-duck/p/13775207.html