Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

ElasticSearch get top 2 results per specific term in aggregations

Given this query, i want to retrieve and limit only to top 2 cities from each country.
So, given the most popular country, retrieve top 2 cities, then next country, top 2 cities and etcera.

{
  "size": 0,
  "aggs": {
    "user_city_id": {
      "terms": {
        "field": "user.city_id",
        "size": 999
      },
      "aggs": {
        "user_country_id": {
          "terms": {
            "field": "user.country_id",
            "size": 1
          },
          "aggs": {
            "user_name": {
              "terms": {
                "field": "user.name",
                "size": 1
              }
            }
          }
        }
      }
    }
  },
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "user.category": 1
          }
        }
      ]
    }
  }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Below aggregation query give you 2 city per country.

{
  "aggs": {
    "user_country_id": {
      "terms": {
        "field": "user.country_id",
        "size": 10
      },
      "aggs": {
        "user_city_id": {
          "terms": {
            "field": "user.city_id",
            "size": 2
          }
        }
      }
    }
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading