# How to sort fields used as terms?

**URL:** <https://discuss.elastic.co/t/how-to-sort-fields-used-as-terms/276325>\
**Category:** Elasticsearch\
**Created:** [June 17, 2021, 11:42pm UTC](https://discuss.elastic.co/t/how-to-sort-fields-used-as-terms/276325 "2021-06-17T23:42:53Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Lucas\_Boswell](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/lucas_boswell/32/90499_2.png) [@Lucas\_Boswell](https://discuss.elastic.co/u/Lucas_Boswell)\
**Post date:** [June 17, 2021, 11:42pm UTC](https://discuss.elastic.co/t/how-to-sort-fields-used-as-terms/276325/1 "2021-06-17T23:42:53Z")

</div>

Hello there,  
I am attempting to understand the sorting/bucket\_sort functionality a bit better. Below is a simple query that groups by a productId, gathers some additional info related to productId, and then calculates a quick sum. How would one sort by the columns that are utilized in the top\_hits aggregation? i.e., if I wanted to sort by form desc.

```auto
{
  "size": 0,
  "aggs": {
    "byProductId": {
      "terms": {
        "field": "productId",
        "size": 10000,
        "order": {
          "_count": "desc"
        }
      },
      "aggs": { 
        "sumQuantity": {
          "sum": {
            "field": "quantity"
          }
        },
        "grouped_info": {
          "top_hits": {
            "size": 1,
            "_source": ["productId","form","strength","genericName"]
          }
        },
        "bucket_sorter": {
          "bucket_sort": {
            "sort": [{"sumQuantity": {"order": "desc"}}]
          }
        }
      }
    }
  }
}

```

I thought I might be able to do this with the bucket\_sort, but I am unable to map to it within the bucket\_sort declaration, but that produces the following error:

```auto
 "Validation Failed: 1: No aggregation [form] found for path [grouped_info>form];"

```

Is what I am trying to do possible? Is there related documentation (besides [Bucket sort aggregation | Elasticsearch Guide [7.13] | Elastic](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-pipeline-bucket-sort-aggregation.html))? Thanks in advance.

---

<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 15, 2021, 11:43pm UTC](https://discuss.elastic.co/t/how-to-sort-fields-used-as-terms/276325/2 "2021-07-15T23:43:49Z")

</div>

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