Query using conditional logic
If you’re just getting started with Flux queries, check out the following:
- for a conceptual overview of Flux and parts of a Flux query.
- Execute queries to discover a variety of ways to run your queries.
Conditional expression syntax
Conditional expressions are most useful in the following contexts:
- When defining variables.
- When using functions that operate on a single row at a time ( filter(), , reduce() ).
Flux evaluates statements in order and stops evaluating once a condition matches.
if r._value > 95.0000001 and r._value <= 100.0 then
"critical"
else if r._value > 85.0000001 and r._value <= 95.0 then
"warning"
else if r._value > 70.0000001 and r._value <= 85.0 then
"high"
else
"normal"
When r._value
is 96, the output is “critical” and the remaining conditions are not evaluated.
Examples
The following example sets the overdue
variable based on the dueDate
variable’s relation to now()
.
The following example uses an example metric
dashboard variable to change how the query filters data. metric
has three possible values:
- Memory
- CPU
- Disk
|> range(start: -1h)
|> filter(
fn: (r) => if v.metric == "Memory" then
r._measurement == "mem" and r._field == "used_percent"
else if v.metric == "CPU" then
r._measurement == "cpu" and r._field == "usage_user"
r._measurement == "disk" and r._field == "used_percent"
else
r._measurement != "",
)
from(bucket: "example-bucket")
|> range(start: -5m)
|> filter(fn: (r) => r._measurement == "mem" and r._field == "used_percent")
|> map(
fn: (r) => ({
// Retain all existing columns in the mapped row
r with
// Set the level column value based on the _value column
level: if r._value >= 95.0000001 and r._value <= 100.0 then
"critical"
else if r._value >= 85.0000001 and r._value <= 95.0 then
"warning"
else if r._value >= 70.0000001 and r._value <= 85.0 then
"high"
else
"normal",
The following example uses the and reduce() functions to count the number of records in every five minute window that exceed a defined threshold.
threshold = 65.0
from(bucket: "example-bucket")
|> range(start: -1h)
|> filter(fn: (r) => r._measurement == "mem" and r._field == "used_percent")
// Aggregate data into 5 minute windows using a custom reduce() function
|> aggregateWindow(
every: 5m,
// Use a custom function in the fn parameter.
// The aggregateWindow fn parameter requires 'column' and 'tables' parameters.
fn: (column, tables=<-) => tables
|> reduce(
identity: {above_threshold_count: 0.0},
fn: (r, accumulator) => ({
// Conditionally increment above_threshold_count if
// r.value exceeds the threshold
above_threshold_count: if r._value >= threshold then
accumulator.above_threshold_count + 1.0
else
accumulator.above_threshold_count + 0.0,
}),
),
)