Beginner : How to aggregate the difference between min and max with Flux?

I receive the energy index every seconds and I want to store the energy usage every 1h

I found the solution to do the calculation with join function.
I tried to do a task based on this but ther is an error I cannot find.
Error : “Duration is missing a unit”

Here is the code I have done :

option task = {name: "Energie diff", every: 1h}

data =
  from(bucket: "home_assistant")
  |> range(start: -task.every)
  |> filter(fn: (r) => r["_measurement"] == "kWh")
  |> filter(fn: (r) => r["_field"] == "value")

min = data
  |> min()

max = data
  |> max()

diff = join(tables: {min: min, max: max}, on: ["_start", "_field", "_measurement"], method: "inner")
  |> map(fn: (r) => ({ r with _value: r._value_max - r._value_min }))

diff
    |> aggregateWindow(every: 1h, fn: last, createEmpty: false)
    |> to(bucket: "agregate", org: "private")```

any idea is welcome !
thanks

Hello @usky73,
Welcome!
Does it say what line you’re getting that error for?
I don’t see anything wrong with your script as is right now.
Can you use a yield() statement after each variable and verify that you’re getting results at each step? Thats usually how I debug my scripts.

data =
  from(bucket: "home_assistant")
  |> range(start: -task.every)
  |> filter(fn: (r) => r["_measurement"] == "kWh")
  |> filter(fn: (r) => r["_field"] == "value")
  |> yield(name: "data") 

min = data
  |> min()
  |> yield(name: "min") 

max = data
  |> max()
  |> yield(name: "max") 

diff = join(tables: {min: min, max: max}, on: ["_start", "_field", "_measurement"], method: "inner")
  |> map(fn: (r) => ({ r with _value: r._value_max - r._value_min }))
  |> yield(name: "diff")

diff
    |> aggregateWindow(every: 1h, fn: last, createEmpty: false)
    |> yield(name: "final") 

Id go through and comment out the rest of the yield statements and look at each one separately to make it easier to verify and eliminate the source of the error through process of elimination.

Also keep in mind the to function requires that the output of final contain the following:

1 Like