将Elasticsearch的painless脚本存储到Elasticsearch中

在AWS的Amazon Elasticsearch Service中,之前不支持调用保存在文件中的脚本,但在5.5版本以上已经新增了对脚本存储的支持。这样一来,可以简化每次查询时在脚本中的写法,直接进行调用。

使用此功能,可以将Elasticsearch的painless脚本保存到Elasticsearch端,并在搜索时通过ID进行调用。

我们将使用之前在Elasticsearch中注册的生日来计算当前年龄的脚本进行保存。

脚本的储存

腳本的存儲位置為_script/{id}。

POST _scripts/script-age
{
  "script": {
    "lang": "painless",
    "code": "Date n = new Date(); Date b = new Date(doc['birthday'].value); DateFormat f = new SimpleDateFormat('yyyy-MM-dd'); return Period.between(LocalDate.parse(f.format(b)), LocalDate.parse(f.format(n))).getYears();"
  }
}

由于在_script_之后指定的值被视为_id_,所以_id_的管理应由使用者自行进行。

使用保存的脚本进行搜索。

如果要使用保存的脚本,则在脚本中指定存储的id。

GET {index}/{type}/_search
{
  "script_fields": {
     "age": {
       "script": {
         "stored": "script-age"
       }
     }
   }
}

脚本的引用

如果要引用已保存的脚本,请使用GET调用_script。

GET _scripts/script-age

删掉脚本

如果要删除脚本,可以使用 “DELETE” 调用 “_script”。

DELETE _scripts/script-age

通过将直接列在查询中的脚本与查询分开,可以简化搜索查询的描述,并使脚本独立管理。

本家手册
https://www.elastic.co/guide/zh/elasticsearch/reference/5.5/modules-scripting-using.html#modules-scripting-stored-scripts

希望能够获取保存的脚本清单,但在版本5.5中似乎没有相应的API支持。