【问题标题】:How do I use BigQuery DML to transform some fields of a struct nested within an array, within a struct, within an array?如何使用 BigQuery DML 转换嵌套在数组、结构内、数组内的结构的某些字段?
【发布时间】:2022-01-22 12:09:59
【问题描述】:

我认为这是Update values in struct arrays in BigQuery 中问题的更复杂版本。

我正在尝试更新结构中的一些字段,其中结构非常嵌套。我无法创建 SQL 来执行此操作。这是我的表架构:

CREATE TABLE `my_dataset.test_data_for_so`
(
  date DATE,
  hits ARRAY<STRUCT<search STRUCT<query STRING, other_column STRING>, metadata ARRAY<STRUCT<key STRING, value STRING>>>>
);

这是我创建表后 BigQuery GUI 中架构的样子:

这是我插入的数据:

INSERT INTO `my_dataset.test_data_for_so` (date, hits)
VALUES (
  CAST('2021-01-01' AS date),
  [
    STRUCT(
      STRUCT<query STRING, other_column STRING>('foo bar', 'foo bar'),
      [
        STRUCT<key STRING, value STRING>('foo bar', 'foo bar')
      ]
    )
  ]
)

我的目标是转换“search.query”和“metadata.value”字段。例如,将它们大写,使行中的所有其他列(以及所有其他结构字段)保持不变。

我正在寻找一种解决方案,涉及手动指定 SQL 中的每一列,或者最好是我只能提及我想在 SQL 中转换的列/字段,而忽略所有其他列/字段。这是一个最小的例子。我在生产中处理的表有数百个列和字段。

例如,当以这种方式转换时,该行将从:

[
  {
    "date": "2021-01-01",
    "hits": [
      {
        "search": {
          "query": "foo bar",
          "other_column": "foo bar"
        },
        "metadata": [
          {
            "key": "foo bar",
            "value": "foo bar"
          }
        ]
      }
    ]
  }
]

到:

[
  {
    "date": "2021-01-01",
    "hits": [
      {
        "search": {
          "query": "FOO BAR",
          "other_column": "foo bar"
        },
        "metadata": [
          {
            "key": "foo bar",
            "value": "FOO BAR"
          }
        ]
      }
    ]
  }
]

【问题讨论】:

    标签: sql google-bigquery


    【解决方案1】:

    最好是我只能提及我想在 SQL 中转换的列/字段...

    使用下面的方法 - 它完全符合您的要求 - 只有那些要更新的字段正在使用中,所有其他(数十或数百 ...)都按原样保留

    update your_table
    set hits = array(
      select as struct *
        replace(
          (select as struct * replace (upper(query) as query) from unnest([search])) as search, 
          array(select as struct * replace(upper(value) as value) from unnest(metadata)) as metadata
        )
      from unnest(hits)
    )
    where true;            
    

    如果应用于您问题中的样本数据 - 结果是

    【讨论】:

    • 就 BigQuery 而言,您是这里社区的重要资源。谢谢你帮我解决这个问题!
    猜你喜欢
    • 2015-04-13
    • 2018-10-19
    • 2016-09-10
    • 2022-01-22
    • 2021-02-09
    • 2016-08-13
    • 1970-01-01
    • 1970-01-01
    • 2015-08-14
    相关资源
    最近更新 更多