Execute Painless stored script

Runs a stored script written in the Painless language.

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 GET <index>/_search request.

Request fields

FieldData typeDescription
queryObjectA filter that specifies documents to process.
script_fieldsObjectFields to include in output.
scriptObjectID of the script that produces a value for a field.

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.

  • The total_ratings field value is the result of the my-first-script execution. See Create or update stored script.

  1. GET books/_search
  2. {
  3. "query": {
  4. "match_all": {}
  5. },
  6. "script_fields": {
  7. "total_ratings": {
  8. "script": {
  9. "id": "my-first-script"
  10. }
  11. }
  12. }
  13. }

copy

Example response

The GET books/_search request returns the following fields:

  1. {
  2. "took" : 2,
  3. "timed_out" : false,
  4. "_shards" : {
  5. "total" : 1,
  6. "successful" : 1,
  7. "skipped" : 0,
  8. "failed" : 0
  9. },
  10. "hits" : {
  11. "total" : {
  12. "value" : 3,
  13. "relation" : "eq"
  14. },
  15. "max_score" : 1.0,
  16. "hits" : [
  17. {
  18. "_index" : "books",
  19. "_id" : "1",
  20. "_score" : 1.0,
  21. "fields" : {
  22. "total_ratings" : [
  23. 12
  24. ]
  25. }
  26. },
  27. {
  28. "_index" : "books",
  29. "_id" : "2",
  30. "_score" : 1.0,
  31. "fields" : {
  32. "total_ratings" : [
  33. 15
  34. ]
  35. }
  36. },
  37. {
  38. "_index" : "books",
  39. "_id" : "3",
  40. "_score" : 1.0,
  41. "fields" : {
  42. "total_ratings" : [
  43. 8
  44. ]
  45. }
  46. }
  47. ]
  48. }
  49. }

Response fields

FieldData typeDescription
tookIntegerHow long the operation took in milliseconds.
timed_outBooleanWhether the operation timed out.
_shardsObjectTotal number of shards processed and also the total number of successful, skipped, and not processed.
hitsObjectContains high-level information about the documents processed and an array of hits objects. See Hits object.

Hits object

FieldData typeDescription
totalObjectTotal number of documents processed and their relationship to the match request field.
max_scoreDoubleHighest relevance score returned from all the hits.
hitsArrayInformation about each document that was processed. See Document object.

Document object

FieldData typeDescription
_indexStringIndex that contains the document.
_idStringDocument ID.
_scoreFloatDocument’s relevance score.
fieldsObjectFields and their value returned from the script.