Get aggregate function by condition in field value

Hello!
I have a query like this:

getSummaryMetrics = (aggregateFunction, field) => from(bucket: "blabla")
  |> range(start: 0)
  |> filter(fn: (r) =>
    r["_field"] == field and
    )
  |> aggregateFunction()
  |> group(columns: ["..."])
  |> pivot(rowKey:["...."], columnKey: ["_field"], valueColumn: "_value")

getSummaryMetrics(aggregateFunction: min, field: "min")
getSummaryMetrics(aggregateFunction: max, field: "max")

The bottom line is that I filter by field and select aggregation for this. I think this is a little dirty solution… Is there any solution for create condition “inside” query for get necessary aggregation function? Something like that:

|> if r._field == "max" then max() 

Perhaps need to create Map with structure fieldName : aggregation function



I also have a problem that when there is a need to call a function with parameters:

getSummaryMetricsQuantile = (quantileFunction, field) => from(bucket: "blabla")
  |> range(start: 0)
  |> filter(fn: (r) =>
    r["_field"] == field and
    )
  |> quantileFunction()

getSummaryMetricsQuantile(quantileFunction: quantile(q: 0.5), field: "percentiles50")

Unfortunately cannot call quantileFunction() with pass quantile(q: 0.5).

Thanks in advance for any help and tips!

Hello @Amerousful,
Yes you can use conditional query logic like:

import "array"
data = from(bucket: "airsensor")
  |> range(start: -40d)
  |> filter(fn: (r) => r["_measurement"] == "airSensors")
  |> filter(fn: (r) => r["_field"] == "co")
  |> filter(fn: (r) => r["sensor_id"] == "TLM0100")
  |> map(fn: (r) => ({ r with _field: "max"}))

getSummaryMetrics = (tables=<-, myfield) => {

result = if myfield == "max" then  
  tables |> filter(fn: (r) => r["_field"] == myfield) |> max() 
  else if myfield == "min" then 
  tables |> filter(fn: (r) => r["_field"] == myfield) |> min() 
  else tables

  return  result
} 

data 
// |> yield(name: "before")
|> getSummaryMetrics(myfield: "max")

Does that help?

1 Like

@Amerousful unfortunately I don’t think you can pass in functions like that. Would be really cool though. I encourage you to submit a feature request!

1 Like

Hello @Anaisdg !
Ok, I will try it. Seems pretty) Thank you very much!