How can I transform InfluxDB GROUP results based on the different rows in the result tables using Flux

2.1k views Asked by At

I'm trying to perform a transform on the results of a Flux group operation.

I need to derive a value based on the values of individual rows.

Source query:

from('bucket')
|> ... filters, etc
|> group()
|> sort() 

returns data with the following shape:

#group:
  result:
    table | field | value
    ----- | ----- | -----
        0 | "A"   | 1
        0 | "B"   | 2
        0 | "C"   | 3
#group:
  result:
    table | field | value
    ----- | ----- | -----
        1 | "A"   | 4
        1 | "B"   | 5
        1 | "C"   | 6
etc...

What I'm trying to do is, for example, add the values of all the rows in a group to end up with data that looks like:

field | value
----- | -----
"New" | 6
"New" | 15
    

I've tried map but that only appears to give me access to the individual rows, not the table in the group. My first thought was to try to map all the rows into one, flat record after which the map is trivial.

How can I access the table itself? Is that a correct approach?

1

There are 1 answers

0
Byron Ross On

I'm sure this is not optimal, but it works for me at the moment, turns out reduce is more appropriate:

calculate = (r, accumulator) => {
  A = if r._field == "A" then r._value else accumulator.A
  B = if r._field == "B" then r._value else accumulator.B
  C = if r._field == "C" then r._value else accumulator.C
  return A + B + C
}

from('bucket')
  |> ... filters, etc
  |> group()
  |> sort() 
  |> reduce(
    // Define the initial accumulator record
    identity: {
      A: 0.0,
      B: 0.0,
      C: 0.0,
      Output: 0.0,
    },
    fn: (r, accumulator) => ({
      A: if r._field == "A" then r._value else accumulator.A,
      B: if r._field == "B" then r._value else accumulator.B,
      C: if r._field == "C" then r._value else accumulator.C,
      Output: calculateMassFlow(r, accumulator)
    })
  )
  |> map(fn: (r) => ({
    _time: r._time,
    _field: "Name",
    _value: r.Output
  }))
  |> group(columns: ["_field"])