# Sorting a terms aggregation by sub-terms-aggregation cardinality aggregation

**URL:** <https://discuss.elastic.co/t/sorting-a-terms-aggregation-by-sub-terms-aggregation-cardinality-aggregation/95049>\
**Category:** Elasticsearch\
**Created:** [July 29, 2017, 7:33pm UTC](https://discuss.elastic.co/t/sorting-a-terms-aggregation-by-sub-terms-aggregation-cardinality-aggregation/95049 "2017-07-29T19:33:27Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![liamwhite](https://avatars.discourse-cdn.com/v4/letter/l/ccd318/32.png) [@liamwhite](https://discuss.elastic.co/u/liamwhite)\
**Post date:** [July 29, 2017, 7:33pm UTC](https://discuss.elastic.co/t/sorting-a-terms-aggregation-by-sub-terms-aggregation-cardinality-aggregation/95049/1 "2017-07-29T19:33:27Z")

</div>

I'd like to be able to order a terms aggregation by the value of a child terms aggregation. Can this be done?

Here's what I have so far:

```auto
:vote_stats:
  :size: 0
  :aggs:
    :ip_votes:
      :terms: { field: 'ip', order: {'images.users.value': 'desc'} } # <- can't do this
      :aggs:
        :images:
          :terms: { field: 'image_id', order: {'users.value': 'desc'} }
          :aggs:
            :users:
              :cardinality: { field: 'user_id' }
            :selector:
              :bucket_selector: { buckets_path: { value: 'users.value' }, script: 'params.value > 1' }

```

If I can't do that, can I at least filter the `ip_votes` aggregation to buckets where the images sub-aggregation isn't empty, as occurs if the order statement was left blank?

Snipped example of current output (the images buckets are empty, I want to find the images buckets that aren't empty):

```json
{
  "doc_count_error_upper_bound": 228,
  "sum_other_doc_count": 58319,
  "buckets": [
    {
      "key": "xx.xx.94.189",
      "doc_count": 3005,
      "images": {
        "doc_count_error_upper_bound": -1,
        "sum_other_doc_count": 2995,
        "buckets": [

        ]
      }
    },
    {
      "key": "xx.xx.116.134",
      "doc_count": 1895,
      "images": {
        "doc_count_error_upper_bound": -1,
        "sum_other_doc_count": 1885,
        "buckets": [

        ]
      }
    },
    {
      "key": "xxxx:xxxx:xxxx:xxxx:c169:fa2b:1eed:6153",
      "doc_count": 1536,
      "images": {
        "doc_count_error_upper_bound": -1,
        "sum_other_doc_count": 1526,
        "buckets": [

        ]
      }
    }
}

```

---

<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:** [August 26, 2017, 7:33pm UTC](https://discuss.elastic.co/t/sorting-a-terms-aggregation-by-sub-terms-aggregation-cardinality-aggregation/95049/2 "2017-08-26T19:33:31Z")

</div>

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