BigQuery - 在 Python 中创建外部表

doc*_*ata 4 python-2.7 google-bigquery

我找不到任何有关如何使用 Python 在 BigQuery 中创建外部表的文档。我想在不使用自动检测但传递架构的情况下创建表。有人知道该怎么做吗?谢谢你!

Vic*_*GGl 8

如果您不想使用命令行工具 和os.system(command),您可以使用 Python BigQuery 库从外部源创建一个 BigQuery 表,代码如下:

from google.cloud import bigquery

client = bigquery.Client()
#Define your schema
schemafield_col1 = bigquery.schema.SchemaField("string_col","STRING")
schemafield_col2 = bigquery.schema.SchemaField("int_col","INTEGER")



dataset_ref = client.dataset('<your-dataset>')
table_ref = bigquery.TableReference(dataset_ref, '<your-table-name>')
table = bigquery.Table(table_ref, [schemafield_col1,schemafield_col2])

external_config = bigquery.ExternalConfig('CSV')
source_uris = ['<url-to-your-external-source>'] #i.e for a csv file in a Cloud Storage bucket 
                                              #it would be something like "gs://<your-bucket>/<your-csv-file>"
external_config.source_uris = source_uris
table.external_data_configuration = external_config

client.create_table(table)
Run Code Online (Sandbox Code Playgroud)

这是API 参考的链接

这里是有关该类ExternalConfig及其属性更多信息。