mapping——date类型
JSON没有日期数据类型,因此Elasticsearch中的日期可以是:
包含格式化日期的字符串,例如“2015-01-01”或“2015/01/01 12:10:30”。
一个长数字,表示自纪元以来的毫秒数。milliseconds-since-the-epoch
一个整数,表示自纪元以来的秒数。seconds-since-the-epoch.
包含格式化日期的字符串,例如“2015-01-01”或“2015/01/01 12:10:30”。
一个长数字,表示自纪元以来的毫秒数。milliseconds-since-the-epoch
一个整数,表示自纪元以来的秒数。seconds-since-the-epoch.
在内部,日期转换为UTC(如果指定了时区)并存储为表示自纪元以来毫秒的长数字。milliseconds-since-the-epoch
对日期的查询在内部转换为对此长表示形式的范围查询,聚合和存储字段的结果将转换回字符串,具体取决于与字段关联的日期格式。
可以自定义日期格式,但如果未指定格式,则使用默认值:“Strict_Date_Optional_Time|Epoch_Millis”
这意味着它将接受具有可选时间戳的日期,这些时间戳符合Strict_Date_Optional_Time支持的格式或自纪元以来的毫秒数。
这意味着它将接受具有可选时间戳的日期,这些时间戳符合Strict_Date_Optional_Time支持的格式或自纪元以来的毫秒数。
es的日期格式默认识别:
#es版本是6.4
1 PUT gg 2 { 3 "mappings": { 4 "_doc":{ 5 "properties": { 6 "date": { 7 "type": "date" 8 } 9 } 10 } 11 } 12 }
GET gg/_mapping
1 { 2 "gg": { 3 "mappings": { 4 "_doc": { 5 "properties": { 6 "date": { 7 "type": "date" 8 } 9 } 10 } 11 } 12 } 13 }
1 PUT gg/_doc/1 2 { "date": "2015-01-01" } 3 4 PUT gg/_doc/2 5 { "date": "2015-01-01T12:10:30Z" } 6 7 PUT gg/_doc/3 8 { "date": 1420070400001 }
创建成功
1 PUT gg/_doc/4 2 { "date": "2019-01-01 12:10:30" } 3 4 5 报错,格式不对 6 { 7 "error": { 8 "root_cause": [ 9 { 10 "type": "mapper_parsing_exception", 11 "reason": "failed to parse [date]" 12 } 13 ], 14 "type": "mapper_parsing_exception", 15 "reason": "failed to parse [date]", 16 "caused_by": { 17 "type": "illegal_argument_exception", 18 "reason": "Invalid format: \"2019-01-01 12:10:30\" is malformed at \" 12:10:30\"" 19 } 20 }, 21 "status": 400 22 }
手动设置日期字段的格式:
#新增一个字段,原来的字段创建之后就无法修改。
1 PUT gg/_doc/_mapping 2 { 3 "properties":{ 4 "date1":{ 5 "type":"date", 6 "format": "yyyy-MM-dd HH:mm:ss||strict_date_optional_time||epoch_millis" 7 } 8 } 9 }
PUT gg/_doc/4 { "date1": "2019-01-01 12:10:30" }
#插入成功 { "_index": "gg", "_type": "_doc", "_id": "4", "_version": 1, "result": "created", "_shards": { "total": 2, "successful": 1, "failed": 0 }, "_seq_no": 1, "_primary_term": 1 }
查看index的mapping格式:
1 GET gg/_mapping 2 3 { 4 "gg": { 5 "mappings": { 6 "_doc": { 7 "properties": { 8 "date": { 9 "type": "date" 10 }, 11 "date1": { 12 "type": "date", 13 "format": "yyyy-MM-dd HH:mm:ss||strict_date_optional_time||epoch_millis" 14 } 15 } 16 } 17 } 18 } 19 }
GET gg/_search { "took": 4, "timed_out": false, "_shards": { "total": 5, "successful": 5, "skipped": 0, "failed": 0 }, "hits": { "total": 4, "max_score": 1, "hits": [ { "_index": "gg", "_type": "_doc", "_id": "2", "_score": 1, "_source": { "date": "2015-01-01T12:10:30Z" } }, { "_index": "gg", "_type": "_doc", "_id": "4", "_score": 1, "_source": { "date1": "2019-01-01 12:10:30" } }, { "_index": "gg", "_type": "_doc", "_id": "1", "_score": 1, "_source": { "date": "2015-01-01" } }, { "_index": "gg", "_type": "_doc", "_id": "3", "_score": 1, "_source": { "date": 1420070400001 } } ] } }