Division of two fields in Elasticsearch

Adi*_*tel 2 groovy elasticsearch

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 :

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)

I tried adding script but i am getting NaN , also to enable this; i had to enable them first in elasticsearch.yml file

script.engine.groovy.inline.aggs: on

Query

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"
          }
        }
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

This particular query is showing me a 'NaN' in output. If I replace the division to multiplication the query works.

Essentially what i am looking for is to divide my two aggregators "spe" and "gained"

Thanks!

Val*_*Val 5

It might be possible that doc.gain is 0 in some of your documents. You may try changing the script to this instead:

"script": "doc['gain'].value != 0 ? doc['spend'].value / doc['gain'].value : 0"
Run Code Online (Sandbox Code Playgroud)

UPDATE

If you want to compute the ratio of the result of two other metric aggregations, you can do so using a bucket_script aggregation (only available in ES 2.0, though).

{
  ...
  "aggs": {
    "custom_name": {
      "terms": {
        "field": "a_name"
      },
      "aggs": {
        "spe": {
          "sum": {
            "field": "spend"
          }
        },
        "gained": {
          "sum": {
            "field": "gain"
          }
        },
        "bucket_script": {
          "buckets_paths": {
            "totalSpent": "spe",
            "totalGained": "gained"
          },
          "script": "totalSpent / totalGained"
        }
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)