Alexandre Elshobokshy
Alexandre Elshobokshy

Reputation: 10922

Script to compare dates

I would like to compare an elastic search date with a format YYY-MM-DD HH:MM:SS as to compare the results of the past 30 days. So if the given date is equal to NOW()-30D it should give me the result wanted. I have tried comparing it this way with a script but it doesn't work :

getMillis(doc["date"].value) >= (new Date().getTime() - 30 * 24 * 60 * 60 * 1000) ? 1 : 0

Another test not working :

$total= new \Elastica\Aggregation\Sum('total');
$total->setScript('doc["date"].value >= (new Date().getTime() - 30) ? 1 : 0');

This should do this : If doc["date"].value is higher or equal to the last 30 days it should give me 1, else it would give me 2.

How can I achieve that? Knowing that I'm using groovy scripting.

Upvotes: 0

Views: 807

Answers (2)

Val
Val

Reputation: 217444

The script you're looking for looks like this:

ChronoUnit.DAYS.between(Instant.ofEpochMilli(doc['date'].date.millis), Instant.ofEpochMilli(new Date().getTime())) > 30 ? 0 : 1

We compute the number of days between the date field and now. If the number of days is bigger than 30, we return 0, otherwise we return 1.

Upvotes: 2

Gautam V.
Gautam V.

Reputation: 536

You achieve same using range query or date range aggregation, I suggest not to use the script with elastic search unless and until it is difficult to get the result using search query

Upvotes: 0

Related Questions