How to use Grafana variables efficiently in Flux Queries

Grafana v9.5.1 . Influxdb 2.71, Ubuntu 20

How to use Grafana variables efficiently in Flux Queries in a time series panel with a variable to toggle between hostnames in the queries.

The base query is straight from the Influxdb explorer to retrieve server data.
from(bucket: “servermonitoring1”)
|> range(start: v.timeRangeStart, stop: v.timeRangeStop)
|> filter(fn: (r) => r[“_measurement”] == “win_proc”)
|> filter(fn: (r) => r[“_field”] == “Working_Set”)
|> filter(fn: (r) => r[“host”] == “WIN-4DI0Q3AMP8N”)
|> filter(fn: (r) => r[“instance”] == “_Total”)
|> aggregateWindow(every: v.windowPeriod, fn: mean, createEmpty: false)
|> yield(name: “mean”)

I modified to use a grafana variable for hostname.
from(bucket: “servermonitoring1”)
|> range(start: v.timeRangeStart, stop: v.timeRangeStop)
|> filter(fn: (r) => r[“_measurement”] == “win_proc”)
|> filter(fn: (r) => r[“_field”] == “Working_Set”)
|> filter(fn: (r) => contains(value: r[“host”], set: ${hostnamev:json}))
|> filter(fn: (r) => r[“instance”] == “_Total”)
|> aggregateWindow(every: v.windowPeriod, fn: mean, createEmpty: false)
|> yield(name: “mean”)

Grafana variable ‘hostnamev’ and its query
import “influxdata/influxdb/schema”
schema.tagValues(bucket: “servermonitoring1”, tag: “host”)

When the base query with hard coded hostname at a time range setting of 1 day runs in about 1 sec.

The second query with using a variable for contains() and hostname takes 120 seconds!

As you increase the time range this get exponentially longer to where its not useful.

Is there a more time efficient means to accomplish using grafana variables in flux queries?

Welcome @onezandzeroz

I noticed your query used this…

instead of something like this:

  |> filter(fn: (r) => r["host"] == "${hostnamev}")

My typical variable query is:

import "influxdata/influxdb/schema"
schema.tagValues(
    bucket: "your-bucket",
    tag: "tag-which-you-want-as-a-variable"
)

Does changing to the above make any difference in the speed?

That works great. I suspected the contains() was a time intense function but not familiar enough in this environment for a better solution.

THANKS!

1 Like