elasticsearch 之时间类型

2022年10月27日10:16:26

日期类型(Date datatype)

JSON 没有日期类型,因此在 Elasticsearch 中可以表达成:

  • 日期格式化的字符串,比如: “2015-01-01” 或者 “2015/01/01 12:10:30”;
  • 毫秒级别的 long 类型
  • 秒级别的 integer 类型,

比如: 1515150699465, 1515150699;
实际上不管日期以何种格式写入,在 ES 内部都会先换成 UTC 时间并存储为 long 类型。

日期格式可以自定义,如果没有指定的话会使用以下的默认格式:
“strict_date_optional_time||epoch_millis”

date 类型的查询在内部转为 long 处理,聚合返回的结果再根据字段定义的格式转为字符串输出。

注: 日期将始终呈现为字符串,即使它们最初是在 JSON 文档中作为 long 串提供的。

日期格式自定义,如果没有格式指定,它会使用以下默认设置:

"strict_date_optional_time||epoch_millis"

如:
PUT my_index
{
  "mappings": {
    "_doc": {
      "properties": {
        "date": {
          "type": "date" 
        }
      }
    }
  }
}

PUT my_index/_doc/1
{ "date": "2015-01-01" } 

PUT my_index/_doc/2
{ "date": "2015-01-01T12:10:30Z" } 

PUT my_index/_doc/3
{ "date": 1420070400001 } 

GET my_index/_search
{
  "sort": { "date": "asc"} 
}

注:sort 返回为数组,值均为毫秒时间戳。

多日期格式设置

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

设置参数

  • boost 默认 1.0
  • doc_values 默认 true
  • format 默认strict_date_optional_time||epoch_millis
  • locale
  • ignore_malformed 是否忽略非正常格式的值,默认 false,抛出异常
  • index 是否可被查询 默认 true
  • null_value 默认值 null
  • store 默认 false

常用 format

  • epoch_millis
  • epoch_second

参考

1.https://www.elastic.co/guide/en/elasticsearch/reference/6.4/date.html
2.https://www.elastic.co/guide/en/elasticsearch/reference/6.4/mapping-date-format.html

  • 作者:web15085599741
  • 原文链接:https://blog.csdn.net/web15085599741/article/details/126358952
    更新时间:2022年10月27日10:16:26 ,共 1179 字。