Group by a field with FLUX

We are using grafana with flux. We are trying to show a sum of the field ‘peso’ while groping by other field called ‘viaje’.

imagen_2021-10-27_032957

The measurement is like the dummy data of this image, where ‘domain’ is a tag and ‘id’, ‘peso’ and ‘viaje’ are fields.

I tried the following flux code but it does not group by anything.

    from(bucket: "hyperauth/autogen")
      |> range(start: v.timeRangeStart, stop: v.timeRangeStop)
      |> filter(fn: (r) => r._measurement == "metric" and r._field == "peso")
      |> group(columns: ["viaje"])
      |> yield()

Thank you in advance!

Hi. If you want to group by “viaje” you need it to be a tag, not a field.

And then group by “viaje”. And if you want to represent a sum of the field “peso” you also need to apply an aggregation function like |> sum()

And also “id” you should also put it as a tag.

I read here that it was possible to group by a field with FLUX https://github.com/influxdata/influxdb/issues/7200#issuecomment-426055525

Edit:

Hi. If you want to group by “viaje” you need it to be a tag, not a field.

And then group by “viaje”. And if you want to represent a sum of the field “peso” you also need to apply an aggregation function like |> sum()

And also “id” you should also put it as a tag.

“Viaje” and “id” cannot be tags because of their high cardinality.

You can group by fields but you need to get the field as column on the data first using the schema.fieldsAsCols() function

import "influxdata/influxdb/schema"

    from(bucket: "hyperauth/autogen")
      |> range(start: v.timeRangeStart, stop: v.timeRangeStop)
      |> filter(fn: (r) => r._measurement == "metric" and ( r._field == "peso" or r._field == "viaje"))
      |> schema.fieldsAsCols()
      |> group(columns: ["viaje"])
      |> yield()

See schema.fieldsAsCols() function | Flux 0.x Documentation

Hope this helps.

2 Likes

Thank you so much!
@nathaniel in Grafana where do I place the import?

Edit: I am using an older version of FLUX, I used

import "influxdata/influxdb/v1"

v1.fieldsAsCols()

Hi I am using the same above query but i am not able to find the solution.I am not able to group by fields