from google.cloud import bigquery
# 设置外部数据源的连接信息
project_id = 'project_id'
dataset_id = 'dataset_id'
table_id = 'table_id'
bucket_name = 'bucket_name'
accessKeyId = 'accessKeyId'
secretAccessKey = 'secretAccessKey'
# 创建外部数据源连接客户端
client = bigquery.Client(project=project_id)
# 创建外部数据源表配置
external_config = bigquery.ExternalConfig("CSV")
external_config.source_uris = ["gs://{}/{}".format(bucket_name, table_id)]
external_config.options.skip_leading_rows = 1
external_config.options.field_delimiter = ","
external_config.options.quote_character = '"'
external_config.options.allow_quoted_newlines = True
external_config.options.allow_jagged_rows = True
external_config.options.max_bad_records = 100
# 授权AWS S3访问
external_config.options.aws_access_key_id = accessKeyId
external_config.options.aws_secret_access_key = secretAccessKey
# 创建BigQuery外部数据源表
table_ref = client.dataset(dataset_id).table(table_id)
table_def = bigquery.Table(table_ref, schema=None)
table_def.external_data_configuration = external_config
table = client.create_table(table_def)
# 查看外部数据源表结果
query_job = client.query("""
SELECT * FROM `{}.{}.{}`
""".format(project_id, dataset_id, table_id))
# 输出查询结果
for row in query_job:
print(row)
上一篇:Bigquery外部表元数据
下一篇:BigQuery外连接