LoginSignup
1
0

CloudFunctions + BigQueryでpandasを使った一括インサートの備忘録

Posted at

概要

  • python
  • csvまたはtsvファイルのデータをBigQueryのテーブルにインポートする
    • pandas DataFrameにcsvのデータをいれて、そのままBigQueryに流し込みたい

起きた事

dataframeに入れたcsvデータをto_bgqを使い、一括でBigQueryに流し込む

df = pandas.read_csv(file_path, encoding='UTF8')

df.to_gbq(
    "project.test_dataset.table",
    table_schema=[スキーマ定義配列],
    if_exists='append'
)

結果、以下の様なエラー

Reason: 400 Error while reading data, error message: Failed to import values for column 'name': Unexpected end of stream"
  • 9400件あたりを超えるか超えないかが、エラー発生の境目になっているっぽいことがわかる
  • DataFrameへのreadは問題ない(全レコード取り込めている)
  • CloudFunctionsメモリも問題ない
  • to_gbqでこける
    to_gbqでのinsert処理はストリーミングらしいので、割り当て上限に引っかかっている

やったこと

DataFrameを特定行ごとに分割して処理する

# 一度のインサートが約9400以上で失敗するので、データフレームを分割して処理
df = pandas.read_csv(file_path, encoding='UTF8')

split_count = 8000
insert_count = 0
splited_df = [df[i:i+split_count] for i in range(0, len(df), split_count)]

for part in splited_df:
    logger.info(f"split insert:{insert_count}〜{insert_count + split_count}")
    part.to_gbq(
        "project.test_dataset.table",
        table_schema=[スキーマ定義配列],
        if_exists='append'
    )
    insert_count += split_count

これで解決。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0