OpenSearch provides several ways to run a script; the following sections show how to run a script by passing script information in the request body of a request.
Example request
The following request runs the stored script that was created in Create or update stored script. The script sums the ratings for each book and displays the sum in the total_ratings
field in the output.
The script’s target is the
books
index.The
"match_all": {}
property value is an empty object indicating to process each document in the index.
copy
Example response
The GET books/_search
request returns the following fields:
{
"took" : 2,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 3,
"relation" : "eq"
},
"max_score" : 1.0,
"hits" : [
{
"_index" : "books",
"_id" : "1",
"_score" : 1.0,
"fields" : {
"total_ratings" : [
12
]
}
},
{
"_index" : "books",
"_id" : "2",
"_score" : 1.0,
"fields" : {
"total_ratings" : [
15
]
}
},
{
"_index" : "books",
"_id" : "3",
"_score" : 1.0,
"fields" : {
"total_ratings" : [
8
]
}
]
}
}
Response fields
Hits object
Document object
To pass different parameters to the script each time when running a query, define params
in script_fields
.
The following request runs the stored script that was created in . The script sums the ratings for each book, multiplies the summed value by the parameter, and displays the result in the output.
The
"match_all": {}
property value is an empty object, indicating that it processes each document in the index.The
total_ratings
field value is the result of themultiplier-script
execution. See Creating or updating a stored script with parameters."multiplier": 2
in theparams
field is a variable passed to the stored scriptmultiplier-script
:
copy
Example response
{
"took" : 12,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 3,
"relation" : "eq"
},
"max_score" : 1.0,
"hits" : [
{
"_index" : "books",
"_type" : "_doc",
"_id" : "3",
"_score" : 1.0,
"fields" : {
"total_ratings" : [
16
]
}
},
{
"_index" : "books",
"_type" : "_doc",
"_id" : "2",
"_score" : 1.0,
"fields" : {
"total_ratings" : [
30
]
}
},
{
"_index" : "books",
"_type" : "_doc",
"_id" : "1",
"_score" : 1.0,
"fields" : {
"total_ratings" : [
24
]
}
}
]
}
Sample response
"took" : 90,
"timed_out" : false,
"_shards" : {
"total" : 5,
"successful" : 5,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 3,
"relation" : "eq"
},
"max_score" : null,
"hits" : [
{
"_index" : "books",
"_type" : "_doc",
"_id" : "2",
"_score" : null,
"fields" : {
"total_ratings" : [
30
]
},
"sort" : [
30.0
]
},
{
"_index" : "books",
"_type" : "_doc",
"_id" : "1",
"_score" : null,
"fields" : {
"total_ratings" : [
24
]
},
"sort" : [
24.0
]
},
{
"_index" : "books",
"_type" : "_doc",
"_id" : "3",
"_score" : null,
"fields" : {
"total_ratings" : [
16
]
},
"sort" : [
16.0
]
}
]