Limit for grouped results in Elasticsearch

My elasticearch search index "people" has 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 the result of documents that have region 2 or 1, but only 2 of them at most. So if the above was my entire index, I would like 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 request in an elastic state? Thank you so much for your help!

+3


source to share


1 answer


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

      

+4


source







All Articles