Khaaz
Khaaz

Reputation: 11

InfluxDB 2.0 - How to merge and sum 2 separate buckets stream in one with Flux

Context

I work in an application with influxDB and I am facing a use case I don't know how to solve.
I am using influxDB 2 and flux for the queries.

Use case

To simplify my use case, I'll take an example with bees.

I want to measure the evolution of the bee population accross time.
I measure 2 populations of bees in 2 separate buckets (bucket A for bee A and bucket B for bee B).
So I want to find a query that merges these 2 buckets to get the current population of bees at any time.
Using 2 buckets is mandatory in my use case. What I want is just a way to "combine" the result when I query.

The results should be sorted based on the timestamps

Examples

The query on the Bee A and the Bee B buckets returns the values in the first 2 lines. The objective is to create the Total line.

Example 1:
In case the measurements are always A, B, A, B; the result must be as

Populations
Bee A 10 12 5 22
Bee B 20 16 19 36
Total 10 30 32 28 21 24 41 58

Example 2:
In case the measurements are A, B, A, A, A, B; the result must be as

Populations
Bee A 10 12 5 22
Bee B 20 16 19 36
Total 10 30 32 25 42 38 41 58

Code

I tried using union but I couldn't get it to work as it kept 2 separates tables instead of one.

bucket1 = from(bucket: "beeA")
  |> range(start: 0)
  |> filter(fn: (r) => r["_measurement"] == "population")
  |> filter(fn: (r) => r["_field"] == "pop")
  |> sort(columns: ["_time"])

bucket2 = from(bucket: "beeB")
  |> range(start: 0)
  |> filter(fn: (r) => r["_measurement"] == "population")
  |> filter(fn: (r) => r["_field"] == "pop")
  |> sort(columns: ["_time"])

union(tables: [bucket1, bucket2])

Upvotes: 1

Views: 4193

Answers (1)

Nitesh
Nitesh

Reputation: 19

you Can try by removing, |> sort(columns: ["_time"]). Also check for |> range(start: 0). You may give different time range and atlast check the selected time range where you have the data.

Upvotes: 0

Related Questions