Flux piping intermediate results

Hello all,

My apologies if this has been asked before.

I’m working on some very basic panels on Grafana, using InfluxDB/Flux as data source. I have some experience in programming, but I’m not particularly versed in databases or Flux.

I need to create about a dozen gauges showing the percentages of times I get some results (call them A, B, C) from tests being performed 24/7

The relevant data is arranged as time/result pairs. Say:
t0 : A
t1 : A
t2 : C
t3 : B
.
.
.
tn : result(n)

Conceptually, this is as simple as dividing the count for each category (A, B, C) by the sum of counts for all categories (A+B+C).

From what I can see, the Flux language uses piping all the time, meaning that to get each of the parameters above I would need to run essentially the same query multiple times to get each percentage.

My question is: is it possible to get/store/reuse intermediate values, so I can use a single query? E.g. get the count for each category, store the sum of them, and then divide the count of each by the total?

Thanks!

Hello @Role23,
Absolutely you can do something like:
// Step 1: Query the data
data = from(bucket: “your_bucket”)
|> range(start: -24h) // Adjust time range as needed
|> filter(fn: (r) => r._measurement == “your_measurement”)
|> filter(fn: (r) => r._field == “result”) // Adjust field name if needed
// uncomment yield() function which acts like a print statement
//|> yield(name:“data”)

// Step 2: Get count of each category (A, B, C)
countA = data
|> filter(fn: (r) => r._value == “A”)
|> count()

countB = data
|> filter(fn: (r) => r._value == “B”)
|> count()

countC = data
|> filter(fn: (r) => r._value == “C”)
|> count()

// Step 3: Combine counts into a single table
combinedCounts = union(tables: [countA, countB, countC])
// uncomment yield() function which acts like a print statement
//|> yield(name:“combinedCounts”)

// Step 4: Calculate the total count (A + B + C)
totalCount = combinedCounts
|> sum(column: “_value”)
|> findRecord(fn: (key) => true, idx: 0) // Get the total sum as a constant value

// Step 5: Map each category’s count to its percentage of the total
percentages = combinedCounts
|> map(fn: (r) => ({ r with _value: float(v: r._value) / float(v: totalCount._value) * 100 }))

// Step 6: Output the result
percentages
// uncomment yield() function which acts like a print statement
|> yield(name:“percentatges”)

Hope that helps!