从Cloud Functions到BigQuery的Pandas Dataframe-只有PARQUET和CSV sou



我正在使用GCP Cloud Functions查询API,并希望将结果写入BigQuery。我收到此错误:

得到意想不到的source_format:"NEWLINE_DELIMITED_JSON"。目前,仅支持 PARQUET 和 CSV

这是我的代码

from google.cloud import bigquery
import pandas as pd
import requests
import datetime
def hello_pubsub(event, context):

response = requests.get("https://api.openweathermap.org/data/2.5/weather?q=berlin&appid=12345&units=metric&lang=de")
responseJson = response.json()

# Creates DataFrame
df = pd.DataFrame({'datetime':pd.to_datetime(format(datetime.datetime.now())),
'name':str(responseJson['name']),
'temp':float(responseJson['main']['temp']),
'windspeed':float(responseJson['wind']['speed']),
'winddeg':int(responseJson['wind']['deg'])
}, index=[0])  
project_id = 'myproj'
client = bigquery.Client(project=project_id)
dataset_id = 'weather'
dataset_ref = client.dataset(dataset_id)
job_config = bigquery.LoadJobConfig()
job_config.autodetect = True
job_config.write_disposition = "WRITE_APPEND"
job_config.source_format = bigquery.SourceFormat.NEWLINE_DELIMITED_JSON
load_job = client.load_table_from_dataframe(df, dataset_ref.table("weather_de"), job_config=job_config)

最好的方法是什么?

BigQuery 客户端库参考指出,当使用load_table_from_dataframe()从数据帧加载到表中时,这是预期行为:

默认情况下,此方法使用镶木地板源格式。若要覆盖此设置,请为source_format提供一个具有格式名称的值。目前仅支持 CSV 和 PARQUET。

您可以尝试将该方法替换为load_table_from_json(),它也可用,并使用NEWLINE_DELIMITED_JSON作为源格式。此方法显然不接受数据帧作为输入,因此我建议使用 JSON 对象来存储 API 响应中所需的数据。否则,您可以使用 pandas 文档中的to_json()方法将创建的现有数据帧转换为 json。

您可以从参考中详细了解 BigQuery 客户端的工作原理,还可以查看构建的源代码格式。

最新更新