一、日期数据类型
1. 简述
JSON是没有日期数据类型的,因此Elasticsearch中的日期可以是:
- 包含格式化日期的字符串,例如“2015-01-01”或“2015/01/01 12:10:30”。
- 一个long型数字,表示自纪元年以来的毫秒数。
- 一个int型数字,表示自纪元以来的秒数。
在es内部,日期被转换为UTC(如果指定了时区),并存储为表示自纪元以来毫秒数的long数字
日期将始终以字符串呈现,即使它们写入es时在JSON文档中以long数字提供。
可以自定义日期格式,但如果未指定格式,则使用默认格式:
"strict_date_optional_time||epoch_millis"
2. 实例
使用默认格式的时间类型定义字段birth_date
PUT date_type_test{"mappings": {"_doc": {"properties": {"birth_date": {"type": "date"}}}}}
# 使用纯日期PUT date_type_test/_doc/1{ "birth_day": "2015-01-01" }# 使用纯日期+时间PUT date_type_test/_doc/2{ "birth_day": "2015-01-01T12:10:30Z" }# 使用自纪元以来的毫秒数PUT date_type_test/_doc/3{ "birth_day": 1420070400001 }
二、多日期格式
1. 简述
可以通过用 | | 作为分隔符来指定多个格式。在找到匹配的格式之前,将依次尝试每个格式。第一种格式将用于将毫秒数(自纪元以来的毫秒数)转换回字符串。
2. 实例
2.1 定义字段(多日期格式)
定义一个日期类型字段date,指定多种格式,每种格式之间用 || 分隔:
PUT multi_date_index{"mappings": {"_doc": {"properties": {"date": {"type": "date","format": "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis"}}}}}
说明:date类型指定了三种时间格式,如果在往es中写入date的数据格式,不是上面三种格式的话,会抛异常。提示格式不匹配。
2.2 插入格式1:yyyy-MM-dd HH:mm:ss
执行操作:
PUT multi_date_index/_doc/2{ "date": "2015-01-01 12:12:30" }
执行结果:创建成功
{"_index" : "multi_date_index","_type" : "_doc","_id" : "2","_version" : 1,"result" : "created","_shards" : {"total" : 2,"successful" : 1,"failed" : 0},"_seq_no" : 0,"_primary_term" : 1}
2.3 插入格式2:yyyy-MM-dd
执行操作:
PUT multi_date_index/_doc/1{ "date": "2015-01-01" }
执行结果:
{"_index" : "multi_date_index","_type" : "_doc","_id" : "1","_version" : 2,"result" : "updated","_shards" : {"total" : 2,"successful" : 1,"failed" : 0},"_seq_no" : 1,"_primary_term" : 1}
2.4 插入格式3:epoch_millis (自纪元以来的毫秒数)
执行操作:
PUT multi_date_index/_doc/3{ "date": 1420070400001 }
执行结果:
{"_index" : "multi_date_index","_type" : "_doc","_id" : "3","_version" : 4,"result" : "updated","_shards" : {"total" : 2,"successful" : 1,"failed" : 0},"_seq_no" : 3,"_primary_term" : 1}
2.5 插入非指定格式
执行操作:
PUT multi_date_index/_doc/4{ "date": "2015-01-01T12:10:30Z" }
执行结果:
{"error": {"root_cause": [{"type": "mapper_parsing_exception","reason": "failed to parse field [date] of type [date]"}],"type": "mapper_parsing_exception","reason": "failed to parse field [date] of type [date]","caused_by": {"type": "illegal_argument_exception","reason": "Invalid format: \"2015-01-01T12:10:30Z\" is malformed at \"T12:10:30Z\""}},"status": 400}
三、日期字段的参数解析
| boost | 字段级查询时间提权。接受浮点数,默认为1.0。(查询提权) | |||
|---|---|---|---|---|
| doc_values | 字段是否应该以列跨距方式存储在磁盘上,以便以后可以用于排序、聚合或编写脚本?接受true(默认)或false。 | |||
| format | 配置支持的日期格式(支持多格式)。默认:`strict_date_optional_time | epoch_millis` (严格日期,可选时间) |
||
| locale | 分析月份之后的日期时使用的区域设置在所有语言中的名称和/或缩写都不相同。默认值是根区域设置, | |||
ignore_malformed |
如果为true,则忽略格式错误的数字。如果为false(默认值),则格式错误的数字将引发异常并拒绝整个文档。 | |||
index |
该字段是否可以被搜索。接受true(默认)和false。 | |||
null_value |
接受一个已配置格式的日期值作为字段,该字段将替换任何显式空值。默认为空,这意味着该字段被视为丢失。(类似mysql表定义中的默认时间设置) | |||
store |
字段值是否应与源字段分开存储和检索。接受true或false(默认)。 |
