Rename error - How to know if column exists to rename

Hello,

I would like to rename column after my query, the extract of my query works well if all the columns exist.

Depending the time range selection, it can be possible that one or more field don’t exist.
When a field does not exist I got the error message

runtime error @23:8-23:43: rename: rename error: column “HCHC” doesn’t exist

Is it possible to do rename only if the column exists ?
I do not find syntax to do it

Thanks in advance

max =
    data()
        |> aggregateWindow(every: 1d, fn: max, createEmpty: false)
        //|> fill(value: 0.0)
        |> pivot(rowKey:["_time"], columnKey: ["_measurement"], valueColumn: "_value")
        |> rename(columns: {HCHC: "HCHC_Max"})
        |> rename(columns: {HCHP: "HCHP_Max"})
        |> rename(columns: {BBRHCJB: "BBRHCJB_Max"})
        |> rename(columns: {BBRHCJW: "BBRHCJW_Max"})
        |> rename(columns: {BBRHCJR: "BBRHCJR_Max"})
        |> rename(columns: {BBRHPJB: "BBRHPJB_Max"})
        |> rename(columns: {BBRHPJW: "BBRHPJW_Max"})
        |> rename(columns: {BBRHPJR: "BBRHPJR_Max"})    
join(tables: {min: min, max: max}, on: ["_time"])
|> drop(columns: ["_field_max","_field_min","_start_max","_start_min","_stop_max","_stop_min"])
  

@Franck_Bellot rather than using the columns parameter in rename(), try using the fn parameter to functionally rename each column:

max =
    data()
        |> aggregateWindow(every: 1d, fn: max, createEmpty: false)
        //|> fill(value: 0.0)
        |> pivot(rowKey: ["_time"], columnKey: ["_measurement"], valueColumn: "_value")
        |> rename(
            fn: (column) => {
                columnRegex = /HCHC|HCHP|BBRHCJB|BBRHCJW|BBRHCJR|BBRHPJB|BBRHPJW|BBRHPJR/
                columnName = if column =~ columnRegex then "${column}_Max" else column

                return columnName
            },
        )

join(tables: {min: min, max: max}, on: ["_time"])
    |> drop(
        columns: [
            "_field_max",
            "_field_min",
            "_start_max",
            "_start_min",
            "_stop_max",
            "_stop_min",
        ],
    )

This will only attempt to rename the columns to do exist and match the regular expression in the fn parameter.

Thanks a lot @scott, it’s helping me a lot