BigQueryに既存のCloud Firestoreのデータを同期したい

Cloud FirestoreとBigQueryを同期してデータを分析したくなりました。

qiita.com

まずこちらの記事がとても分かりやすく書かれていました。

しかし、紹介されているExport Collections to BigQuery は「変更があったドキュメント」しかBigQueryに送信してくれません。

既にDB上にあるデータもBigQuery上で分析に使いたいです。

そこで既存のデータもBigQueyに同期する方法を調べたのでメモしておきます。

一部詰まった部分があったため記事として残しておきますが、一連のやり方はこちらに書いてあります。 github.com

同期手順

gcloudツールをダウンロードしていない場合、まずはこちらからダウンロードして使えるようにします。

こちらを使ってログインをしないと後に Error importing Collection to BigQuery: Error: Could not load the default credentials.という認証系のエラーで怒られます。

ルート直下にダウンロードして、実行ファイルからloginをします。

[~]
$ ls
... google-cloud-sdk

[~]
$ ./google-cloud-sdk/bin/gcloud init

[~]
$ ./google-cloud-sdk/bin/gcloud auth application-default login

これで認証ができました。

次にbqにデータをインポートするコマンドをnpx経由で叩きます。

$ npx @firebaseextensions/fs-bq-import-collection

対話形式で回答していきます。

? What is your Firebase project ID? hogemaru-app
? What is the path of the the Cloud Firestore Collection you would like to import from? (This may, or may not, be the same Collection for which you plan to mirror changes.) posts
? Would you like to import documents via a Collection Group query? Yes
? What is the ID of the BigQuery dataset that you would like to use? (A dataset will be created if it doesn't already exist) firestore_export
? What is the identifying prefix of the BigQuery table that you would like to import to? (A table will be created if one doesn't already exist) posts
? How many documents should the import stream into BigQuery at once? 300
? Where would you like the BigQuery dataset to be located? asia-northeast1
? Would you like to run the import across multiple threads? No

これで上記の認証が済んでいればコマンドラインで指定した件数ずつインポートが開始されます(今回はデフォルトの300件ずつ)。

...
{"severity":"INFO","message":"Inserting 262 row(s) of data into BigQuery"}
{"severity":"INFO","message":"Inserted 262 row(s) of data into BigQuery"}
---------------------------------------------------------
Finished importing 10000 Firestore rows to BigQuery
---------------------------------------------------------

[~]
$

これでBigQueyで以下のようなクエリを叩いてみてください。

SELECT COUNT(document_id)
FROM POSTS;

既存のデータ量分が取得できているかと思います!

参考