mamol
mamol

Reputation: 158

Get date value in update query elasticsearch painless

I'm trying to get millis value of two dates and subtract them to another. When I used ctx._sourse.begin_time.toInstant().toEpochMilli() like doc['begin_time'].value.toInstant().toEpochMilli() it gives me runtime error. And ctx._source.begin_time.date.getYear() (like this Update all documents of Elastic Search using existing column value) give me runtime error with message

  "ctx._source.work_time = ctx._source.begin_time.date.getYear()",
  "                                              ^---- HERE"

What type I get with ctx._source if this code works correctly doc['begin_time'].value.toInstant().toEpochMilli(). I can't find in documentation of painless how to get values correctly. begin_time is date 100%.

So, how can I write a script to get the difference between two dates and write it to another integer?

Upvotes: 1

Views: 1807

Answers (1)

Joe - Check out my books
Joe - Check out my books

Reputation: 16923

If you look closely, the script language from the linked question is in groovy but it's not supported anymore. What we use nowadays (2021) is called painless.

The main point here is that the ctx._source attributes are the original JSON -- meaning the dates will be strings or integers (depending on the format) and not java.util.Date or any other data type that you could call .getDate() on. This means we'll have to parse the value first.

So, assuming your begin_time is of the format yyyy/MM/dd, you can do the following:

POST myindex/_update_by_query
{
  "query": {
    "match_all": {}
  },
  "script": {
    "source": """
      DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd");
      LocalDate begin_date = LocalDate.parse(ctx._source.begin_time, dtf);
      
      ctx._source.work_time = begin_date.getYear()
    """
  }
}

BTW the _update_by_query script context (what's accessible and what's not) is documented here and working with datetime in painless is nicely documented here.

Upvotes: 3

Related Questions