在我的 python 项目中,我需要用关系数据框填充一个 bigquery 表。我在从头开始创建新表并确保我上传到它的第一个数据实际放入表中时遇到了很多麻烦。
我已阅读页面 https://cloud.google.com/bigquery/streaming-data-into-bigquery#dataconsistency并且已经看到将 insertId 应用于插入查询可以解决问题,但由于我使用 pandas 的数据帧,pandas-gbq 包的 to_gbq 函数似乎非常适合此任务。然而,当使用 to_gbq 函数并创建/替换新表时,有时(显然是随机的)第一个数据 block 没有写入表中。
有谁知道如何确保将 DataFrame 完全插入到 bigquery 新创建的表中?谢谢
请您参考如下方法:
我相信你遇到的是https://github.com/pydata/pandas-gbq/issues/75 .基本上,Pandas 使用 BigQuery 流式 API 将数据写入表中,但流式 API 从创建表到开始工作之间存在延迟。
编辑:pandas-gbq 0.3.0 版通过使用加载作业将数据帧上传到 BigQuery 而不是流式传输来解决此问题。
与此同时,我建议使用“加载作业”来创建表。例如,使用 client.load_table_from_file google-cloud-bigquery 包中的方法。
from google.cloud.bigquery import LoadJobConfig
from six import StringIO
destination_table = client.dataset(dataset_id).table(table_id)
job_config = LoadJobConfig()
job_config.write_disposition = 'WRITE_APPEND'
job_config.source_format = 'NEWLINE_DELIMITED_JSON'
rows = []
for row in maybe_a_dataframe:
row_json = row.to_json(force_ascii=False, date_unit='s', date_format='iso')
rows.append(row_json)
body = StringIO('{}\n'.format('\n'.join(rows)))
client.load_table_from_file(
body,
destination_table,
job_config=job_config).result()
编辑:对于包含非 ASCII 字符的列,此代码示例失败。参见 https://github.com/pydata/pandas-gbq/pull/108
