# Aggregate on nested document with filters

**URL:** <https://discuss.elastic.co/t/aggregate-on-nested-document-with-filters/173874>\
**Category:** Elasticsearch\
**Created:** [March 26, 2019, 8:07am UTC](https://discuss.elastic.co/t/aggregate-on-nested-document-with-filters/173874 "2019-03-26T08:07:14Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Kingpin007](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/kingpin007/32/42760_2.png) [@Kingpin007](https://discuss.elastic.co/u/Kingpin007)\
**Post date:** [March 26, 2019, 8:07am UTC](https://discuss.elastic.co/t/aggregate-on-nested-document-with-filters/173874/1 "2019-03-26T08:07:14Z")

</div>

USING ELASTICSEARCH 6.2  
So I have a rather deeply-nested document structure.

```
{
    "type": "Certain Type",
    "lineItems": [
        {
            "lineValue": 10,
            "events": [
                {
                    "name": "CREATED",
                    "timeStamp": "TIME VALUE"
                },
                {
                    "name": "ENDED",
                    "timeStamp": "TIME VALUE"
                }
            ]
        }
    ]
}

```

What I want to do is find out the average time required for all lines to go from CREATED to ENDED.

So I wrote a query like -  
GET returnorderdata/returnorders/\_search

```
{
  "size": 0,
  "query": {
    "match": {
      "type": "Certain Type"
    }
  },
  "aggs": {
    "avg time": {
      "nested": {
        "path": "lineItems.events"
      },
      "aggs": {
        "avg time": {
          "avg": {
            "script": {
              "lang": "painless",
              "source": """
          long timeDiff = 0; 
          long fromTime = 0; 
          long toTime = 0; 
          if(doc['lineItems.events.name.keyword'] == "CREATED"){
            fromTime = doc['lineItems.events.timeValue'].value.getMillis();
          }
          else if(doc['lineItems.events.name.keyword'] == "ENDED"){
            toTime = doc['lineItems.events.timeValue'].value.getMillis();
          }
          timeDiff = toTime-fromTime;
          return (timeDiff)
          """
            }
          }
        }
      }
    }
  }
}

```

I end up getting 0 as the answer. Is there any way to achieve this in ElasticSearch?

---

<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:** [April 23, 2019, 8:07am UTC](https://discuss.elastic.co/t/aggregate-on-nested-document-with-filters/173874/2 "2019-04-23T08:07:16Z")

</div>

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