Compute difference between current and previous doc in ElasticSearch Aggregation

Viewed 330

I have and index which stores measures with following structure:

{sensorId: 'sensor1', value: '13.5', 'timestamp': '2016-02-19 12:00:00'}
{sensorId: 'sensor1', value: '15.7', 'timestamp': '2016-02-19 12:02:00'}
{sensorId: 'sensor1', value: '14.3', 'timestamp': '2016-02-19 12:09:00'}
{sensorId: 'sensor1', value: '14.6', 'timestamp': '2016-02-19 12:13:00'}

Is there any way to aggregate these measures and return the sum of the difference between a measure and the previous measure? For example the operation should be similar to this:

"query" : {
   //operations
 },
  "aggs": {
    "difference_per_day": {
      "date_histogram": {
        "field": "timestamp",
        "interval": "day"
      },
      "aggs": {
        "difference": {
          "sum": {
            "script": "doc[index]['value'].value - doc[index-1]['value'].value"
          }
        }
      }
    }
  }

Is it possible? Thanks in advance.

0 Answers
Related