Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save renshuki/d022cbdf0e587501fb6ce696e949ea26 to your computer and use it in GitHub Desktop.

Select an option

Save renshuki/d022cbdf0e587501fb6ce696e949ea26 to your computer and use it in GitHub Desktop.
Elasticsearch Watcher example using "Percentile Ranks"

This watcher trigger an alert when less than 80% of page responses are under 500ms. (Time range not present in the sample below and need to be added )

Index sample

POST latency/_doc
{
  "response_time": 100
}

Watcher

{
  "trigger": {
    "schedule": {
      "interval": "1m"
    }
  },
  "input": {
    "search": {
      "request": {
        "search_type": "query_then_fetch",
        "indices": [
          "latency"
        ],
        "types": [],
        "body": {
          "size": 0,
          "aggs": {
            "load_time_ranks": {
              "percentile_ranks": {
                "field": "response_time",
                "values": [
                  500
                ]
              }
            }
          }
        }
      }
    }
  },
  "condition": {
    "script": {
      "source": "if (ctx.payload.aggregations.load_time_ranks.values[\"500.0\"] < 80) { return true; } return false;",
      "lang": "painless"
    }
  },
  "actions": {
    "logging_1": {
      "logging": {
        "level": "info",
        "text": "Watch [{{ctx.metadata.name}}] has exceeded the threshold"
      }
    }
  },
  "transform": {
    "script": {
      "source": "HashMap result = new HashMap(); result.result = ctx.payload.aggregations.load_time_ranks.values[0]; return result;",
      "lang": "painless"
    }
  }
}
@sfenman
Copy link
Copy Markdown

sfenman commented Oct 6, 2020

Really nice example, helped me a lot thanks. I am still struggling with how I will intergate a timerange filter like :

"filter": [ { "range": { "@timestamp": { "gte": "now-3m" } } }]

Any help would be appreciated.

@imbel
Copy link
Copy Markdown

imbel commented Apr 13, 2021

For anyone coming across this, I have a date range filter working using a similar watcher. Based on the above example, this snippet should work, changing the timestamp field and ranges as needed:

"body": {
    "size": 0,
    "aggs": {
        "load_time_ranks": {
            "percentile_ranks": {
                "field": "response_time",
                "values": [
                    500
                ]
            }
        },
        "range": {
            "date_range": {
                "field": "@timestamp",
                "ranges": [
                    {
                        "from": "now-4h",
                        "to": "now"
                    }
                ]
            }
        }
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment