Comparing timestamps in painless


(Steve Stevens) #1

How do I check if a payload timestamp (_source['@timestamp']) to scheduled time plus 5 minutes?

def schedTimestamp=Instant.ofEpochMilli(ctx.trigger.scheduled_time.getMillis()).plus(Duration.ofMinutes(+5);
def payloadTimestamp=ctx.payload.hits.hits[0]._source['@timestamp'];
return schedTimestamp.isBefore(payloadTimestamp);

I'm trying to make use of the mechanism in a more complicated script transform but I can't seem to get an Instant of payloadTimestamp.


(Alexander Reelsen) #2

Hey,

the initial idea is correct. However ctx.payload.hits.hits[0]._source['@timestamp'] is not of type datetime but just a string, thus the comparison fails. You need to convert that one also into an Instant. You can try to use Instant.parse() for that.

--Alex


(Steve Stevens) #3

Thanks for the swift reply.
My date is in the format
2018-01-17T11:10:42.217+00:00
As opposed to the expected
2018-01-17T11:10:42.217Z

I get the following error:
{
"type": "date_time_parse_exception",
"reason": "Text '2018-01-17T11:10:42.217Z+00:00' could not be parsed, unparsed text found at index 24"
}

I've had a look at the java.time doc for Instant and there doesn't seem to be a parse method that allows for a dateformatter.
Would you be able to make a suggestion?


(Alexander Reelsen) #4

How about something like

def formatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
def x = LocalDateTime.parse(ctx.payload.timestamp, formatter);

--Alex


(Steve Stevens) #5

Thanks again for the help.

I gave that a go but despite whilst it successfully parsed the string it seems to just be culling the zoning entirely.
Using the same DateTimeFormatter constant I used the following:

Instant.from( DateTimeFormatter.ISO_OFFSET_DATE_TIME.parse( ctx.payload.timestamp ) );

and that produces an Instant with the offset.

Thanks for the support!


(system) #6

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.