Hello!
I faced a limitation on sorting buckets of a term aggrigation, based on a scripted metrics sub aggregation values.
This issue clearly states that it is not possible to do this in elasticsearch.
However, i managed to do this using Bucket Sort aggregation.
Results make sense as far i can tell.
I want to know  am i missing something? is my approach correct?
Query:
{
  "aggs": {
    "by-method-name": {
      "terms": {
        "field": "event_name.keyword"
      },
      "aggs": {
        "percentages_calc": {
          "scripted_metric": {
            "init_script": "state.errors = 0; state.t = 0;",
            "map_script": "if (doc['event_outcome.keyword'].value == 'ERROR') { state.errors += 1;state.t += 1} state.t += 1",
            "combine_script": "return state",
            "reduce_script": "double failureT = 0;double total = 0; for (s in states) {failureT += s.errors; total += s.t} return (failureT/total) * 100;"
          }
        },
        "sort_by_percentage": {
          "bucket_sort": {
            "sort": [
              {
                "percentages_calc.value": {
                  "order": "desc"
                }
              }
            ]
          }
        }
      }
    }
  },
  "size": 0
}
            