在BigQuery文件中加载列名称加载python

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

我正在尝试从Google的BigQuery Python库(google-cloud-bigquery==1.3.0)上传文件

使用documentation

dataset_ref = client.dataset(dataset_id)
table_ref = dataset_ref.table(table_id)
job_config = bigquery.LoadJobConfig()
job_config.source_format = bigquery.SourceFormat.CSV
job_config.skip_leading_rows = 1
job_config.autodetect = True

with open(filename, 'rb') as source_file:
    job = client.load_table_from_file(
        source_file,
        table_ref,
        location='US',
        job_config=job_config)

job.result()

这成功创建了表并插入数据,在本例中是一个简单的字符串类型的单列文件。

但是,它设置以下列名称:string_field_0

有没有办法可以自定义这些列名?

python google-cloud-platform google-bigquery
2个回答
0
投票

因为你只有一列只有字符串,即使你在代码中使用job_config.skip_leading_rows = 1,BigQuery也无法计算出标题/列名称,即它不知道行和标题之间的区别。如果你有一个第二列,比如说是一个整数,那么BigQuery就可以保留列名,因为它现在可以区分它们。

作为一种解决方法,要么不使用auto_detect并手动指定架构(毕竟它只是一列),要么加载它然后用一些SQL命中它并重命名列。


1
投票

您应该能够为加载作业添加架构。例如

job_config.schema = [SchemaField('columnName', 'STRING', mode='nullable')]
© www.soinside.com 2019 - 2024. All rights reserved.