How to sort fields used as terms?

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.

{
  "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:

 "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)? Thanks in advance.

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