Using doc_count to calculate percentage after aggregation

try this:

DELETE test

PUT test/_bulk
{ "index" : {}}
{ "result": "PASS" }
{ "index" : {}}
{ "result": "PASS" }
{ "index" : {}}
{ "result": "PASS" }
{ "index" : {}}
{ "result": "PASS" }
{ "index" : {}}
{ "result": "PASS" }
{ "index" : {}}
{ "result": "PASS" }
{ "index" : {}}
{ "result": "PASS" }
{ "index" : {}}
{ "result": "PASS" }
{ "index" : {}}
{ "result": "PASS" }
{ "index" : {}}
{ "result": "FAIL" }

GET test/_search
{
  "size": 0,
  "aggs": {
    "filters_agg": {
      "filters": {
        "filters": {
          "first": {
            "match_all": {}
          }
        }
      },
      "aggs": {
        "by_result": {
          "terms": {
            "field": "result.keyword",
            "size": 10
          }
        },
        "pass_fail_relation": {
          "bucket_script": {
            "buckets_path": {
              "pass": "by_result['PASS']>_count",
              "fail": "by_result['FAIL']>_count"
            },
            "script": "params.fail/(params.pass + params.fail)"
          }
        }
      }
    }
  }
}
1 Like