Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

elasticsearch-painless - Manipulate date

I am trying to manipulate date in elasticsearch's scripting language painless. Specifically, I am trying to add 4 hours, which is 14,400 seconds.

{
  "script_fields": {
    "new_date_field": {
      "script": {
        "inline": "doc['date_field'] + 14400"
      }
    }
  }
}

This throws Cannot apply [+] operation to types [org.elasticsearch.index.fielddata.ScriptDocValues.Longs] and [java.lang.Integer].

Thanks

like image 959
Eran H. Avatar asked Aug 24 '17 14:08

Eran H.


1 Answers

The solution was to use .value

{
  "script_fields": {
    "new_date_field": {
      "script": {
        "inline": "doc['date_field'].value + 14400"
      }
    }
  }
}

However, I actually wanted to use it for reindexing, where the format is a bit different. Here is my version for manipulating time in the _reindex api

POST _reindex
{
  "source": {
    "index": "some_index_v1"
  },
  "dest": {
    "index": "some_index_v2"
  },
  "script": {
    "inline": "def sf = new SimpleDateFormat(\"yyyy-MM-dd'T'HH:mm:ss\"); def dt = sf.parse(ctx._source.date_field); def calendar = sf.getCalendar(); calendar.setTime(dt); def instant = calendar.toInstant(); def localDateTime = LocalDateTime.ofInstant(instant, ZoneOffset.UTC); ctx._source.date_field = localDateTime.plusHours(4);"
  }
}

Here is the inline script in a readable version

def sf = new SimpleDateFormat(\"yyyy-MM-dd'T'HH:mm:ss\");
def dt = sf.parse(ctx._source.date_field);
def calendar = sf.getCalendar();
calendar.setTime(dt);
def instant = calendar.toInstant();
def localDateTime = LocalDateTime.ofInstant(instant, ZoneOffset.UTC);
ctx._source.date_field = localDateTime.plusHours(4);

Here is the list of functions supported by painless, it was painful.

like image 64
Eran H. Avatar answered Oct 02 '22 15:10

Eran H.