Link Search Menu Expand Document Documentation Menu

创建或更新存储脚本

1.0 版引入

创建或更新存储脚本或搜索模板。

有关 Painless 脚本的更多信息,请参阅

路径参数

参数 数据类型 描述
script-id 字符串 存储脚本或搜索模板 ID。在整个集群中必须是唯一的。必填。

查询参数

所有参数都是可选的。

参数 数据类型 描述
context 字符串 脚本或搜索模板运行的上下文。为防止错误,API 会立即在此上下文中编译脚本或模板。
cluster_manager_timeout 时间 等待连接到集群管理器的时间。默认为 30 秒。
timeout 时间 等待响应的时间段。如果在超时值之前未收到响应,则请求失败并返回错误。默认为 30 秒。

请求正文字段

字段 数据类型 描述
script(脚本) 对象 定义脚本或搜索模板、其参数及其语言。请参阅下面的脚本对象

脚本对象

字段 数据类型 描述
lang 字符串 脚本语言。必填。
source 字符串或对象 必填。

对于脚本,一个包含脚本内容的字符串。

对于搜索模板,一个定义搜索模板的对象。支持与 搜索 API 请求正文相同的参数。搜索模板还支持 Mustache 变量。

请求示例

以下示例请求使用名为 books 的索引和以下文档

POST _bulk
{"index":{"_index":"books","_id":1}}
{"name":"book1","author":"Faustine","ratings":[4,3,5]}
{"index":{"_index":"books","_id":2}}
{"name":"book2","author":"Amit","ratings":[5,5,5]}
{"index":{"_index":"books","_id":3}}
{"name":"book3","author":"Gilroy","ratings":[2,1,5]}

创建 Painless 脚本

以下请求创建 Painless 脚本 my-first-script。它计算每本书的评分总和并在输出中显示总和。

PUT _scripts/my-first-script
{
  "script": {
      "lang": "painless",
      "source": """
          int total = 0;
          for (int i = 0; i < doc['ratings'].length; ++i) {
            total += doc['ratings'][i];
          }
          return total;
        """
  }
}

前面的示例使用 OpenSearch Dashboards 中开发工具控制台的语法。您也可以使用 curl 请求。

以下 curl 请求与之前的 Dashboards 控制台示例等效

curl -XPUT "http://opensearch:9200/_scripts/my-first-script" -H 'Content-Type: application/json' -d'
{
  "script": {
      "lang": "painless",
      "source": "\n          int total = 0;\n          for (int i = 0; i < doc['\''ratings'\''].length; ++i) {\n            total += doc['\''ratings'\''][i];\n          }\n          return total;\n        "
  }
}'

有关运行脚本的信息,请参阅执行 Painless 存储脚本

创建或更新带参数的存储脚本

Painless 脚本支持 params 将变量传递给脚本。

以下请求创建 Painless 脚本 multiplier-script。该请求计算每本书的评分总和,将总和乘以 multiplier 参数,并在输出中显示结果。

PUT _scripts/multiplier-script
{
  "script": {
      "lang": "painless",
      "source": """
          int total = 0;
          for (int i = 0; i < doc['ratings'].length; ++i) {
            total += doc['ratings'][i];
          }
          return total * params['multiplier'];
        """
  }
}

示例响应

PUT _scripts/my-first-script 请求返回以下字段

{
  "acknowledged" : true
}

要确定脚本是否成功创建,请使用获取存储脚本 API,并将脚本名称作为 script 路径参数传递。

剩余 350 字符

有问题?

想贡献?