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

How to sort buckets by doc_count?

GET /civile/_search
{
  "size": 0,
  "query": {
    "match": {
      "distretto": "MI"
    }
  },
  "aggs": {
    "our_buckets": {
      "composite": {
        "size": 1000,
        "sources": [
          { "codiceoggetto": { "terms": { "field": "codiceoggetto.keyword", "order": "desc" } } }
        ]
      }
    }
  }
}

My Elasticsearch query match documents by distretto = "MI".
With size = 0 I hide results.

But most important thing is that I define our_buckets aggregation.
It return 1000 keys and it do a "group by" on codiceoggetto.keyword field.

Now I want order my buckets results by doc_count! How can I do?

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

>Solution :

you can do it using bucket_sort

{
  "size": 0,
  "query": {
    "match": {
      "distretto": "MI"
    }
  },
  "aggs": {
    "our_buckets": {
      "composite": {
        "size": 1000,
        "sources": [
          {
            "codiceoggetto": {
              "terms": {
                "field": "codiceoggetto.keyword"
              }
            }
          }
        ]
      },
      "aggs": {
        "sort_by_count": {
          "bucket_sort": {
            "sort": [
              {
                "_count": {
                  "order": "desc"
                }
              }
            ]
          }
        }
      }
    }
  }
}
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