在Elasticsearch(Python)中按时间戳过滤

时间:2016-10-25 23:32:20

标签: python elasticsearch timestamp

我有一个docs索引。我在Python中编写了弹性搜索查询

query = """{
  "query": {
    "filtered": {
      "filter": {
        "bool": {
          "must": [
            { "term": { "subcategory_id": 3 } },
            { "term": { "category_id": 3 } },
            { "term": { "skill_record_id": 14 } }
          ]
        }
      }
    }
  },
  "size": 5
}"""

并搜索此查询:

print json.dumps( es.search(index=stat_index, body=json.loads( query ) ), indent=4)
{
    "hits": {
        "hits": [
            {
                "_score": 1.0, 
                "_type": "github_stat", 
                "_id": "AVe_-b_QotO5vl4OfuNL", 
                "_source": {
                    "subcategory_id": 3, 
                    "timestamp": {
                        "$date": 1476405398063
                    }, 
                    "category_id": 3, 
                    "skill_record_id": 14
                }, 
                "_index": "db_stat"
            }, 
            ... 
            {
                "_score": 1.0, 
                "_type": "github_stat", 
                "_id": "AVfABKISotO5vl4OfuXa", 
                "_source": {
                    "subcategory_id": 3, 
                    "timestamp": {
                        "$date": 1476406111491
                    }, 
                    "category_id": 3, 
                    "skill_record_id": 14
                }, 
                "_index": "db_stat"
            }
        ], 
        "total": 255, 
        "max_score": 1.0
    }, 
    "_shards": {
        "successful": 5, 
        "failed": 0, 
        "total": 5
    }, 
    "took": 8, 
    "timed_out": false
}

答案中有时间戳字段。所以,当我添加“@timestamp”进行查询时,没有结果(是的,我试过“lt”和“gt”,但仍然没有效果):

query = """{
  "query": {
    "filtered": {
      "filter": {
        "bool": {
          "must": [
            { "term": { "subcategory_id": 3 } },
            { "term": { "category_id": 3 } },
            { "term": { "skill_record_id": 14 } },
            { "range": { "@timestamp": { "lt": 1477437347, "format": "epoch_millis" } } }
          ]
        }
      }
    }
  },
  "size": 2
}"""

print json.dumps( es.search(index=stat_index, body=json.loads( query ) ), indent=4)
{
    "hits": {
        "hits": [], 
        "total": 0, 
        "max_score": null
    }, 
    "_shards": {
        "successful": 5, 
        "failed": 0, 
        "total": 5
    }, 
    "took": 149, 
    "timed_out": false
}

我做错了什么?

0 个答案:

没有答案