【问题标题】:How to pass multiple delimiter in Python for BigQuery storage using Cloud Function如何使用 Cloud Function 在 Python 中为 BigQuery 存储传递多个分隔符
【发布时间】:2021-10-17 18:50:36
【问题描述】:

我正在尝试将多个 csv 文件加载到 BigQuery 表中。对于某些 csv 文件,分隔符是逗号,对于某些是分号。有什么方法可以在 Job config 中传递多个分隔符。

    job_config = bigquery.LoadJobConfig(
    autodetect=True,
    source_format=bigquery.SourceFormat.CSV,
    field_delimiter=",",
    write_disposition="WRITE_APPEND",
    skip_leading_rows=1,
)

谢谢 丽兹

【问题讨论】:

  • 否,创建 2 个作业或预处理您的文件以使用通用分隔符
  • 这是否意味着我们不能像在熊猫中那样在这里传递多个分隔符。
  • 每个作业一个分隔符,每个作业没有多个。
  • 是否将 csv 文件中的 ; 替换为 , 是一个选项?那么没有文本字段应该包含;,使用像sed 这样的shell命令非常快。
  • 是的,我替换了它。但是现在我可以在 csv 文件中看到像 ABC 这样的带有额外分隔符的行;; ..如何照顾它

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


【解决方案1】:

为此,我在 Cloud Functions 中部署了以下代码。我使用“Cloud Storage”作为触发器,使用“Finalize/Create”作为事件类型。该代码可以成功地在逗号和分号分隔的文件上运行 Bigquery Load 作业。

ma​​in.py

def hello_gcs(event, context):
 from google.cloud import bigquery
 from google.cloud import storage
 import subprocess

# Construct a BigQuery client object.
 client = bigquery.Client()
 client1 = storage.Client()

 bucket = client1.get_bucket('Bucket-Name')
 blob = bucket.get_blob(event['name'])  

# TODO(developer): Set table_id to the ID of the table to create.
 table_id = "ProjectID.DatasetName.TableName"
 with open("/tmp/z", "wb") as file_obj:

   blob.download_to_file(file_obj)

 subprocess.call(["sed", "-i", "-e",  "s/;/,/", "/tmp/z"])


 job_config = bigquery.LoadJobConfig(

   autodetect=True,
   skip_leading_rows=1,
   field_delimiter=",",
   write_disposition="WRITE_APPEND",
      

   # The source format defaults to CSV, so the line below is optional.
   source_format=bigquery.SourceFormat.CSV,
 )
  
 with open("/tmp/z", "rb") as source_file:

   source_file.seek(0)
  

   job = client.load_table_from_file(source_file, table_id, job_config=job_config)

   # Make an API request.
 job.result()  # Waits for the job to complete.

requirements.txt

# Function dependencies, for example:
# package>=version
google-cloud
google-cloud-bigquery
google-cloud-storage

这里,我用“;”代替使用“,”使用Sed 命令。需要注意的一点是,在 Cloud Functions 中写入文件时,我们需要将路径指定为 /tmp/file_name,因为它是 Cloud Functions 中唯一允许写入文件的位置。它还假设文件中除了分隔符之外没有额外的逗号或分号。

【讨论】:

  • 如何将不同的 csv 文件映射到 Bigquery 中的表。对我来说,它是多个 csv 文件
  • 此代码将推送到 GCS 存储桶中的每个文件放入 Bigquery 表中。它不适用于 GCS 存储桶中预先存在的文件。如果后者是要求,则没有特别需要使用基于事件触发的 Cloud Functions。关于将文件映射到各种表,需要文件和表的命名方案。如果你能澄清你的要求,我可以根据这个编辑我的答案。另外,请编辑问题的一部分以反映您对多个表的要求。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-23
  • 1970-01-01
  • 1970-01-01
  • 2012-06-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多