我有一个带有以下映射的字段“ aDate”(以及许多其他字段)的elasticsearch索引
"aDate" : { "type" : "date", "format" : "date_optional_time" }
当我查询文件时,我得到类似的结果
"aDate" : 1421179734000,
我知道这是时代,内部的java / elasticsearch日期格式,但是我想要一个类似的结果:
"aDate" : "2015-01-13T20:08:54",
我玩脚本
{ "query":{ "match_all":{ } }, "script_fields":{ "aDate":{ "script":"if (!_source.aDate?.equals('null')) new java.text.SimpleDateFormat('yyyy-MM-dd\\'T\\'HH:mm:ss').format(new java.util.Date(_source.aDate));" } } }
但是它给出了奇怪的结果( 脚本基本上可以正常工作,但是aDate是唯一返回的字段,而_source丢失了 )。看起来像
"hits": [{ "_index": "idx1", "_type": "type2", "_id": "8770", "_score": 1.0, "fields": { "aDate": ["2015-01-12T17:15:47"] } },
如果可能的话,我希望没有脚本的解决方案。
在Elasticsearch中运行查询时,您可以请求其返回原始数据,例如,指定字段:
curl -XGET http://localhost:9200/myindex/date-test/_search?pretty -d ' { "fields" : "aDate", "query":{ "match_all":{ } } }'
将以您最初存储日期的格式为您提供日期:
{ "_index" : "myindex", "_type" : "date-test", "_id" : "AUrlWNTAk1DYhbTcL2xO", "_score" : 1.0, "fields" : { "aDate" : [ "2015-01-13T20:08:56" ] } }, { "_index" : "myindex", "_type" : "date-test", "_id" : "AUrlQnFgk1DYhbTcL2xM", "_score" : 1.0, "fields" : { "aDate" : [ 1421179734000 ] }
除非使用脚本,否则无法更改日期格式。
curl -XGET http://localhost:9200/myindex/date-test/_search?pretty -d ' { "query":{ "match_all":{ } }, "script_fields":{ "aDate":{ "script":"use( groovy.time.TimeCategory ) { new Date( doc[\"aDate\"].value ) }" } } }'
将返回:
{ "_index" : "myindex", "_type" : "date-test", "_id" : "AUrlWNTAk1DYhbTcL2xO", "_score" : 1.0, "fields" : { "aDate" : [ "2015-01-13T20:08:56.000Z" ] } }, { "_index" : "myindex", "_type" : "date-test", "_id" : "AUrlQnFgk1DYhbTcL2xM", "_score" : 1.0, "fields" : { "aDate" : [ "2015-01-13T20:08:54.000Z" ] } }
要应用格式,请按如下所示附加格式:
"script":"use( groovy.time.TimeCategory ){ new Date( doc[\"aDate\"].value ).format(\"yyyy-MM-dd\") }"
将返回 "aDate" : [ "2015-01-13" ]
"aDate" : [ "2015-01-13" ]
要显示T,您需要使用引号,但将其替换为等效的Unicode:
T
"script":"use( groovy.time.TimeCategory ){ new Date( doc[\"aDate\"].value ).format(\"yyyy-MM-dd\u0027T\u0027HH:mm:ss\") }"
退货 "aDate" : [ "2015-01-13T20:08:54" ]
"aDate" : [ "2015-01-13T20:08:54" ]
在查询中使用 _source 指定要返回的字段:
curl -XGET http://localhost:9200/myindex/date-test/_search?pretty -d ' { "_source" : "name", "query":{ "match_all":{ } }, "script_fields":{ "aDate":{ "script":"use( groovy.time.TimeCategory ) { new Date( doc[\"aDate\"].value ) }" } } }'
将返回我的name字段:
name
"_source":{"name":"Terry"}, "fields" : { "aDate" : [ "2015-01-13T20:08:56.000Z" ] }
使用星号将返回所有字段,例如: "_source" : "*",
"_source" : "*",
"_source":{"name":"Terry","aDate":1421179736000}, "fields" : { "aDate" : [ "2015-01-13T20:08:56.000Z" ] }