【问题标题】:Exporting BigQuery Table Data to Google Cloud Storage having where clause using python使用 python 将 BigQuery 表数据导出到具有 where 子句的 Google Cloud Storage
【发布时间】:2018-11-20 11:59:45
【问题描述】:
我想将表数据从 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子句没有空间添加查询或限制数据。
【问题讨论】:
标签:
python
google-bigquery
google-cloud-storage
【解决方案1】:
不幸的是,这将是两步过程。
首先,您需要构建结果表和导出结果之后。
从成本的角度来看,影响应该是最小的——你需要为临时表使用的存储付费,但成本是每月每 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")
【解决方案2】:
使用您提供的代码(遵循this doc),您只能将整个表导出到 GCS,而不是查询的结果。
或者,您可以将查询结果download and save 到本地文件并上传到 GCS。或者更简单,将查询结果保存到新的 BigQuery 表中,然后使用您使用的代码将该新表完全导出到 GCS。
【解决方案3】:
解决方案:使用 python 将 BigQuery 数据导出到具有 where 子句的 Google Cloud Storage
from google.cloud import bigquery
from google.cloud import storage
def export_to_gcs():
QUERY = "SELECT * FROM TABLE where CONDITION" # change the table and where condition
bq_client = bigquery.Client()
query_job = bq_client.query(QUERY) # BigQuery API request
rows_df = query_job.result().to_dataframe()
storage_client = storage.Client() # Storage API request
bucket = storage_client.get_bucket(BUCKETNAME) # change the bucket name
blob = bucket.blob('temp/Add_to_Cart.csv')
blob.upload_from_string(rows_df.to_csv(sep=';',index=False,encoding='utf-8'),content_type='application/octet-stream')
return "success"
【解决方案4】:
在原生 BigQuery SQL 中使用“EXPORT DATA OPTIONS”命令从 SQL 查询中导出数据。
使用 python 客户端将 SQL 提交到 BigQuery,BigQuery 将负责其余的工作。
from google.cloud import bigquery
from google.cloud import storage
BQ = bigquery.Client()
CS = storage.Client()
def gcp_export_http(request):
sql = """
EXPORT DATA OPTIONS(uri="gs://gcs-bucket/*",format='PARQUET',
compression='SNAPPY') AS SELECT * FROM
table_name where column_name > colunn_value
"""
query_job = BQ.query(sql)
res = query_job.result()
return res