Groovy to Painless; get current date time

I am trying to convert this Groovy script to Painless:

(0.08 / ((3.16*pow(10,-11.5)) * abs(DateTime.now().getMillis() - doc['created'].date.getMillis()) + 0.05)) + 1.0

So far this is what I have, but I keep getting the error message "Variable [DateTime] is not defined". How do I get the current DateTime in Painless?

(0.08 / ((3.16*Math.pow(10,-11.5)) * Math.abs(DateTime.now().getMillis() - doc['created'].date.getMillis()) + 0.05)) + 1.0

1 Like

See this previous thread which explains what to do (passing in now through a param):

I ended up using System.currentTimeMillis(). Will this give me the same problem? And in that case, can you please give me an example of how you would solve it?

        {
          "script_score": {
            "script": "(0.08 / ((3.16*Math.pow(10,-11.5)) * Math.abs(System.currentTimeMillis() - doc['created'].date.getMillis()) + 0.05)) + 1.0"
          }
        }
3 Likes

The problem there is that script will be executed on multiple nodes (where each shard of the index resides), each of which could have a different current time. The way to have a global and consistent time is to pass it in within the request.

{
  "script_score": {
    "script": {
      "inline": "(0.08 / ((3.16*Math.pow(10,-11.5)) * Math.abs(params['time'] - doc['created'].date.getMillis()) + 0.05)) + 1.0",
      "params": {
        "time": 123456789 /* time set in the request, in millis */
      }
    }
  }
}   

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.