Atmesh Mishra
Atmesh Mishra

Reputation: 549

InfluxDB Query to fetch count of distinct values for Grafana

I have a collector which collects three fields from a log file and saves it to influxDB in following format:

FeildA   FeildB   FeildC
-------     --------    --------
A            00          123
B            02          100
A            00          13
A            00          123

I want to plot graph in Grafana such that I get count of occurrence of "A" and "B" (FeildA)
IMP: FeildA can have multiple values, not known before-hand. Hence writing query with "where" clause is not an option.

Upvotes: 0

Views: 4612

Answers (1)

Yuri Lachin
Yuri Lachin

Reputation: 1500

If FeildA is only defined as field in measurement schema you can use regexp in "where" clause and these queries might work for you:

```

SELECT COUNT(FeildA) FROM "logdata" WHERE $timeFilter and FeildA::field =~ /^A$/
SELECT COUNT(FeildA) FROM "logdata" WHERE $timeFilter and FeildA::field =~ /^A$/
SELECT COUNT(FeildA) FROM "logdata" WHERE $timeFilter and FeildA =~ /^(A|B)$/

```

If the number of expected distinct values of FeildA (cardinality) is resonable the real solution would be to make FeildA a "Tag" instead of "Field". Then you can use "group by tag" in query. For example, query:

```

SELECT COUNT(FeildA) FROM "logdata" WHERE $timeFilter AND "FeildA" =~ /^(A|B|C|D)$/ GROUP BY time(1m), FeildA fill(null)

```

will give counts of occurrence of "A","B","C","D". But this require changes in collector. FeildA can be both a "tag" and a "field" in influxdb but it is better when names are different to avoid collision and simplify syntax in queries.

Upvotes: 1

Related Questions