Why is Flux query taking time than same InfluxQL query

Hello All,
Currently I am in process of Migrating the Influx database from version 1.8.x to 2.6 and hence started using Flux. I have converted the following InfluxQL query to flux query but I have noticed that my Flux query is taking way to much time to fetch the same data.
InfluxQL query SELECT (last("Km")-first("Km"))/1000 AS "Km" FROM "Measurement_one" WHERE "some_Id" =~ /^(6470747bee7f5256c1dec136|648c1e2514a8ec65eb5f785c)$/ AND "Km" > 0 GROUP BY time(1h)
Flux Query `
data = () => from(bucket: “my_bucket”)
|> range(start: v.timeRangeStart, stop: v.timeRangeStop)
|> filter(fn: (r) => r[“_measurement”] == “Measurement_One”)
|> filter(fn: (r) => r[“_field”] == “Km”)
|> filter(fn: (r) => r[“some_id”] =~ /^(6470747bee7f5256c1dec136|648c1e2514a8ec65eb5f785c)$/)
first = data()|> aggregateWindow(every: 1h, fn: first, createEmpty: false)
last = data() |> aggregateWindow(every: 1h, fn: last, createEmpty: false)

union(tables: [first, last])
|> pivot(rowKey:[“_time”], columnKey: [“_field”], valueColumn: “_value”)
|> difference(columns: [“Km”])
|> map(fn: (r) => ({ r with _value: r.Km/1000.0 }))
|> keep(columns: [“_time”, “_value”, “deviceName”])
|> yield()`
Is the reason of bad performance of flux query is because of the way I am making the query? if yes can someone point to what am I doing wrong?

Hi @Belly_Musketier

If the “Km” value is always increasing, then is last(“Km”) - first(“Km”) mathematically equivalent to the difference between the minimum and maximum values over the given time period? If yes, then the spread() function should do the trick.

data = () => from(bucket: “my_bucket”)
 |> range(start: v.timeRangeStart, stop: v.timeRangeStop)
 |> filter(fn: (r) => r[“_measurement”] == “Measurement_One”)
 |> filter(fn: (r) => r[“_field”] == “Km”)
 |> filter(fn: (r) => r[“some_id”] =~ /^(6470747bee7f5256c1dec136|648c1e2514a8ec65eb5f785c)$/)
 |> map(fn: (r) => ({ r with _value: r.Km/1000.0 }))
 |> spread()
 |> yield()