# Aggregation: Difference of Two Date Fields to Aggregate Timedeltas

**URL:** <https://discuss.elastic.co/t/aggregation-difference-of-two-date-fields-to-aggregate-timedeltas/84190>\
**Category:** Elasticsearch\
**Created:** [May 2, 2017, 12:51am UTC](https://discuss.elastic.co/t/aggregation-difference-of-two-date-fields-to-aggregate-timedeltas/84190 "2017-05-02T00:51:52Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Michael\_Sander](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/michael_sander/32/838_2.png) [@Michael\_Sander](https://discuss.elastic.co/u/Michael_Sander)\
**Post date:** [May 2, 2017, 12:51am UTC](https://discuss.elastic.co/t/aggregation-difference-of-two-date-fields-to-aggregate-timedeltas/84190/1 "2017-05-02T00:51:52Z")

</div>

1. I have two date fields in my index (e.g., `start_time` and `end_time`). How can I build a histogram that aggregates the difference, _e.g._, `end_time - start_time` to find a total time? I could reindex everything, calculate the differences, store it separately, and run the aggregation on the stored field, but **is there any way to do this at query time**?

2. I want to do it at query time, because I have more than 2 date fields, I have several dozen. To precalculate every combination would require O([number of dates]^2) to be saved in each document. I took a look at [`bucket_script` pipeline aggregations](https://www.elastic.co/guide/en/elasticsearch/reference/5.2/search-aggregations-pipeline-bucket-script-aggregation.html), will they do the trick?

3. Final question part: The dates are stored in nested documents, my mapping looks like this:

```auto
/index-name/_mapping?pretty
{
  "index-name" : { "mappings" : {
      "doc-type" : {
        "properties" : {
          "event_field" : {
            "type" : "nested",
            "properties" : {
              "date" : { "type" : "date" },
              "type" : { "type" : "keyword" }
            }
          }
        }
      }
    } }
}

```

What I would really like to do is aggregate on the difference of the dates in a nested field with `type` property `X` with the date of a nested field with `type` property `Y`. Am I asking too much? Thanks.

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [May 30, 2017, 1:05am UTC](https://discuss.elastic.co/t/aggregation-difference-of-two-date-fields-to-aggregate-timedeltas/84190/2 "2017-05-30T01:05:12Z")

</div>

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