How to use carriage return in a script template with a runtime mapping field?

Here is an example that illustrates the problem we are having with "mustache" and the carriage return.

In our script template, we need :

  • a runtime mapping field : to compute a result (with a big script in our real case)
  • conditional template : to build search criteria according to params existence (many criteria in our real case)

We use Elasticsearch 7.16 and kibana debug console to make our tests.

We create this script template with this request :

POST _scripts/test
{
  "script": {
    "lang": "mustache",
    "source": """{
      "runtime_mappings": {
        "result": {
          "type": "long",
          "script": {
            "source": "emit({{#foo}}{{foo}}{{/foo}}{{^foo}}0{{/foo}})"
          }
        }
      }
      {{#foo}}
        ,"fields": [
          "result"
        ]
      {{/foo}}
    }"""
  }
}

Here are 2 examples of requests that show how this script works:

Request 1 : Search request with param
Return the computed field "result" with the "foo" parameter value (12345)

GET _search/template
{
  "id": "test",
  "params": {
    "foo": 12345
  }
}

Request 2 : Search request without param
Don't return computed field "result".

GET _search/template
{
  "id": "test"
}

Like i said before, in our real case we have a very big "painless" script in the computed field.
For more readability, we therefore wrote this script on several lines and that's when a problem appears.

An error happened when we declare:

"source": "
  emit({{#foo}}{{foo}}{{/foo}}{{^foo}}0{{/foo}})
"

instead of:

"source": "emit({{#foo}}{{foo}}{{/foo}}{{^foo}}0{{/foo}})"

Due to the JSON specifications, we cannot use carriage returns otherwise we get the following error:
Illegal unquoted character ((CTRL-CHAR, code 10)): has to be escaped using backslash to be included in string value

We also cannot use the notation with """ because it will conflict with the one used to declare the source of the script template.

Is there a trick to set the computed field script to multiple lines in Kibana debug console ?

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