簡體   English   中英

使用 Cloud function 將 TXT 文件轉換為 CSV 並在 Google BigQuery 中填充數據

[英]Convert TXT file into CSV with Cloud function and populate data in Google BigQuery

我正在嘗試轉換一個txt。 文件放入 csv。 並通過 Google Cloud function 使用所有數據填充 BigQuery 表。

TXT 文件看起來與 CSV 文件非常相似,如下所示。 整個文件重量約為 35Go,行數超過 350k。

[![在此處輸入圖像描述][1]][1]

我嘗試應用上面共享的 python 腳本,但它不起作用......我的 function 運行正常,但它沒有向 BigQuery 填充任何數據。

我跟着這個stackoverflow 踏步

我的 main.py function:

import pandas as pd
from google.cloud import bigquery

def txt_to_csv(event, context):
    fileName = "gs://Bucket_name/file.txt" 
    bigqueryClient = bigquery.Client("project-name")
    tableRef = bigqueryClient.dataset("Dataset").table("07_02_2021")
    dataFrame = pd.read_csv(fileName, sep=",")
    bigqueryJob = bigqueryClient.load_table_from_dataframe(dataFrame, tableRef)
    bigqueryJob.result()

我的 requirements.txt 文件:

google-api-core==1.16.0
google-api-python-client==1.8.0
google-auth==1.12.0
google-auth-httplib2==0.0.3
google-cloud-bigquery==1.24.0
google-cloud-core==1.3.0
google-cloud-storage==1.26.0
google-resumable-media==0.5.0
googleapis-common-protos==1.51.0
pandas==1.0.3
pyarrow

有人幫我嗎? 我覺得我錯過了讓它正常工作的步驟......比如可能為我的表創建一個特定的數據框/模式 或者也許我應該將 pandas dataframe 加載到桌子上還是錯誤的方式?

我成功地使用您的代碼從Cloud Storage 存儲桶中的文件填充數據:

import pandas as pd
from google.cloud import bigquery

def txt_to_csv(event, context):
    fileName = "gs://Bucket_NAME/File.txt" 
    bigqueryClient = bigquery.Client("PROJECT_ID")
    tableRef = bigqueryClient.dataset("DATASET_NAME").table("TABLE_NAME")
    dataFrame = pd.read_csv(fileName, sep=",")
    bigqueryJob = bigqueryClient.load_table_from_dataframe(dataFrame, tableRef)
    bigqueryJob.result()

我按照以下步驟操作:

1)我使用了帶有以下數據的.txt文件:

full_name,birth_year
"Lea",1996
"Jose",1995
"John",1997
"Berta",2001
"Marta",2005

2) 我在 BigQuery 中創建了一個包含以下字段的表:

  • 全名作為字符串
  • 出生年份為 Integer

3) I deploy the Cloud Function using the requirements.txt you provided, it deployed successfully however when I tested the Cloud Function "By going to your Cloud Function --> Testing Tab and click on **Test the Function **button ",我收到以下錯誤:

Missing optional dependency 'gcsfs'. The gcsfs library is required 
to handle GCS files Use pip or conda to install gcsfs.
  • 為了緩解這個問題,我將gcsfs庫添加到 Cloud Functions requirements.txt 文件中:

google-api-core==1.16.0
google-api-python-client==1.8.0
google-auth==1.12.0
google-auth-httplib2==0.0.3
google-cloud-bigquery==1.24.0
google-cloud-core==1.3.0
google-cloud-storage==1.26.0
google-resumable-media==0.5.0
googleapis-common-protos==1.51.0
pandas==1.0.3
pyarrow
gcsfs==0.7.2

4)我再次部署function並進行了測試。 這次 function 將數據正確添加到 BigQuery 表中。

解決方案

  • 所以請注意:部署雲 Function 不會將數據填充到 BigQuery,您需要對其進行測試。

  • 另一方面,您有一個字段為字符串類型的表,但在 .txt 文件中,您有 Integer、時間戳等類型的數據。如果您只是想測試,那么您可以將所有數據放在您的 .txt 文件中字符串或根據文件中的數據類型更改 BigQuery 表的字段類型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM