我有一个 Python 脚本,它从 firebase 下载数据,对其进行处理,然后将其转储到 JSON 文件中。我可以通过命令行将它上传到 BigQuery,但现在我想将一些代码放入 Python 脚本中,以将其全部完成。
这是我目前的代码。
import json
from firebase import firebase
firebase = firebase.FirebaseApplication('<redacted>')
result = firebase.get('/connection_info', None)
id_keys = map(str, result.keys())
#with open('result.json', 'r') as w:
# connection = json.load(w)
with open("w.json", "w") as outfile:
for id in id_keys:
json.dump(result[id], outfile, indent=None)
outfile.write("\n")
最佳答案
要使用 google-cloud-bigquery
Python 库加载 JSON 文件,请使用 Client.load_table_from_file()方法。
from google.cloud import bigquery
bigquery_client = bigquery.Client()
table_id = 'myproject.mydataset.mytable'
# This example uses JSON, but you can use other formats.
# See https://cloud.google.com/bigquery/loading-data
job_config = bigquery.LoadJobConfig(
source_format='NEWLINE_DELIMITED_JSON'
)
with open(source_file_name, 'rb') as source_file:
job = bigquery_client.load_table_from_file(
source_file, table_id, job_config=job_config
)
job.result() # Waits for the job to complete.
编辑:从 Python 库的 0.28.0 版开始,上传到表格的方式发生了变化。以下是在 0.27 及更早版本中执行此操作的方法。
要使用 google-cloud-bigquery
Python 库加载 JSON 文件,请使用 Table.upload_from_file()
方法。
bigquery_client = bigquery.Client()
dataset = bigquery_client.dataset('mydataset')
table = dataset.table('mytable')
# Reload the table to get the schema.
table.reload()
with open(source_file_name, 'rb') as source_file:
# This example uses JSON, but you can use other formats.
# See https://cloud.google.com/bigquery/loading-data
job = table.upload_from_file(
source_file, source_format='NEWLINE_DELIMITED_JSON')
关于python - 从 python 上传到 Bigquery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44838239/