Calculate values over aggregation results

Hello,

I am trying to ‘minus’ operation after below terms aggregation.

GET test02/_search
{
  "aggs": {
    "txid_aggs": {
      "terms": {
        "field": "txid.keyword",
        "size": 10
      },
      "aggs": {
        "logdate_aggs": {
          "terms": {
            "field": "logdate",
            "size": 10
          }
        }
      }
    }
  },
  "size": 0
}

result looks like below but i don’t know how i can do minus operation with "key " field values from the aggregation result
(e.g. "2019-06-05T01:51:44.498Z" - "2019-06-05T01:51:48.498Z").

{
  "took" : 16,
  "timed_out" : false,
  "_shards" : {
    "total" : 5,
    "successful" : 5,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : 6,
    "max_score" : 0.0,
    "hits" : [ ]
  },
  "aggregations" : {
    "txid_aggs" : {
      "doc_count_error_upper_bound" : 0,
      "sum_other_doc_count" : 0,
      "buckets" : [
       {
          "key" : "67890ba-d7db-4367-a0c8-fbeffb7c9dfb",
          "doc_count" : 2,
          "logdate_aggs" : {
            "doc_count_error_upper_bound" : 0,
            "sum_other_doc_count" : 0,
            "buckets" : [
              {
                "key" : 1559699504498,
                "key_as_string" : "2019-06-05T01:51:44.498Z",
                "doc_count" : 1
              },
              {
                "key" : 1559699508498,
                "key_as_string" : "2019-06-05T01:51:48.498Z",
                "doc_count" : 1
              }
            ]
          }
        }
      ]
    }
  }
}

please advise. thank you!!!

Isn't it possible to perform calculation with "key" values after aggregation??

I just need the result from "1559699504498" - "1559699508498" from above aggregation result.

Please advise.

Thank you!

Please advise

I don't think there's a way to do exactly what you want, but maybe there's a creative workaround?

For example, are there always going to be two timestamps in each of the buckets for txid.keyword? In that case, you could calculate the min and the max values of logdate. Those you can then subtract using a bucket_script aggregation. The result would be something like this:

GET test02/_search
{
  "aggs": {
    "txid_aggs": {
      "terms": {
        "field": "txid.keyword",
        "size": 10
      },
      "aggs": {
        "min": {
          "min": {
            "field": "logdate"
          }
        },
        "max": {
          "max": {
            "field": "logdate"
          }
        },
        "diff": {
          "bucket_script": {
            "buckets_path": {
              "min": "min",
              "max": "max"
            },
            "script": "params.max - params.min"
          }
        }
      }
    }
  },
  "size": 0
}
1 Like

it works. thank you so much!!! :slight_smile: