Calculating duration

Hi,
I am not sure if this can be achieved, I have the following query:

GET /winlogbeat-7.14.0-2022.02.03-000001/_search
{
  "query": {
    "match_all": {}
  },
  "aggs": {
    "bulks": {
      "terms": {
        "field": "winlog.event_data.TargetLogonId",
        "size": 10
      },
  "aggs": {
    "bulks": {
      "terms": {
        "field": "winlog.event_data.TargetUserName",
        "size": 10
      },
        "aggs": {
    "bulks": {
      "terms": {
        "field": "host.name",
        "size": 10
      },
      "aggs": {
        "orders": {
          "top_hits": {
            "size": 10
          }
        }
      }
    }
  }
  }
  }
  }
  }
  }

From the query results I need to calculate the following:
Where ever the field - winlog.event_id=4624 appears, this should be the start time(from the timestamp).
Where ever the field - winlog.event_id=4634 appears, this should be the end time.
And than I need to calculate the duration (difference) .
Is there a way to achieve that?

Thanks!

Are winlog.event_id=4624 and winlog.event_id=4634 unique for each [winlog.event_data.TargetLogonId, winlog.event_data.TargetUserName, host.name] buckets? Or are there several start and end events in the bucket and you have to calculate multiple duration.

Anyway, such customized aggregation could be implemented using scripted metric aggregation.