我想我最终找到了根本原因。在为文档建立索引时,ES会将提供的值视为UTC日期/时间。查询时,ES使用UTC日期/时间
now与索引的时间戳进行比较。
假设我比UTC落后5个小时,并且正在使用本地日期/时区为文档编制索引,那么我的查询实际上是在说“给我少于5个小时-从现在开始30分钟的日期。
这是我最终编写的查询,以查看它在字面上进行比较的值,以及为实现布尔查询内部的“预期”结果而要做的事情:
GET test-index/testType/_search?pretty{ "query": { "bool" : { "must" : { "script" : { "script" : { "inline": "doc['timestamp'].value < new Date().getTime() - (5 * 60 * 60 * 1000) - (120 * 60 * 1000)", "lang": "painless"} } } } }, "script_fields": { "timestampValue" : { "script" : "doc['timestamp'].value" }, "valueTimestampMustBeLessThan" : { "script" : "new Date().getTime() - (120 * 60 * 1000)" }, "now" : { "script" : "new Date().getTime()" }, "subtract": { "script": "(120 * 60 * 1000)" }, "timestamp" : { "script" : "doc['timestamp']" }, "lt?" : { "script" : "doc['timestamp'].value < new Date().getTime() - (120 * 60 * 1000)" }, "gt?" : { "script" : "doc['timestamp'].value > new Date().getTime() - (120 * 60 * 1000)" } }}一个例子:
- 我在2017年8月18日下午6:40左右插入的文档读取其UTC时间为该时间,而其“本地”时间为1:40 pm。
- 我在2017年8月18日下午6:41左右运行的查询读取
now
的UTC时间为11:41 pm,其“本地”时间为6:41 pm。
ES文档中有很多地方提到它使用UTC中的日期,例如:
- https://www.elastic.co/guide/zh-CN/elasticsearch/reference/current/date.html
- https://www.elastic.co/guide/zh-CN/elasticsearch/reference/current/query-dsl-range-query.html#CO160-2
但是直到现在我还是完全不了解其中的含义。
在执行操作时,我只需要确保我的应用插入了UTC时间,尤其是在给定时区的情况下。



