python - 从 python 上传到 Bigquery

标签 python json upload export google-bigquery

我有一个 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.

来自代码示例:https://github.com/googleapis/python-bigquery/blob/9d43d2073dc88140ae69e6778551d140430e410d/samples/load_table_file.py#L19-L41

编辑:从 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')

来自代码示例:https://github.com/GoogleCloudPlatform/python-docs-samples/blob/4de1ac3971d3a94060a1af7f478330b9c40cfb09/bigquery/cloud-client/load_data_from_file.py#L34-L50

关于python - 从 python 上传到 Bigquery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44838239/

相关文章:

Python 静态方法并不总是可调用的

json - 指定扩展的私钥已存在。重新使用该 key 或先将其删除

php - 文件上传返回上传html页面

javascript - 动态改变JS

python - 很难启动 Rabbitmq Server 并想知道为什么不断收到此错误 init :do_boot/3 line 817

python - 短语改写器

python - 为什么 PyQt4 在 Python Packaging Index 上不可用?

javascript - 从输入属性获取 jquery Map

javascript - JQuery/Javascript 循环遍历 JQuery Mobile slider 并根据其值创建 JSON 字符串

wordpress - 如何允许Wordpress用户直接上传到youtube或vimeo?