In Elasticsearch, you can compare dates in a painless script using the Instant class, which allows you to work with date-time values. Here's an example of how to compare dates in a painless script:

Let's assume you have a date field named my_date_field in your Elasticsearch documents, and you want to filter documents where my_date_field is greater than a specific date.

  1. First, you need to construct an Instant object from the date you want to compare. In this example, we'll use the current date as the reference date:
POST your_index/_search { "query": { "bool": { "filter": { "script": { "script": { "lang": "painless", "source": "Instant myDate = Instant.parse(doc['my_date_field'].value); Instant currentDate =; myDate.isAfter(currentDate);" } } } } } }

In the above script, we are using the Instant.parse() method to convert the my_date_field value to an Instant object. We also use to get the current date as another Instant object. Then, we use the isAfter() method to compare the two dates, returning true if my_date_field is after the current date, and false otherwise.

  1. If you want to compare against a specific date instead of the current date, you can construct the Instant object from the desired date using Instant.parse():
POST your_index/_search { "query": { "bool": { "filter": { "script": { "script": { "lang": "painless", "source": "Instant myDate = Instant.parse(doc['my_date_field'].value); Instant specificDate = Instant.parse('2023-07-28T00:00:00Z'); myDate.isAfter(specificDate);" } } } } } }

In this example, we are comparing my_date_field against the specific date '2023-07-28T00:00:00Z'.

Remember that the date format should be in ISO 8601 format ('yyyy-MM-dd'T'HH:mm:ss.SSSZ') for Instant.parse() to work correctly.

By using the Instant class in painless scripts, you can effectively compare dates in Elasticsearch queries.

Have questions or queries?
Get in Touch