How to externalise painless scripts and call it

hi
I have looked into the few examples, of painless script
https://www.elastic.co/guide/en/elasticsearch/painless/current/painless-execute-api.html
A current example shown is

POST /_scripts/painless/_execute
{
  "script": {
    "source": "params.count / params.total",
    "params": {
      "count": 100.0,
      "total": 1000.0
    }
  }
}

But all the examples show "inline" script of 1 or 2 lines, but we got a complex logic and wanted to externalise the painless script, so that I can pass parameters into the script and get return value (a typical function call concept)

the one I'm looking forward is something like

POST /_scripts/painless/_execute
{
  "script": {
    "name": "my_external_script(count,total)",
    "params": {
      "count": 100.0,
      "total": 1000.0
    }
  }
}

Scripts can be stored in Elasticsearch using the Scripts API, giving the script an id that can then be later used to reference it. For example

to store the script

POST _scripts/calculate-avg
{
  "script": {
    "lang": "painless",
    "source": "params.count / params.total"
  }
}

Then, to use

POST /_scripts/painless/_execute
{
  "script": {
    "id": "calculate-avg",
    "params": {
      "count": 100.0,
      "total": 1000.0
    }
  }
}

You may also be interested in checking out the Painless lab in Kibana, to help in writing more complex Painless scripts

1 Like

perfect. thank mate

1 Like

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.