要通过BigQuery查询云存储桶中的CSV文件,需要将CSV文件导入BigQuery数据集中。以下是一个示例代码,演示如何将CSV文件导入到BigQuery中:
from google.cloud import bigquery
from google.cloud import storage
# 设置Google Cloud项目和存储桶信息
project_id = 'your-project-id'
bucket_name = 'your-bucket-name'
dataset_name = 'your-dataset-name'
table_name = 'your-table-name'
# 创建BigQuery和存储客户端
bigquery_client = bigquery.Client(project=project_id)
storage_client = storage.Client(project=project_id)
# 获取存储桶
bucket = storage_client.get_bucket(bucket_name)
# 获取存储桶中的CSV文件
blobs = bucket.list_blobs()
# 创建BigQuery数据集(如果不存在)
dataset_ref = bigquery_client.dataset(dataset_name)
dataset = bigquery.Dataset(dataset_ref)
dataset = bigquery_client.create_dataset(dataset, exists_ok=True)
# 导入CSV文件到BigQuery表中
for blob in blobs:
if blob.name.endswith('.csv'):
table_ref = bigquery_client.dataset(dataset_name).table(table_name)
job_config = bigquery.LoadJobConfig()
job_config.source_format = bigquery.SourceFormat.CSV
job_config.skip_leading_rows = 1
job_config.autodetect = True
job_config.write_disposition = bigquery.WriteDisposition.WRITE_APPEND
load_job = bigquery_client.load_table_from_uri(
'gs://{}/{}'.format(bucket_name, blob.name),
table_ref,
job_config=job_config
)
load_job.result() # 等待导入作业完成
print('导入文件 {} 到表 {}.{} 成功'.format(blob.name, dataset_name, table_name))
请注意,上述代码假设您已经设置了适当的身份验证凭据,并且安装了google-cloud-bigquery
和google-cloud-storage
Python库。
此代码将遍历存储桶中的所有对象,并将以.csv
结尾的文件导入到BigQuery表中。导入作业的配置为自动检测模式,这意味着BigQuery将尝试根据文件内容推断模式。您还可以根据需要进行其他配置,例如指定模式、字段分隔符等。
完成导入后,您可以使用BigQuery查询语句查询导入的数据。