【问题标题】:Autocreate tables in Bigquery for multiple CSV files在 Bigquery 中为多个 CSV 文件自动创建表
【发布时间】:2021-08-08 15:16:26
【问题描述】:

每当使用 python 中的云功能将文件上传到存储桶中时,我想在 Bigquery 中自动生成表。

例如,如果将 sample1.csv 文件上传到存储桶,那么将在 Bigquery 中创建一个 sample1 表。 如何使用 Python 使用云功能自动化它我尝试使用以下代码但能够生成 1 个表并且所有数据都附加到该表中,如何继续

def hello_gcs(event, context):
    from google.cloud import bigquery
    # Construct a BigQuery client object.
    client = bigquery.Client()

    # TODO(developer): Set table_id to the ID of the table to create.
    table_id = "test_project.test_dataset.test_Table"

    job_config = bigquery.LoadJobConfig(
    autodetect=True,
    skip_leading_rows=1,
    # The source format defaults to CSV, so the line below is optional.
    source_format=bigquery.SourceFormat.CSV,
    )
    uri = "gs://test_bucket/*.csv"

    load_job = client.load_table_from_uri(
    uri, table_id, job_config=job_config
    )  # Make an API request.

    load_job.result()  # Waits for the job to complete.

    destination_table = client.get_table(table_id)  # Make an API request.
    print("Processing file: {file['name']}.")

【问题讨论】:

    标签: python-3.x google-bigquery google-cloud-functions


    【解决方案1】:

    听起来你需要做三件事:

    1. 从您收到的通知事件中提取 CSV 文件/对象的名称以触发您的函数。

    2. 更新示例代码中的table_id,以根据您在第一步中提取的文件名设置表名。

    3. 更新示例代码中的uri 以仅使用单个文件作为输入。如所写,您的示例尝试将数据从 所有 GCS 中匹配的 CSV 对象加载到表中。

    【讨论】:

    • @Daemon 您能否分享一下您正在加载 uri 中仅单个文件作为输出。像这样:# TODO(developer): 将 table_id 设置为要创建的表的 ID。 table_id = event['name'] job_config = bigquery.LoadJobConfig( autodetect=True, skip_leading_rows=1, # 源格式默认为CSV,所以下面一行是可选的。source_format=bigquery.SourceFormat.CSV, ) uri = "gs ://test_bucket/event['name'].csv"
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-21
    相关资源
    最近更新 更多