Create InfluxQL query with optional filter variables on Library Panel

After much research I have managed to develop this trick to be able to invoke a library panel (for example, table type), where the query uses one or more variables as filters in an optional way.

In this way I can use the same library panel from several dashboards in which I can use a filter for a tag (or several) without having to change the query.

So for example if I have 5 tags that I can search, I can generate a query that can use 1 to 5 variables each filtering by a different tag, so that in a dashboard I can have only 2 of the 5 possible filters defined, or all, or none (and show all the data).

The query would be like this (modify to suit needs):

SELECT …
FROM β€œmeasurement”
WHERE $timeFilter
AND (β€˜${var1:raw}’ =~ /^${var1:raw}$/ OR β€œtag1” =~ /^${var1}$/)
AND (β€˜${var2:raw}’ =~ /^${var2:raw}$/ OR β€œtag2” =~ /^${var2}$/)
AND (β€˜${var3:raw}’ =~ /^${var3:raw}$/ OR β€œtag3” =~ /^${var3}$/)
AND (β€˜${var4:raw}’ =~ /^${var4:raw}$/ OR β€œtag4” =~ /^${var4}$/)
AND (β€˜${var5:raw}’ =~ /^${var5:raw}$/ OR β€œtag5” =~ /^${var5}$/)
GROUP BY …

The operation is as follows. If any of the variables (var1 for example) does not exist, grafana will NOT replace β€˜${var1:raw}’ with its respective value, performing a comparison with a regex that contains THAT unmodified string.

Otherwise, it enters the OR condition in which the tag is already evaluated with the value or values ​​of said variable.

1 Like

Same approach on PostgreSQL query…

WHERE…
AND (
β€˜${var1:raw}’ ~ β€˜${var1:raw}’ – If variable is not defined, this whill be TRUE
OR field = ANY(string_to_array(β€˜${var1:raw}’, β€˜,’))
)

1 Like

After more tests and found mistakes on query I finally found that this query works when:

  1. There is no variables defined (one or more).
  2. There is one or more variables that have no values.
  3. There is one or more variables that have values (and may apply this for filter series)

SELECT …
FROM β€œmeasurement”
WHERE $timeFilter
AND (β€˜${var1:percentencode}’ =~ /${.}/ OR β€˜${var1:percentencode}’ = β€˜β€™ OR β€˜${var1:percentencode}’ = β€˜All’ OR β€œtag1” =~ /^${var1:regex}$/)
AND (β€˜${var2:percentencode}’ =~ /${.
}/ OR β€˜${var2:percentencode}’ = β€˜β€™ OR β€˜${var1:percentencode}’ = β€˜All’ OR β€œtag1” =~ /^${var2:regex}$/)
AND (β€˜${var3:percentencode}’ =~ /${.}/ OR β€˜${var3:percentencode}’ = β€˜β€™ OR β€˜${var3:percentencode}’ = β€˜All’ OR β€œtag1” =~ /^${var3:regex}$/)
AND (β€˜${var4:percentencode}’ =~ /${.
}/ OR β€˜${var4:percentencode}’ = β€˜β€™ OR β€˜${var4:percentencode}’ = β€˜All’ OR β€œtag1” =~ /^${var4:regex}$/)
AND (β€˜${var5:percentencode}’ =~ /${.*}/ OR β€˜${var5:percentencode}’ = β€˜β€™ OR β€˜${var5:percentencode}’ = β€˜All’ OR β€œtag1” =~ /^${var5:regex}$/)