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

3.4k views Asked by At

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: ","))
2

There are 2 answers

0
Jonathan Sternberg On BEST ANSWER

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: ""}
  })
1
Pilot Alpal On

Your original attempt was almost fine.

This way it should split the column:

import "strings"
data
  |> map (fn:(r) => ({
  r with
  names_1: strings.split(v: r.name, t: ",")[0],
  names_2: strings.split(v: r.name, t: ",")[1]
  }))