here is an example from a dashboard i am actively using
from(bucket: "home_energy")
|> range(start: v.timeRangeStart, stop: v.timeRangeStop)
|> filter(fn: (r) => r._field == "Mains1_W" or r._field == "Mains2_W")
|> pivot(rowKey: ["_time"], columnKey: ["_field"], valueColumn: "_value")
|> map(fn: (r) => ({ r with _value: r.Mains1_W + r.Mains2_W }))
|> keep(columns: ["_value", "_time"])
|> aggregateWindow(every: v.windowPeriod, fn: last, createEmpty: false)
|> rename(columns: {_value: "Total Power Draw"})
in this, i am pulling data from my bucket home_energy
i am getting my two MAINS watts Mains1_W
and Mains2_W
the purpose of this query is to graph total power draw of the house, so i need to add the two measurements together
before i can do this, i need to use the pivot command
|> pivot(rowKey: ["_time"], columnKey: ["_field"], valueColumn: "_value")
you can see more details on pivot here
now i can actually perform the desired math function where i add the two values together
|> map(fn: (r) => ({ r with _value: r.Mains1_W + r.Mains2_W }))
you can see more here
and go down to the area titled ** Transform values in a data stream**
the next line allows me to keep the data i care about, and get rid of the rest
|> keep(columns: ["_value", "_time"])
i need this because i want the _value
and time
data for the graph, but i no longer need the data in the Mains1_W
and Mains2_W
finally i need to control the window size so when i change the time window in grafana the graph will update accordingly. i also want to rename the _value
field to something a little more “user friendly”
|> aggregateWindow(every: v.windowPeriod, fn: last, createEmpty: false)
|> rename(columns: {_value: "Total Power Draw"})