Truncating results in watcher action

alerting

(Andrey Utis) #1

Hello,

I have a query that returns really long strings sometimes. I want to truncate the string to a max length of let's say 200 characters. I'm calling a webhook that has a parameter like this:

"message" : "{{#ctx.payload.hits.hits}}{{_source.text}} - {{_source.exception_message}}

{{/ctx.payload.hits.hits}}"

Is there any easy way to truncate _source.text and _source.exception_message fields when generating this parameter?

Thanks,
Andrey


(Alexander Reelsen) #2

Hey Andrey,

mustache itself has no means of truncating, but you can use a script transform in your action to achieve this, see this example

POST _xpack/watcher/watch/_execute
{
  "watch" : {
    "trigger" : { "schedule" : { "interval" : "10s" } },
    "input" : {
      "simple" : {
        "data" : [
          {"a": "short"}, {"a" : "loooooooooongloooooooooongloooooooooongloooooooooongloooooooooongloooooooooongloooooooooongloooooooooongloooooooooongloooooooooong"}
        ]
      }
    },
    "actions" : {
      "log_error" : {
        "transform" : {
          "script" : {
            "inline" : "ctx.payload.data.collect(e -> e.a.substring(0, (int) Math.min(e.a.length(), 10)))"
          }
        },
        "logging" : {
          "text" : "Found {{ctx.payload.hits.total}} errors in the logs"
        }
      }
    }
  }
}

--Alex


(Andrey Utis) #3

Alex,

That looks great, but doesn't seem to work in my version.. it's returning this error:

  "type": "script_exception",
  "reason": "failed to compile script [ScriptException[Failed to compile inline script [ctx.payload.data.collect(e -> e.text.substring(0, (int) Math.min(e.text.length(), 300)))] using lang [groovy]]; nested: ScriptException[failed to compile groovy script]; nested: MultipleCompilationErrorsException[startup failed:\n39b79deb278b37ddf0f53ca43268d9df949f9b2a: 1: unexpected token: -> @ line 1, column 28.\n   ctx.payload.data.collect(e -> e.text.substring(0, (int) Math.min(e.text.length(), 300)))\n                              ^\n\n1 error\n];] with lang [ctx.payload.data.collect(e -> e.text.substring(0, (int) Math.min(e.text.length(), 300)))] of type [groovy]"

We haven't upgraded to 5 yet. Is there a way to do this with the previous version?

Thanks,
Andrey


(Alexander Reelsen) #4

Hey,

do'h, my bad. I was thinking in terms of Elasticsearch 5 using the new and fresh scripting language. You can do something similar in groovy, along the lines

x.data.collect { x -> x.a.substring(0, Math.min(x.a.length(), 10)) }

not tested this time and top of my more and more rusty groovy skills.

--Alex


(system) #5

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