向键添加新字段

默认情况下,RDI 将字段添加到目标数据库中的 hashJSON 对象中,这些字段与源表的列匹配。 下面的示例展示了如何使用 add_field 转换向目标数据添加额外字段。

添加单个字段

第一个示例向数据中添加了一个字段。 source 部分选择了 chinook 数据库的 customer 表(这里的可选 db 值对应于 config.yaml 中定义的 sources..connection.database 值)。

transform部分,add_field转换会向对象添加一个名为localphone的额外字段,该字段是通过使用JMESPath函数regex_replace()phone字段中移除国家和区号创建的。如果您更喜欢使用SQL表达式创建新字段,您也可以将language指定为sql

output 部分指定了 hash 作为写入目标的 data_type,这覆盖了在 config.yaml 中定义的 target_data_type 的默认设置。此外,output.with.key 部分指定了一个自定义的键格式,形式为 cust:,其中 id 部分由 uuid() 函数生成。

完整的示例如下所示:

source:
  db: chinook
  table: customer
transform:
  - uses: add_field
    with:
      expression: regex_replace(phone, '\+[0-9]+ (\([0-9]+\) )?', '')
      field: localphone
      language: jmespath
output:
  - uses: redis.write
    with:
      connection: target
      data_type: hash
      key:
        expression: concat(['cust:', uuid()])
        language: jmespath

如果你使用redis-cli查询默认转换生成的目数据,你会看到类似以下内容:

 1) "customerid"
 2) "27"
 3) "firstname"
 4) "Patrick"
 5) "lastname"
 6) "Gray"
.
.
17) "phone"
18) "+1 (520) 622-4200"
.
.

使用上面的作业文件,数据还包括新的localphone字段:

 1) "customerid"
 2) "27"
 3) "firstname"
 4) "Patrick"
 5) "lastname"
 6) "Gray"
 .
 .
23) "localphone"
24) "622-4200"

添加多个字段

add_field 转换也可以同时添加多个字段,如果你在 fields 子部分中指定它们。下面的示例向 track 对象添加了两个字段。第一个新字段 seconds 是使用 SQL 表达式从 milliseconds 字段计算轨道持续时间(以秒为单位)创建的。第二个新字段 composerlist 使用 split() 函数添加一个 JSON 数组,以在 composer 字符串字段中包含逗号的地方进行分割。

source:
  db: chinook
  table: track
transform:
  - uses: add_field
    with:
      fields:
        - expression: floor(milliseconds / 1000)
          field: seconds
          language: sql
        - expression: split(composer)
          field: composerlist
          language: jmespath
output:
  - uses: redis.write
    with:
      connection: target
      data_type: json
      key:
        expression: concat(['track:', trackid])
        language: jmespath

您可以查询目标数据库以查看JSON对象中的新字段:

> JSON.GET track:1 $

"[{\"trackid\":1,\"name\":\"For Those About To Rock (We Salute You)\",\"albumid\":1,\"mediatypeid\":1,\"genreid\":1,\"composer\":\"Angus Young, Malcolm Young, Brian Johnson\",\"milliseconds\":343719,\"bytes\":11170334,\"unitprice\":\"0.99\",\"seconds\":343,\"composerlist\":[\"Angus Young\",\" Malcolm Young\",\" Brian Johnson\"]}]"

使用add_fieldremove_field

你可以使用add_fieldremove_field 转换一起来完全替换源中的字段。例如, 如果你添加了一个新的fullname字段,你可能不再需要单独的firstnamelastname字段。你可以通过如下作业文件来移除它们:

source:
  db: chinook
  table: customer
transform:
  - uses: add_field
    with:
      expression: concat(firstname, ' ', lastname)
      field: fullname
      language: sql
  - uses: remove_field
    with:
      fields:
        - field: firstname
        - field: lastname
output:
  - uses: redis.write
    with:
      connection: target
      data_type: hash
      key:
        expression: concat(['cust:', customerid])
        language: jmespath
RATE THIS PAGE
Back to top ↑