Static field - Calculate diffs between date fields with painless

I'm attempting to add a new static field on an existing index, and having struggles getting data back in the preview to verify syntax.

I've confirmed that both fields are registered as "date" type in the index.

Here's the config I'm trying to use in the Scripted Field designer:
Language: painless
Type: number
Format: default (number)
Popularity: 1

Script:

return doc['end_time'].value - doc['start_time'].value;

Note - the version in use is 6.8.

*** Just saw you are on version 6.8 and I am not sure it contains the library below on that far back of a version. But will leave the answer here since it applies to newer versions.

I would use the datetime API to do anything with dates. Here is how do to do difference between dates.

Something like the below. I did miliseconds but you can choose a different unit.

ZonedDateTime end = ZonedDateTime.parse(doc['end_time'].value); 
ZonedDateTime start = ZonedDateTime.parse(doc['start_time'].value); 

long differenceInMillis = ChronoUnit.MILLIS.between(start, end);

return differenceInMillis;

Hi Aaron, thanks for your help.

I've just attempted that (with a slight adjustment on object names) and still am getting no results :confused:

ZonedDateTime end = ZonedDateTime.parse(doc['end_time'].value); 
ZonedDateTime start = ZonedDateTime.parse(doc['start_time'].value); 

long differenceInMillis = ChronoUnit.MILLIS.between(start, end);

return differenceInMillis;

image

Did you see my note about versions? I don't think this will work on 6.8 and only newer versions.

I did see that, but I figured I'd give it a shot to capture the outcomes here. Thanks.

If I get some time I'll look up how to do it with that version.

1 Like

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