ElasticSearch Get Time in Groovy Script

北战南征 提交于 2019-12-22 08:39:54

问题


My application is using this script for boosting more recent items in the index:

(5 / ((3.16*pow(10,-11)) * abs(time() - doc[\'date\'].date.getMillis()) + 0.2)) + 1.0

It's written in MVEL, but as of 1.3, MVEL is deprecated for Groovy. The script throws this error now:

GroovyScriptExecutionException[MissingMethodException[No signature of method: Script4.time() is applicable for argument types: () values: []\nPossible solutions: find(), dump(), find(groovy.lang.Closure), use([Ljava.lang.Object;), is(java.lang.Object), with(groovy.lang.Closure)]]

This sounds to me like the function for getting a millisecond timestamp is different in Groovy. I tried System.currentTimeMillis(), but it gave another error saying it didn't support imports.

So how can I fix the time() function to work with Groovy?


回答1:


As you already have discovered, you need to rewrite your script in Groovy instead of MVEL. Instead of time you need to use DateTime.now().getMillis(). Here's an example of how you use it: http://writequit.org/org/es/index.html#time-in-groovy-script




回答2:


I didn't find out how to get the time within the script, but it seems you can add variables to the query that are available within the script. Here's the resulting JSON.

"function_score": {
    "query": /*...*/,
    "functions": [
        {
            "filter": {
                "exists": {
                    "field": "date"
                }
            },
            "script_score": {
                "params": {
                    "now": 1409001061000
                },
                "script": "(5 / ((3.16*pow(10,-11)) * abs(now - doc['date'].date.getMillis()) + 0.2)) + 1.0"
            }
        }
    ],
}

And my application generates the timestamp (in this case 1409001061000).



来源:https://stackoverflow.com/questions/25492558/elasticsearch-get-time-in-groovy-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!