限制Elasticsearch中的分组结果

时间:2015-08-03 19:49:43

标签: elasticsearch group-by

在我的弹性搜索索引"人们"有以下文件:

{"name": "John", "district": 1},
{"name": "Anne", "district": 1},
{"name": "Mary", "district": 2},
{"name": "Bobby", "district": 2},
{"name": "Nick", "district": 1},
{"name": "Bob", "district": 3},
{"name": "Kenny", "district": 1}

我想获得区域为2或1的文档的结果,但最多只有2个。所以,如果以上是我的整个索引,我希望它返回:

{"name": "John", "district": 1},
{"name": "Anne", "district": 1},
{"name": "Mary", "district": 2},
{"name": "Bobby", "district": 2},

是否可以使用弹性的单个查询来实现此目的? 非常感谢你的帮助!

1 个答案:

答案 0 :(得分:5)

这样的事情应该这样做:

GET /some_index/some_type/_search?search_type=count
{
  "aggs": {
    "district_1_or_2": {
      "filter": {
        "bool": {
          "should": [
            {
              "term": {
                "district": 1
              }
            },
            {
              "term": {
                "district": 2
              }
            }
          ]
        }
      },
      "aggs": {
        "district": {
          "terms": {
            "field": "district",
            "size": 10
          },
          "aggs": {
            "top": {
              "top_hits": {
                "size": 2
              }
            }
          }
        }
      }
    }
  }
}