首页 > 解决方案 > 使用 python 将 BigQuery 表数据导出到具有 where 子句的 Google Cloud Storage

问题描述

我想将表数据从 BigQuery 导出到 Google Cloud Storage。问题是,我需要从 date1 到 date2 的数据,而不是整个表数据。

extract_job = client.extract_table(
    table_ref,
    destination_uri,
    # Location must match that of the source table.
    location='US')  # API request
extract_job.result()  

这是我在谷歌云帮助中找到的。没有使用 where 子句添加查询或限制数据的空间。

标签: pythongoogle-bigquerygoogle-cloud-storage

解决方案


不幸的是,这将是两步过程。首先,您需要构建结果表和导出结果之后。从成本的角度来看,影响应该是最小的 - 您将为临时表使用的存储付费,但成本为每月每 GB 0.02 美元 - 因此,如果您设法在 1 小时内完成任务 - 成本将为每 GB 0.000027 美元

job_config = bigquery.QueryJobConfig()
gcs_filename = 'file_*.gzip'

table_ref = client.dataset(dataset_id).table('my_temp_table')
job_config.destination = table_ref

job_config.write_disposition = bigquery.WriteDisposition.WRITE_TRUNCATE

# Start the query, passing in the extra configuration.
query_job = client.query(
    """#standardSql
    select * from `project.dataset.table` where <your_condition> ;""",
    location='US',
    job_config=job_config)

while not query_job.done():
    time.sleep(1)

#check if table successfully written
print("query completed")
job_config = bigquery.ExtractJobConfig()
job_config.compression = bigquery.Compression.GZIP
job_config.destination_format = (
    bigquery.DestinationFormat.CSV)
job_config.print_header = False

destination_uri = 'gs://{}/{}'.format(bucket_name, gcs_filename)

extract_job = client.extract_table(
    table_ref,
    destination_uri,
    job_config=job_config,
    location='US')  # API request
extract_job.result()
print("extract completed")

推荐阅读