title: ElasticSearch calculate percentage for each bucket from total
body: <p>I'm using ElasticSearch v5. I'm trying to do something similar described in <a href="https://stackoverflow.com/questions/33532425/elasticsearch-analytics-percent">Elasticsearch analytics percent</a> where I have a terms aggregation and I want to calculate a percentage which is a value from each bucket over the total of all buckets. This is my request:</p>
  
  <pre><code>{
    "query": {
      "match_all": {}
    },
    "aggs": {
      "periods": {
        "terms": { 
          "field": "periods",
          "size": 3
        },
        "aggs": {
          "balance": {
            "sum": {
              "field": "balance"
            }
          }
        }
      },
      "total_balance": {
          "sum_bucket": {
              "buckets_path": "periods&gt;balance" 
          }
      }
    }
  </code></pre>
  
  <p>}</p>
  
  <p>The result I get back this like this:</p>
  
  <pre><code>{
    "aggregations": {
      "periods": {
        "doc_count_error_upper_bound": 0,
        "sum_other_doc_count": 1018940846,
        "buckets": [
          {
            "key": 1177977600000,
            "doc_count": 11615418,
            "balance": {
              "value": 2492032741768.1616
         }
         },
         {
            "key": 1185926400000,
            "doc_count": 11592425,
            "balance": {
              "value": 2575365325406.6533
        }
        },
        {
            "key": 1175385600000,
            "doc_count": 11477402,
            "balance": {
              "value": 2456256695380.8306
            }
          }
        ]
      },
      "total_balance": {
        "value": 7523654762555.645
      }
    }
  }
  </code></pre>
  
  <p>How do I calculate "balance"/"total_balance" for each item in the bucket from ElasticSearch? I tried bucket script aggregation at the bucket (periods) level, but I cannot set my buckets_path to total_balance. This post <a href="https://discuss.elastic.co/t/combining-two-aggregations-to-get-term-percentage/22201" rel="noreferrer">https://discuss.elastic.co/t/combining-two-aggregations-to-get-term-percentage/22201</a> talks about using Significant Terms Aggregation, but I need calculation of using specific fields, not doc_count. I know I can do this as a simple calculation on the client side, but I would like to do this all together in ElasticSearch if possible.</p>