Function to perform aggregation on value according to table measurement

Hi everyone!
I have a query like this:

 from(bucket:"bucket1") 
  |> range(start: 0) 
  |> filter(fn: (r) => 
  r._measurement == "Data1"
  or r._measurement == "Data2"
  or r._measurement == "Data3"
  or r._measurement == "Data4")
  |> group(columns: ["_measurement"])
  |> HandleData()

And I want to create a function called HandleData, which will perform aggregation on all the input tables according to the measurement field.

I mean something like this:

HandleData = (tables=<-) =>
 {
    val = if _measurement == "Data4" then average(_value)
    else sum(_value)

    o = {measurement: _measurement , value: val}
    return o
 }                          

I couldn’t find any lead on how to solve this until now, I will highly appreciate any help in solving this matter.

Best Regards,
Shiran.

Hi Shiran,
Probably not what you’re looking for, but if I insert this line protocol:

Data1 foo=1 1642096935
Data1 foo=2 1642096936
Data2 foo=3 1642096935
Data2 foo=4 1642096936

with this query:

data = from(bucket: "test")
  |> range(start: v.timeRangeStart, stop: v.timeRangeStop)
  |> filter(fn: (r) => r["_measurement"] =~ /Data/)
  |> filter(fn: (r) => r["_field"] == "foo")

data1 = data
  |> filter(fn: (r) => r["_measurement"] == "Data1")
  |> mean()

data2 = data
  |> filter(fn: (r) => r["_measurement"] == "Data2")
  |> sum()

union(tables:[data1, data2])
 |> yield()

I get this result:

image

Might give you a way forward…

Thanks,
Tom

@Shiran_Saada To add to @thopewell’s suggestion, your proposed function would look something like this:

HandleData = (tables=<-) => {
    data4 = tables
        |> filter(fn: (r) => r["_measurement"] == "Data4")
        |> mean()
    otherData = tables
        |> filter(fn: (r) => r["_measurement"] != "Data4")
        |> sum()

    return union(tables:[data4, otherData])
}