BigQuery 自动检测与手动架构的不同行为

问题描述 投票:0回答:2

我的 Google 存储桶中有一个 CSV 文件。我试图通过 BigQuery 读取此内容,因此我在 CSV 文件上创建一个外部表。此 CSV 文件的第一列的格式为“2022-05-14 08:00:00 Africa/Accra”。

当我使用自动检测架构时,我可以查询该文件,而当我手动定义与自动检测的架构相同的架构时,我收到错误:“无法解析'2022-05-14 08:00:00 Africa/Accra' 作为字段 SMS_DT(位置 0)的 TIMESTAMP,从位置 415 开始,并显示消息“无法识别的时区:非洲/阿克拉”。

这种差异如何合理?我怎样才能手动定义模式并获得成功的结果?

google-bigquery
2个回答
0
投票

由于您想手动定义模式,因此可以使用Python客户端库,您可以在其中定义模式。当您显式指定表的模式时,可以设置

autodetect=False
。您可以尝试以下代码供您参考。

代码:

from google.cloud import bigquery
 
# Construct a BigQuery client object.
client = bigquery.Client()
 
# TODO(developer): Set table_id to the ID of the table to create.
table_id = "project.dataset.tablename"
 
job_config = bigquery.LoadJobConfig(
 
    schema = [
        
        bigquery.SchemaField("E", "DATETIME"),
        bigquery.SchemaField("F", "INTEGER"),
        bigquery.SchemaField("G", "TIMESTAMP")
    ],
    autodetect=False,
    source_format=bigquery.SourceFormat.CSV
)
uri = "gs://bucket/sample.csv"
 
load_job = client.load_table_from_uri(
    uri, table_id, job_config=job_config
)  # Make an API request.
 
load_job.result()  # Waits for the job to complete.
 
destination_table = client.get_table(table_id)
print("Loaded {} rows.".format(destination_table.num_rows))

样本.csv

E,F,G
2021-01-12 23:26:37,986,2022-05-14 08:00:00 Africa/Accra

输出:


0
投票

我认为当 BigQuery 使用自动检测架构加载源文件时与我们手动创建架构并将源文件加载到表中时存在一些细微的区别。

即使我遇到了这个问题,当我尝试从 BigQuery 控制台加载文件时,它加载时没有任何问题,但当我使用相同的架构并尝试通过 Python 客户端加载相同的文件时;它引发了解析错误。

因此,更简单的解决方法是对导致错误的列使用 STRING 数据类型,然后使用 E.g. PARSE_DATETIME/ PARSE_TIMESTAMP 函数解析字符串数据。

https://cloud.google.com/bigquery/docs/reference/standard-sql/datetime_functions#parse_datetime

https://cloud.google.com/bigquery/docs/reference/standard-sql/timestamp_functions#parse_timestamp

SELECT PARSE_TIMESTAMP('%Y-%m-%d %H:%M:%S %Z', '2022-05-14 08:00:00 Africa/Accra')
© www.soinside.com 2019 - 2024. All rights reserved.