Search code examples
influxdbinfluxdb-2flux-influxdb

How to create Influxdb alert for deviating from average hourly values?


So I'm trying to find any documentation on more complex Flux queries but after days of searching I'm still lost. I want to be able to calculate average values for each hour of the week and then when new data comes in I want to check if it deviates by x standard deviations for that hour.

Basically I want to have 24x7 array fields each representing the mean/median value for each hour of the week for the last 1 year. Then I want to compare last days values for each hour against these averages and report an error. I do not understand how to calculate these averages. Is there some hidden extensive documentation on Flux?

I don't really need a full solution, just some direction would be nice. Like, are there some utility functions for this in the standard lib or whatever

EDIT: After some reading, it really looks like all I need to do is use the window and aggregateWindow functions but I haven't yet found how exactly


Solution

  • Ok, so, this is what worked for me. Needs some cleaning up but gets the values successfully grouped per hour+weekday and the mean of all the values

    import "date"
    tab1 = from(bucket: "qweqwe")
      |> range(start: v.timeRangeStart, stop: v.timeRangeStop)
      |> filter(fn: (r) => r["_measurement"] == "asdasd")
      |> filter(fn: (r) => r["_field"] == "reach")
      |> aggregateWindow(every: 1h, fn: mean, createEmpty: false)
    
    
    mapped = tab1 
      |> map(fn: (r) => ({ r with wd: string(v: date.weekDay(t: r._time)), h: string(v: date.hour(t: r._time)) }))
      |> map(fn: (r) => ({ r with mapped_time: r.wd + " " + r.h }))
    
    grouped = mapped
      |> group(columns: ["mapped_time"], mode: "by")
      |> mean()
      |> group() 
      |> toInt()
    
      |> yield()