# Aggregation: Order by bucket count descending

**URL:** <https://discuss.elastic.co/t/aggregation-order-by-bucket-count-descending/164164>\
**Category:** Elasticsearch\
**Created:** [January 14, 2019, 3:23pm UTC](https://discuss.elastic.co/t/aggregation-order-by-bucket-count-descending/164164 "2019-01-14T15:23:27Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![hello](https://avatars.discourse-cdn.com/v4/letter/h/7993a0/32.png) [@hello](https://discuss.elastic.co/u/hello)\
**Post date:** [January 14, 2019, 3:23pm UTC](https://discuss.elastic.co/t/aggregation-order-by-bucket-count-descending/164164/1 "2019-01-14T15:23:27Z")

</div>

If I use the following aggregation as an example:

```auto
    {
      "aggs" : {
        "actors" : {
          "terms" : {
            "field" : "actors"
          },
          "aggs" : {
            "costars" : {
              "terms" : {
                "field" : "actors"
              }
            }
          }
        }
      }
    }

```

and the results look something like this:

```auto
    "aggregations": {
      "actors": {
        "buckets": [
          {
            "key": "Harvey Keitel",
            "doc_count": 1,
            "costars": {
              "buckets": [
                {
                  "key": "Steve Buscemi",
                  "doc_count": 1
                }, {
                  "key": "Uma Thurman",
                  "doc_count": 1
                }, {
                  "key": "Bruce Willis",
                  "doc_count": 1
                }
              ]
            }
          }
        ]
      }
    }

```

Is there any way to sort by the Actors with the most Costar bucket counts?

---

<div class="post-metadata">

**Author:** ![Mark\_Harwood](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/mark_harwood/32/10538_2.png) [@Mark\_Harwood](https://discuss.elastic.co/u/Mark_Harwood)\
**Post date:** [January 15, 2019, 8:03am UTC](https://discuss.elastic.co/t/aggregation-order-by-bucket-count-descending/164164/2 "2019-01-15T08:03:39Z")

</div>

> [@hello](#):
>
> Is there any way to sort by the Actors with the most Costar bucket counts?

The ‘cardinality’ aggregation can be used to count the costars and you can order by that value. Be careful if you have many stars though because cardinality aggregations can add up in memory costs when you are computing lots of them for a lot of different parent entities. There are controls that trade space for accuracy.

---

<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:** [February 12, 2019, 8:03am UTC](https://discuss.elastic.co/t/aggregation-order-by-bucket-count-descending/164164/3 "2019-02-12T08:03:43Z")

</div>

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.
