# Sorting through average aggregation

**URL:** <https://discuss.elastic.co/t/sorting-through-average-aggregation/93102>\
**Category:** Elasticsearch\
**Created:** [July 14, 2017, 2:43am UTC](https://discuss.elastic.co/t/sorting-through-average-aggregation/93102 "2017-07-14T02:43:07Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![SamA](https://avatars.discourse-cdn.com/v4/letter/s/7993a0/32.png) [@SamA](https://discuss.elastic.co/u/SamA)\
**Post date:** [July 14, 2017, 2:43am UTC](https://discuss.elastic.co/t/sorting-through-average-aggregation/93102/1 "2017-07-14T02:43:07Z")

</div>

I have a nested aggregate query. First, I group the items by phone, then by carrier, and then by their average prices. I want the average pricing to be in descending order. For example, I want my documents to look like this:

> .iPhone 6

> ...Verizon

> ......$250

> ...T-Mobile

> ......$235

> ...Sprint

> ........$220

Here's my current query:

```
{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "market": "American"
          }
        }
      ],
      "filter": [
        {
          "range": {
            "Purchase": {
              "gte": 20170530,
              "lte": 20170602
            }
          }
        }
      ]
    }
  },

  "aggs": {
    "group_by_phone": {
      "terms": {
        "field": "phone",
        "order": {
          "_term": "asc"
        },
        "size": 200
      },
      "aggs": {
        "group_by_carrier": {
          "terms": {
            "field": "carrier"
          },
          "aggs": {
            "group_by_avg": {
              "avg": {
                "field": "price"
              }
            }
          }
        }
      }
    },
    "group_by_carriers": {
      "terms": {
        "field": "carriers",
        "order": {
          "_term": "asc"
        },
        "size": 200
      }
    }
  }
}

```

How do I put the pricing in descending order?

---

<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 11, 2017, 2:43am UTC](https://discuss.elastic.co/t/sorting-through-average-aggregation/93102/2 "2017-08-11T02:43:08Z")

</div>

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