How to calculate difference between min and max with Flux?

Hello,
New to InfluxDB, I’m switching from MySql to influxDB 2.0
I’m so converting my mySQL queries to Flux.

I’m trying to calculate the difference between min and max of a range.

Here is what I tried:

datamin = from(bucket: "grafana")
  |> range(start: v.timeRangeStart, stop: v.timeRangeStop)
  |> filter(fn: (r) => r["_measurement"] == "history")
  |> filter(fn: (r) => r["_field"] == "value")
  |> min()
  |> aggregateWindow(every: 1s, fn: unique, createEmpty: false)
datamax = from(bucket: "grafana")
  |> range(start: v.timeRangeStart, stop: v.timeRangeStop)
  |> filter(fn: (r) => r["_measurement"] == "history")
  |> filter(fn: (r) => r["_field"] == "value")
  |> max()
  |> aggregateWindow(every: 1s, fn: unique, createEmpty: false)

Both independently are giving the correct values. Now I just want to show the difference but I don’t find the correct syntax. Below is the schematic idea of what I like to do

(datamin-datamax)
  |> yield()

Please help me for the correct syntax. Or maybe there is a more direct way to get this ?..
Thanks !

Hello @Heyjay,
Welcome!! Yes this is a common question. Learning Flux and Annotated CSV takes some adjustment, but once the flip switches it’s a lot easier.

data = from(bucket: "my-bucket")
  |> range(start: v.timeRangeStart, stop: v.timeRangeStop)
  |> filter(fn: (r) => r["_measurement"] == "cpu")
  |> filter(fn: (r) => r["_field"] == "usage_system")
  |> filter(fn: (r) => r["cpu"] == "cpu-total")

min = data
  |> min()

max = data
  |> max()

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

You can use a join() to subtract the two results. I join on all of the columns that are the same across the two tables to remove redundant columns.

1 Like

@Anaisdg thank you so much for the trick. This will help me a lot!

1 Like

@Heyjay,
Absolutely. Please let me know if you have any more questions :slight_smile: