So, you need to aggregate by issue_id
and then find the number of days between the time the issue was opened (status 20) and when it was closed (status 51).
You should be able to run the query below and find exactly what you need in the diff_days
bucket field in the response:
GET test2/_search
{
"size": 0,
"aggs": {
"issues": {
"terms": {
"field": "issue_id",
"size": 10
},
"aggs": {
"openedStatus": {
"filter": {
"term": {
"status_id": "51"
}
},
"aggs": {
"openedDate": {
"min": {
"field": "created_on"
}
}
}
},
"closedStatus": {
"filter": {
"term": {
"status_id": "20"
}
},
"aggs": {
"closedDate": {
"min": {
"field": "closed_on"
}
}
}
},
"diff_days": {
"bucket_script": {
"buckets_path": {
"opened": "openedStatus>openedDate",
"closed": "closedStatus>closedDate"
},
"script": "(params.closed - params.opened) / 86400000"
}
}
}
}
}
}
Results =>
"issues" : {
"doc_count_error_upper_bound" : 0,
"sum_other_doc_count" : 0,
"buckets" : [
{
"key" : 167893,
"doc_count" : 3,
"closedStatus" : {
"doc_count" : 1,
"closedDate" : {
"value" : 1.565005134E12,
"value_as_string" : "2019-08-05T11:38:54.000Z"
}
},
"openedStatus" : {
"doc_count" : 2,
"openedDate" : {
"value" : 1.559556432E12,
"value_as_string" : "2019-06-03T10:07:12.000Z"
}
},
"diff_days" : {
"value" : 63.06368055555556 <--- 63 days
}
}
]
}