Sort buckets by the number of sub-buckets?


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.



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