Unable to write painless transform script for Mathematical operation


(Shantanu Deshpande) #1

Hi,

I am stuck at the point that I need to write a painless script which will calculate the percentage difference between two values. In other words, I need to calculate the % variation between the value on the current day and the previous.

So far, I've been able to apply two aggs for two days to get the two values in separate buckets. But I am short on ideas on how to transform the data.

Here's the output of aggs:

"aggregations": {
          "aggs2": {
            "buckets": [
              {
                "doc_count": 3,
                "to_as_string": "2018-05-30T00:00:00.000Z",
                "to": 1527638400000,
                "my_agg": {
                  "value": 549.1748046875
                },
                "key": "*-2018-05-30T00:00:00.000Z"
              },
              {
                "from_as_string": "2018-05-29T00:00:00.000Z",
                "doc_count": 1,
                "from": 1527552000000,
                "my_agg": {
                  "value": 546.0120849609375
                },
                "key": "2018-05-29T00:00:00.000Z-*"
              }
            ]
          },
          "aggs1": {
            "buckets": [
              {
                "doc_count": 2,
                "to_as_string": "2018-05-29T00:00:00.000Z",
                "to": 1527552000000,
                "my_agg": {
                  "value": 549.1748046875
                },
                "key": "*-2018-05-29T00:00:00.000Z"
              },
              {
                "from_as_string": "2018-05-28T00:00:00.000Z",
                "doc_count": 2,
                "from": 1527465600000,
                "my_agg": {
                  "value": 549.1748046875
                },
                "key": "2018-05-28T00:00:00.000Z-*"
              }
            ]
          }
        }

I just want to write a script which compares the two values 549.174 and 546.01, calculate the % difference.

P.S.: I've gone through elastic watcher examples repository on github.

Any help would be appreciated.


(system) #2

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.


(Alexander Reelsen) #3

Hey,

sorry for the late answer, but can you clarify what your problem is? Is it accessing the data or finding the right path or creating a loop to do this for each bucket? Does the below snippet help?

def results = []
for (int i = 0 ; i < ctx.payload.aggregations.aggs2.buckets.size() ; i++) {
  results.add(ctx.payload.aggregations.aggs2.buckets[i].my_agg.value / ctx.payload.aggregations.aggs1.buckets[i].my_agg.value);
}
return [result: results];