Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
501 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...