title: Division of two fields in Elasticsearch
body: <p>Currently i am trying to group a field based on one field and than getting sum of other fields with respect to the respective field used for grouping. I want to get a new value which needs to be division of the summed field . I will provide the current query i have :</p>
  
  <p>In my query i am aggregating them based on the field ("a_name") and summing "spend" and "gain". I want to get a new field which would be ratio of sum (spend/gain)</p>
  
  <p>I tried adding script but i am getting NaN , also to enable this; i had to enable them first in elasticsearch.yml file</p>
  
  <p>script.engine.groovy.inline.aggs: on</p>
  
  <p>Query</p>
  
  <pre><code>GET /index1/table1/_search
  {
    "size": 0,
    "query": {
      "filtered": {
        "query": {
          "query_string": {
            "query": "*",
            "analyze_wildcard": true
          }
        },
        "filter": {
          "bool": {
            "must": [
              {
                "term": {
                  "account_id": 29
                }
              }
            ],
            "must_not": []
          }
        }
      }
    },
    "aggs": {
      "custom_name": {
        "terms": {
          "field": "a_name"
        },
        "aggs": {
          "spe": {
            "sum": {
              "field": "spend"
            }
          },
          "gained": {
            "sum": {
              "field": "gain"
            }
          },
          "rati": {
            "sum": {
              "script": "doc['spend'].value/doc['gain'].value"
            }
          }
        }
      }
    }
  }
  </code></pre>
  
  <p>This particular query is showing me a 'NaN' in output. If I replace the division to multiplication the query works.</p>
  
  <p>Essentially what i am looking for is to divide my two aggregators "spe" and "gained"</p>
  
  <p>Thanks!</p>