A Flux query for InfluxDB to generate average electricity usage per hour by weekday
After further learning with Flux and thinking about how to extract what I wanted from it (in my other post), I finally managed to figure out how to generate average hourly electricity consumption by weekday using only a Flux query.
Assumptions:
The data is already regularly timed. e.g. every 30 minutes (which is what I download from my energy provider). If not, you would need to add something like aggregateWindow(every: 1h, fn: sum) into your query before the pivot to make it so.
This query does all the processing in realtime, meaning that it has to be crunched every time it loads. On my Raspberry Pi InfluxDB instance, it takes about 10 seconds to do 60 days of data. You might want to push it to the bottom of your dashboard so that Grafana only loads it if you scroll down that far.
I’m still learning the best ways to write queries with Flux, so there might be a tidier way of doing things.
Source data
Given the electricity usage data structure like this…
_time
usage_amount
2024-01-01T10:00:00.000Z
0.13
2024-01-01T10:30:00.000Z
0.32
2024-01-01T11:00:00.000Z
0.18
… etc
Output data
The script below will turn it into this…
timeofday
sun
mon
tue
wed
thu
fri
sat
00:00
0.0
0.11
0.0
0.0
0.0
0.0
0.0
00:30
0.1
0.30
0.1
0.2
0.1
0.2
0.1
01:00
0.0
0.14
0.0
0.0
0.0
0.0
0.0
… etc
The query
Displaying the data
To display the generated data in a Grafana visualisation, I’m using a bar chart, because that will accept an arbitrary string value for the x-axis. It would be nice to be able to display it as lines rather than bars, but it’s a good start.
I hope this has been helpful. Thanks for reading. :-)