如何更改 BigQuery 重复记录的 col 类型

2024-03-09

我正在尝试更改重复记录的 col 类型STRING to TIMESTAMP。 BQ 文档提供了一些建议(手动更改模式 https://cloud.google.com/bigquery/docs/manually-changing-schemas#changing_a_columns_data_type)。但是,我对每条推荐的建议都遇到了问题。

这是一个示例架构:

{
  'name' => 'id',
  'type' => 'STRING',
  'mode' => 'REQUIRED'
},
{
  'name' => 'name',
  'type' => 'STRING',
  'mode' => 'REQUIRED'
},
// many more fields including nested records and repeated records
{
  'name' => 'locations',
  'type' => 'RECORD',
  'mode' => 'REPEATED',
  'fields' => [
    {
      'name' => 'city',
      'type' => 'STRING',
      'mode' => 'REQUIRED'
    },
    {
      'name' => 'updated_at',
      'type' => 'STRING',   // ** want this as TIMESTAMP **
      'mode' => 'REQUIRED'
    },
  ]
}

使用查询的问题:

我认为我们必须取消重复记录,将字段转换为每个重复记录的时间戳,然后以某种方式重新创建行以插入到新表中。

将表导出为 JSON 时出现问题:

当以 JSON 格式导出表时,它会导出数据的原始 json 表示形式(带有地图和字典,正如我们所期望的那样)。

但是,我们无法将该原始数据导入回 BQ:

BigQuery 不支持 JSON 格式的地图或字典。例如, "product_categories": {"my_product": 40.0} 无效,但是 "product_categories": {"column1": "my_product" , "column2": 40.0} 是 有效的。

https://cloud.google.com/bigquery/docs/loading-data-cloud-storage-json#limitations https://cloud.google.com/bigquery/docs/loading-data-cloud-storage-json#limitations

任何建议将不胜感激!


以下答案是基于此:REPEATED RECORDBigQuery 标准 SQL 中的类型表示为 typeARRAY<STRUCT<f1 f1_type, f2 f2_type ... >>.

这不是我最喜欢的,因为您必须指定完整的列列表。也许有更好的方法。

#standardSQL
-- Build sample data, try to mimic what's in question.
CREATE OR REPLACE TABLE
  <your_dataset>.sample_table AS
SELECT name, 
       array<struct<city string, update_at string>>[("SFO", "2011-1-1"), ("SEA", "2022-2-2")] 
       as locations
FROM UNNEST(['Name1', "Name2", "Name3"]) as name;

然后下面的SQL将转换update_at列入DATE并保存到新表(如果您愿意,也可以保存到同一个表)。

#standardSQL
CREATE OR REPLACE TABLE
  <your_dataset>.output_table AS
SELECT * REPLACE (
   ARRAY(SELECT AS STRUCT * REPLACE(CAST(update_at AS DATE) AS update_at)
         FROM UNNEST(locations)) 
   AS locations 
   )
FROM
  <your_dataset>.sample_table;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何更改 BigQuery 重复记录的 col 类型 的相关文章

随机推荐