Elasticsearch范围过滤字符串返回不正确的结果

时间:2015-03-03 22:33:58

标签: elasticsearch

在我的索引中,我有一个名为“time”的字段,其类型为“string”。还有另一个字段“日期”类型为“日期”。

当我尝试查询索引并根据时间过滤结果时,我得到的结果不正确。例如,我的查询是: {“和”:{“过滤器”:[{“term”:{“date”:“2015-02-06”}},{“range”:{“time”:{“from”:“22:11 “,”到“:”23:59“,”include_lower“:true,”include_upper“:true}}}

在结果中,我得到日期为“2015-02-06”的字段,但时间是“16:01”,“07:01”等。

我做错了什么?

1 个答案:

答案 0 :(得分:1)

您需要格式化时间字段,才能使范围过滤器正常工作。我不认为"range"知道如何处理"string"字段。

这对我有用:"time" : { "type": "date", "format": "HH:mm" }

以下是我使用的完整示例:

DELETE /test_index

PUT /test_index
{
   "settings": {
      "number_of_shards": 1
   },
   "mappings": {
      "doc": {
         "properties": {
             "time" : { "type": "date", "format": "HH:mm" },
             "date" : { "type": "date" }
         }
      }
   }
}

POST /test_index/_bulk
{"index":{"_index":"test_index","_type":"doc","_id":1}}
{"date": "2015-02-06","time": "16:01"}
{"index":{"_index":"test_index","_type":"doc","_id":2}}
{"date": "2015-02-06","time": "07:01"}
{"index":{"_index":"test_index","_type":"doc","_id":3}}
{"date": "2015-02-06","time": "22:30"}
{"index":{"_index":"test_index","_type":"doc","_id":4}}
{"date": "2015-02-08","time": "15:30"}

POST /test_index/_search
{
   "query": {
      "filtered": {
         "query": {
            "match_all": {}
         },
         "filter": {
            "and": {
               "filters": [
                  {
                     "term": {
                        "date": "2015-02-06"
                     }
                  },
                  {
                     "range": {
                        "time": {
                           "from": "22:11",
                           "to": "23:59",
                           "include_lower": true,
                           "include_upper": true
                        }
                     }
                  }
               ]
            }
         }
      }
   }
}
...
{
   "took": 5,
   "timed_out": false,
   "_shards": {
      "total": 1,
      "successful": 1,
      "failed": 0
   },
   "hits": {
      "total": 1,
      "max_score": 1,
      "hits": [
         {
            "_index": "test_index",
            "_type": "doc",
            "_id": "3",
            "_score": 1,
            "_source": {
               "date": "2015-02-06",
               "time": "22:30"
            }
         }
      ]
   }
}