Using conditions in watcher

Hi All,

I am trying to add conditions in a watcher.
If the value of the ctx.payload.value is less than 100, it should print a particular message "Within the limit". And if not than it should print another message "Limit exceeded".
I am trying the below snippet inside the Transform section, but it is showing compilation error. Could anyone please help on this?

"transform": {
"script": {
if (ctx.payload.total < 100)
{
return "Within limit"
}
else
{
return "Out of limit"
}
return ctx.payload;
""",
"lang": "painless"
}
}

You can try ctx.payload.hits.total.value for referring total number of hits in your search results.

Exactly as @sai_kiran1 says... It really depends on what is executed before in order to tell where to set the condition.
If you have a search input, it's likely you'll need to check the ctx.payload.hits.total.
Also keep in mind the transform section (at Watcher root level) is executed after the condition.

In case you need help, I would suggest sharing the Watcher content AND the Watcher execution result (without the transform), so we can see the actual response from the input(s).

Hi @Luca_Belluccini ,

PF the current watcher below.
We want to show if (ctx.payload.total > 100 ) , print "limit exceeded".
Else print "within limit".

{
"trigger" : {
"schedule" : {
"interval" : "2m"
}
},
"input": {
"http": {
"request": {
"scheme": "https",
"host": "####",
"port": 9243,
"method": "get",
"path": "_cat/indices",
"params": {
"format": "yaml",
"human": "true",
"bytes": "mb"
},
"headers": {},
"auth": {
"basic": {
"username": "elastic",
"password": "***"
}
}
}
}
},
"condition": {
"script": {
"source": "return true;",
"lang": "painless"
}
},
"actions": {
"email_administrator": {
"transform": {
"script": {
"source": """
ctx.payload.total = (ctx.payload.data.stream().collect(Collectors.summarizingDouble(e -> Double.parseDouble(e['store.size']))).sum)/1024;
return ctx.payload;
""",
"lang": "painless"
}
},
"email": {
"profile": "standard",
"to": [
"myemail@abc.com"
],
"subject": "Index-wise data",
"body": {
"html": """

Index-wise data


{{#ctx.payload.data}} {{/ctx.payload.data}}
IndexName StoreSize
{{index}} {{store.size}} MB
TOTAL STORE SIZE {{ctx.payload.total}} GB

"""
}
}
}
}
}

In the transform:

ctx.payload.total = (ctx.payload.data.stream().collect(Collectors.summarizingDouble(e -> Double.parseDouble(e['store.size']))).sum)/1024;
ctx.payload.message = ctx.payload.total > 100 ? "Limit exceeded" : "Within the limit";
return ctx.payload;

In the email payload you can use {{ctx.payload.message}}.

1 Like

Thanks @Luca_Belluccini !

Working perfectly for me.

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