Limit grouped results in Elasticsearch

依然范特西╮ 提交于 2019-12-23 16:06:31

问题


In my elasticsearch index "people" there are the following documents:

{"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}

I would like to get a result of documents that have a district of 2 or 1, but only 2 of them maximum. So if the above were my whole index, I would want it to return:

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

Is it possible to achieve this with a single query in elastic? Thank you very much for your help!


回答1:


Something like this should do it:

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
              }
            }
          }
        }
      }
    }
  }
}


来源:https://stackoverflow.com/questions/31795599/limit-grouped-results-in-elasticsearch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!