Search code examples
influxdbinfluxdb-2flux-influxdb

How to split a string column in two in Flux (InfluxDB)


I have a column of #datatype string which is called names and contains the following info for each row:

ABV,BVA
BAC,DWA
ZZA,DSW
  ...

My question is how can I split (by the comma ,) this column into two columns with names (names_1 and names_2), such that I will get something like this:

names_1    names_2
ABV        BVA
BAC        DWA
ZZA        DSW
      ...

I tried strings.split() but it only works on an single string. So maybe I need a way to do apply this code to a whole column:

import "strings"

data
  |> map (fn:(r) => strings.split(v: r.names, t: ","))

Solution

  • I think you might be looking for something like this:

    import "experimental/array"
    import "strings"
    
    array.from(rows: [{value: "A,B"}])
      |> map(fn: (r) => {
        parts = strings.split(v: r.value, t: ",")
        return {first: parts[0], second: parts[1]}
      })
    

    The array.from() can be replaced with from() to read data from influxdb. The map function expects a record to be returned. If you have some data that might not have two values after the split, you can also do:

    import "experimental/array"
    import "strings"
    
    array.from(rows: [{value: "A,B"}])
      |> map(fn: (r) => {
        parts = strings.split(v: r.value, t: ",")
        return if length(arr: parts) > 1 then
          {first: parts[0], second: parts[1]}
        else {first: parts[0], second: ""}
      })