How to sort buckets by doc_count?

Advertisements
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?

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

Leave a ReplyCancel reply