Calculate timestamp duration to next document

You can concatenate the individual events using a scripted metric like in this post: Concatenating array objects in elasticsearch transform aggregations

The script should be enhanced to sort the events by time, then you can iterate over the list and add duration fields.

Unfortunately I don't see a possibility to flatten the structure. With "flatten" I mean breaking the group by into individual documents again.