Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit grouped results in Elasticsearch

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!

like image 622
Max101 Avatar asked Mar 16 '23 05:03

Max101


1 Answers

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
              }
            }
          }
        }
      }
    }
  }
}
like image 66
Andrei Stefan Avatar answered Apr 05 '23 23:04

Andrei Stefan