Time difference between two timestamps separated by a unique ID using scripted fields

Hi guyz,

I am new to scripted fields. I have logs with entries 'RequestExecuted' and RequestReceived' with their timestamps and connected by unique ID called 'TransactionId'. I am trying to get the time difference between RequestReceived' and 'RequestExecuted' . Below is my logic
´int timetaken = 0;
int start = 0;
String TransactionId;
int end = 0;

for (def dissect_item : params._source['dissect']) {
    if (dissect_item['MessageIdentifier'] == 'RequestReceived') {          
        start = dissect_item['timestamp'].value.millis;          
        TransactionId = dissect_item['TransactionId'];
    }

    if( dissect_item['MessageIdentifier'] =='RequestExecuted' && dissect_item['TransactionId'] == TransactionId) {          
        end = dissect_item['dissect.timestamp'].value.millis;          
        timetaken = end - start; 
        return timetaken;
    }`

and the data in the kibana looks like this:

image
Please help me as I have tried many ways but always getting an error.

Scripted fields in Kibana work only in the context of a single document so it cannot look in another document in order to do the diff. What I would suggest would be to create a scripted field that checks if any of the fields exists in the doc and then returnds that field's value.
Then you can do a serial diff aggregation, split by Transaction ID