Convert watches elasticsearch output to json with groovy Ask Question

alerting

(Hedi Chahed) #1

I want to convert payload.hits.hits to json in elasticsearch watcher output. I found as a solution groovy transform script :slight_smile:

PUT _watcher/watch/error_alert
{
"trigger": {
  "schedule": {
  "interval": "1m"
}
},
"input": {
"search": {
  "request": {
    "body": {
      "query": {
        "bool": {
          "must": [
            {
              "query_string": {
                "default_field": "message",
                "query": "ERROR"
              }
            },
            {
              "range": {
                "@timestamp": {
                  "gte": "now-1m",
                  "lte": "now"
                }
              }
            }
          ]
        }
      }
    }
  }
}
},
"condition": {
  "compare": {
    "ctx.payload.hits.total": {
      "gt": 0
  }
 }
 },
"transform" : {
    "script" : "return [ body:  groovy.json.JsonOutput.toJson(ctx.payload.hits.hits)]"
},
"actions": {
"some_webhook": {
  "webhook": {
    "method": "POST",
    "host": "*.*.*.*",
    "port": 4000,
    "path": "/sms",
    "headers": {
      "Content-Type": "application/json"
    },
    "body": "message: {{ctx.payload.body}}"
  }
}
}
}

This request returns this exception:

 "type": "general_script_exception",
"reason": "failed to compile script [ScriptException[compile error]; nested: IllegalArgumentException[Variable [body] is not defined.];]"

I use:
Elasticsearch 5.3.0
Kibana 5.0.2


(Alexander Reelsen) #2

Hey,

you are using invalid JSON with the body field. Also, you cannot use groovy to create JSON. The solution here is to use the mustache {{toJson}} directive

Hope this helps!

--Alex


(system) #3

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