google-bigquery - 如何更改 BigQuery 重复记录的列类型

标签 google-bigquery

我正在尝试将重复记录的 col 类型从 STRING 更改为 TIMESTAMP。这里有一些来自 BQ 文档的建议 ( manually-changing-schemas )。但是,我对每条推荐的建议都遇到了问题。

这是一个示例架构:

{
  '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 表示形式(如我们所期望的那样,带有 map 和字典)。

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

BigQuery does not support maps or dictionaries in JSON. For example, "product_categories": {"my_product": 40.0} is not valid, but "product_categories": {"column1": "my_product" , "column2": 40.0} is valid.

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

如有任何建议,我们将不胜感激!

最佳答案

以下答案基于:REPEATED RECORD BigQuery StandardSQL 中的类型表示为类型 ARRAY<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;

enter image description here enter image description here

然后下面的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;

enter image description here

关于google-bigquery - 如何更改 BigQuery 重复记录的列类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55485264/

相关文章:

google-bigquery - Google Big Query 中的加权排名/综合得分

sql - 谷歌 BigQuery : Using TABLE_QUERY if project_id contains a hyphen "-"

google-analytics - Google Analytics-BigQuery

google-bigquery - 避免在bigquery中重复

google-bigquery - 我在 BigQuery 上有每日表格。如何查询 "newest"之一?

google-bigquery - 使用窗口函数将 Google Data Studio 连接到 BigQuery 时出现问题

sql - 使用带有多个输出列的 SELECT IN 更新表

python - 如何使用 pandas read_gbq 防止 SQL 注入(inject)

google-bigquery - BigQuery 脚本: running a SQL query based on each row included in a table column

cron - 如何在 crontab 中运行 BQ 命令