Aggregate on nested document with filters

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?

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