# Elasticsearch bucket\_script to subtract two timestamps

**URL:** <https://discuss.elastic.co/t/elasticsearch-bucket-script-to-subtract-two-timestamps/125309>\
**Category:** Elasticsearch\
**Created:** [March 23, 2018, 6:22am UTC](https://discuss.elastic.co/t/elasticsearch-bucket-script-to-subtract-two-timestamps/125309 "2018-03-23T06:22:44Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![abdon](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/abdon/32/9195_2.png) [@abdon](https://discuss.elastic.co/u/abdon)\
**Post date:** [March 23, 2018, 10:24am UTC](https://discuss.elastic.co/t/elasticsearch-bucket-script-to-subtract-two-timestamps/125309/2 "2018-03-23T10:24:57Z")

</div>

Do you need those `firstUrl` and `lastUrl` aggregations to be `terms` aggregations? Because if you change those to `min` and `max` aggregations the solution is simple:

```auto
{
  "query": {
    "bool": {
      "filter": {
        "range": {
          "page.time": {
            "gte": "now-w",
            "lte": "now"
          }
        }
      }
    }
  },
  "aggs": {
    "sessionLengthData": {
      "terms": {
        "field": "sId.keyword",
        "size": 10
      },
      "aggs": {
        "firstUrl": {
          "min": {
            "field": "page.time"
          }
        },
        "lastUrl": {
          "max": {
            "field": "page.time"
          }
        },
        "sessionLength": {
          "bucket_script": {
            "buckets_path": {
              "startTime": "firstUrl",
              "endTime": "lastUrl"
            },
            "script": "params.endTime - params.startTime"
          }
        }
      }
    }
  }
}

```

---

_[View the full topic](https://discuss.elastic.co/t/elasticsearch-bucket-script-to-subtract-two-timestamps/125309)._
