{
"size": 0,
"query": {
"bool": {
"must": [
{
"terms": {
"state": ["active", "inactive"]
}
}
]
}
},
"aggs": {
"users": {
"terms": {
"field": "userId",
"size": 10
},
"aggs": {
"sessions": {
"terms": {
"field": "userSession",
"size": 10
},
"aggs": {
"states": {
"terms": {
"field": "state",
"size": 2
},
"aggs": {
"timestamps": {
"min": {
"field": "@timestamp"
}
}
}
},
"duration": {
"scripted_metric": {
"init_script": "state.timestamps = []",
"map_script": "if (doc['state.keyword'].value == 'active') { state.timestamps.add(doc['@timestamp'].value.toInstant().toEpochMilli()) } else if (doc['state.keyword'].value == 'inactive') { state.timestamps.add(doc['@timestamp'].value.toInstant().toEpochMilli()) }",
"combine_script": "return state.timestamps",
"reduce_script": "long duration = 0; if (states.size() == 2) { duration = states[1] - states[0]; } return duration;"
}
}
}
}
}
}
}
}