Skip to main content
 首页 » 编程设计

python之BigQuery Python API : Preserve null fields during extract_table job

2024年12月31日9wayfarer

我有以下代码:

job_config = bigquery.ExtractJobConfig() 
job_config.compression = bigquery.Compression.GZIP 
job_config.destination_format = ( 
    bigquery.DestinationFormat.NEWLINE_DELIMITED_JSON) 
 
destination_uri = 'gs://{}/{}'.format(bucket_name, gcs_filename) 
 
extract_job = client.extract_table( 
    table, 
    destination_uri, 
    job_config=job_config, 
    location='US')  # API request 
extract_job.result()  # Waits for job to complete. 

(请注意,我正在其他地方获取我的表对象。)

这有效,并将请求的表作为换行分隔的 JSON 转储到 GCS 中。但是,表中的某些列可以为空,其中一些包含空值。为了我们所有数据的一致性,我想在 json 结果中保留空值。有什么办法可以做到这一点而不必使用 avro?

此处的帖子:Big Query table extract in JSON, preserve nulls? ... 建议实际查询表。我不认为这对我来说是一个选择,因为我正在提取的表每个包含数百万行。我正在查看的一个包含近 1 亿行,数据量超过 25GB。但我一直无法找到一种方法来设置提取作业以保留空值。

请您参考如下方法:

我认为最好的方法是先使用查询作业。

  1. 您已从某处提取表并运行查询作业
  2. 以不带标题的 CSV 格式运行提取

有代码可以做到这一点

job_config = bigquery.QueryJobConfig() 
gcs_filename = 'file_with_nulls*.json.gzip' 
 
table_ref = client.dataset(dataset_id).table('my_null_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 TO_JSON_STRING(t) AS json from `project.dataset.table` as t ;""", 
    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") 

完成后 - 您可以删除在步骤 1 中创建的临时表。 如果您快速完成,成本将非常低(每月 1TB 的存储空间为 20 美元 - 因此即使 1 小时的 25GB 空间也将为 20/30/24 = 3 美分)