# Sort buckets by the number of sub-buckets?

**URL:** <https://discuss.elastic.co/t/sort-buckets-by-the-number-of-sub-buckets/32221>\
**Category:** Elasticsearch\
**Created:** [October 14, 2015, 11:57pm UTC](https://discuss.elastic.co/t/sort-buckets-by-the-number-of-sub-buckets/32221 "2015-10-14T23:57:40Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Laurent\_Querel](https://avatars.discourse-cdn.com/v4/letter/l/3ab097/32.png) [@Laurent\_Querel](https://discuss.elastic.co/u/Laurent_Querel)\
**Post date:** [October 14, 2015, 11:57pm UTC](https://discuss.elastic.co/t/sort-buckets-by-the-number-of-sub-buckets/32221/1 "2015-10-14T23:57:40Z")

</div>

Hi

Is it possible to order the buckets of a first level aggregation by the number of buckets of a second level aggregations. For example I would like to do something like:

```
{
    "aggs" : {
        "aggr_level_1" : {
            "terms" : {
                "field" : "field_1",
                "order" : { "aggr_level_2._count" : "desc" }
            },
            "aggs" : {
                "aggr_level_2" : { "terms" : { "field" : "field_2" } }
            }
        }
    }
}

```

Unfortunately when this request is executed, ES returns the following error:

```
Invalid terms aggregation order path [srcIp.doc_count]. Terms buckets can only be sorted on a sub-aggregator path that is built out of zero or more single-bucket aggregations within the path and a final single-bucket or a metrics aggregation at the path end.

```

Is it a limitation? If yes, is there a workaround? For Info I'm using ES 2.0 beta2 for my test.

Thanks

Laurent

---

<div class="post-metadata">

**Author:** ![colings86](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/colings86/32/44960_2.png) [@colings86](https://discuss.elastic.co/u/colings86)\
**Post date:** [October 15, 2015, 6:22am UTC](https://discuss.elastic.co/t/sort-buckets-by-the-number-of-sub-buckets/32221/2 "2015-10-15T06:22:55Z")

</div>

You could have a cardinality aggregation for the field `field_2` on the second level and order your terms aggregation by the cardinality aggregation.

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [July 5, 2017, 11:44pm UTC](https://discuss.elastic.co/t/sort-buckets-by-the-number-of-sub-buckets/32221/3 "2017-07-05T23:44:42Z")

</div>


