首页 > 解决方案 > 将 BigQuery 结果导出为 Avro 或 JSON

问题描述

如果有办法将 BigQuery 结果保存为 JSON 或 Avro 格式,请告诉我。

我正在使用以下代码在 BigQuery 表上运行查询。

client = bigquery.Client.from_service_account_json('/Users/gaurang.shah/Downloads/fb3735b731b9.json')

job_config = bigquery.QueryJobConfig()
job_config.priority = bigquery.QueryPriority.BATCH
sql = """
   select * 
    FROM `bigquery-public-data.samples.shakespeare`
    limit 1;
"""
location = 'US'
query_job = client.query(sql, location=location, job_config=job_config)
query_job = client.get_job(query_job.job_id, location=location)  
print(query_job.result())

我正在尝试在不使用GCS的情况下导出 BigQuery 表。这是我认为可以实现这一目标的一种方式。

我认为的另一种方式是使用BQ command line工具。但是不确定它是否对我可以触发多少个查询以及我可以检索多少数据有任何限制。

标签: google-bigquery

解决方案


您需要先运行查询,将结果写入表,然后连接到 BigQuery导出/提取 API,结果/表可以以您想要的格式导出到 GCS。例如,这里是 CSV:

# from google.cloud import bigquery
# client = bigquery.Client()
# bucket_name = 'my-bucket'
project = 'bigquery-public-data'
dataset_id = 'samples'
table_id = 'shakespeare'

destination_uri = 'gs://{}/{}'.format(bucket_name, 'shakespeare.csv')
dataset_ref = client.dataset(dataset_id, project=project)
table_ref = dataset_ref.table(table_id)

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

print('Exported {}:{}.{} to {}'.format(
    project, dataset_id, table_id, destination_uri))

在这里查看更多。


推荐阅读