Got internal error in transform script

Hi, all

I am a newbie for painless.
I wrote a watcher, snippet of the transform bellow:

"transform":{
    "script": "string hosts=''; for (item in ctx.payload.aggregations.whichHost.buckets.entrySet()) {hosts = hosts + ', ' + item.getKey();} return ['hosts' : ''];"
},

After run the simulate, I got a error:

Watcher: An internal server error occurred

I want to foreach the buckets, and then concatenate the key of the item.

How? :sob:

I resolved this problem by followed script:

String host=''; for (int i = 0; i < ctx.payload.aggregations.whichHost.buckets.length; i++) {host = host + ', ' + ctx.payload.aggregations.whichHost.buckets[i].key;} return ['error_count' : ctx.payload.aggregations.whichHost.buckets.length, 'hosts' : host]

But is there another way more pretty?

hey,

if this a transformation issue, or do you just want to display the hosts in your action. If so, you could just use the {{#join}} feature of mustache to join an array of data together.

See https://www.elastic.co/guide/en/elasticsearch/reference/5.6/search-template.html#_concatenating_array_of_values

I have created an example if you dont want to use mustache, but stay with lambdas, check out execute watch

POST _xpack/watcher/watch/_execute
{
  "watch" : {
    "trigger" : {
      "schedule" : {
        "interval" : "10m"
      }
    },
    "input" : { "simple" : {
      "foo" : [
        { "field" : "value1" },
        { "field" : "value2" },
        { "field" : "value3" },
        { "field" : "value4" },
        { "field" : "value5" }
        ]
    }},
    "actions" : {
      "logging" : {
        "transform" : {
          "script":" return ['foo': ctx.payload.foo.stream().map(item -> item.field).collect(Collectors.toList()).join(' ,') ]"
        },
        "logging" : {
          "text" : "{{ctx.payload}}"
        }
      }
    }
  }
}

--Alex

Yeah, thank you very much.
The code is perfect :grin:

Hi,

I try to use the {{#join}} in a template in the action section, but I got a syntax error. The snippet of the code below:

"actions": {
  "notify_slack": {
      "throttle_period_in_millis": 30000,
      "template": {
        "id": "tpl_slack_notify",
        "params": {
          "hosts": "{{ctx.payload.aggregations.whichHost.bucket"
        }
      }
  }
}

And I saw the manual for action in watcher, there is no anyone section talk about which use the template in the action snippet.

Could I use the template in the action section? Is there a sample for it?

Thank you

I do not see any usage of join here? Please also paste the full watch for easier understanding.

Thank you so much!

--Alex

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