Defaulting to a zero output?


I have a query that returns the total power consumed in the current day:

import "date"
starttime = date.sub(d:2h, from: today())
from(bucket: "hassincontainer")
  |> range(start: starttime, stop: date.truncate(t: now(), unit: 1m))
  |> filter(fn: (r) => r["_measurement"] == "kWh")
  |> filter(fn: (r) => r["_field"] == "value")
  |> filter(fn: (r) => r["entity_id"] == "dishwasher_pro_energy")
  |> aggregateWindow(every: 1h, fn: unique)
  |> difference()
  |> sum()

The problem is, often the query returns no results (as there isnt any data for the current day). How do I default the returned value to zero in that case? I have tried using map() and if exists but no joy, as those only work if there is data.


Hi @tejasitraj,
As a query relies on a non-empty result. You could try something like this:

import "array"

total = array.from(rows: [{_value: 0.0}])

data = from(bucket: "generators")
    |> range(start: v.timeRangeStart, stop: v.timeRangeStop)
    |> filter(fn: (r) => r._measurement == "genData")
    |> filter(fn: (r) => r._field == "fuel")
    |> group()    
    |> sum(column: "_value")

union(tables: [total, data])
|> group() 
|> sum()
1 Like