ElasticSearch:查询是否存在具有指定字段值

时间:2015-07-08 15:28:56

标签: elasticsearch

我有一个元素ID列表(例如:[1,23,42,45]),我正在寻找检查具有这些ID的ES数据库元素是否已经存在的最快方法。结果我想收到仅包含Elasticsearch中存在的id的响应:例如[1,42] - 这意味着具有id 1和42的元素仍在DB中。

现在我发送数据库中所有元素ID的查询,然后检查这些列表中是否有我的[1,23,42,45]。有没有更快的方法?

2 个答案:

答案 0 :(得分:1)

您可以使用ids query

GET /your_index/your_type/_search
{
  "query": {
    "ids": {
      "values": [1, 23, 42, 45]
    }
  },
  "fields": []
}

答案 1 :(得分:0)

Here's another way, if what you are wanting is just a list of existing ids from the list you supply (I can't tell if that's what you're asking for or not):

POST /test_index/_search?search_type=count
{
    "aggs": {
        "id_terms": {
            "terms": {
                "field": "id",
                "include": [1, 23, 42, 45]
            }
        }
    }
}

If I have documents with ids 1,2,3,42, the response is:

{
   "took": 1,
   "timed_out": false,
   "_shards": {
      "total": 1,
      "successful": 1,
      "failed": 0
   },
   "hits": {
      "total": 4,
      "max_score": 0,
      "hits": []
   },
   "aggregations": {
      "id_terms": {
         "doc_count_error_upper_bound": 0,
         "sum_other_doc_count": 0,
         "buckets": [
            {
               "key": 1,
               "doc_count": 1
            },
            {
               "key": 42,
               "doc_count": 1
            }
         ]
      }
   }
}

Here is the code I used to test it:

http://sense.qbox.io/gist/96d8d27078e74f7645eee85044b59899c57d0022