Firestoreエクスポート・インポート
Google Cloud Firestoreのデータをエクスポート・インポートする方法について説明します。
基本的な使い方
Section titled “基本的な使い方”エクスポート
Section titled “エクスポート”特定のコレクションをCloud Storageにエクスポートします。
# handlebarコレクションをエクスポートgcloud firestore export gs://nerikosodev.appspot.com/firestore_export/handlebar --collection-ids=handlebarエクスポートしたデータをFirestoreにインポートします。
# handlebarコレクションをインポートgcloud firestore import gs://nerikosodev.appspot.com/firestore_export/handlebar --collection-ids=handlebarパラメータ説明
Section titled “パラメータ説明”gs://nerikosodev.appspot.com/firestore_export/handlebar: エクスポート先/インポート元のCloud Storageパス--collection-ids=handlebar: 対象のコレクションID
高度な使い方
Section titled “高度な使い方”複数コレクションの処理
Section titled “複数コレクションの処理”# 複数のコレクションをエクスポートgcloud firestore export gs://your-bucket/firestore_export/$(date +%Y%m%d_%H%M%S) \ --collection-ids=users,posts,comments
# 全コレクションをエクスポート(--collection-idsを省略)gcloud firestore export gs://your-bucket/firestore_export/all_$(date +%Y%m%d_%H%M%S)非同期実行の確認
Section titled “非同期実行の確認”# エクスポート/インポート操作の一覧表示gcloud firestore operations list
# 特定の操作の詳細確認gcloud firestore operations describe [OPERATION_NAME]プロジェクト間のデータ移行
Section titled “プロジェクト間のデータ移行”# ソースプロジェクトからエクスポートgcloud firestore export gs://source-bucket/firestore_export/data \ --project=source-project
# ターゲットプロジェクトにインポートgcloud firestore import gs://source-bucket/firestore_export/data \ --project=target-projectスクリプト例
Section titled “スクリプト例”バックアップスクリプト
Section titled “バックアップスクリプト”#!/bin/bash
# 設定PROJECT_ID="nerikosodev"BUCKET="gs://${PROJECT_ID}.appspot.com"COLLECTIONS=("handlebar" "users" "settings")TIMESTAMP=$(date +%Y%m%d_%H%M%S)
# 各コレクションをバックアップfor collection in "${COLLECTIONS[@]}"; do echo "エクスポート中: ${collection}" gcloud firestore export "${BUCKET}/firestore_backup/${TIMESTAMP}/${collection}" \ --collection-ids="${collection}" \ --project="${PROJECT_ID}"done
echo "バックアップ完了: ${TIMESTAMP}"リストア手順書
Section titled “リストア手順書”#!/bin/bash
# エクスポート一覧の確認gsutil ls gs://nerikosodev.appspot.com/firestore_backup/
# 特定の日時のバックアップからリストアBACKUP_PATH="gs://nerikosodev.appspot.com/firestore_backup/20240101_120000/handlebar"
# データのインポートgcloud firestore import "${BACKUP_PATH}" --collection-ids=handlebar
# インポート状況の確認gcloud firestore operations list --filter="metadata.operationType=IMPORT_DOCUMENTS"- 権限: Cloud Storageへの読み書き権限とFirestoreの管理権限が必要
- コスト: エクスポート/インポート操作は読み取り・書き込み操作としてカウントされる
- データ整合性: エクスポート中もFirestoreは稼働しているため、完全な整合性は保証されない
- タイムスタンプ: エクスポート先のパスに日時を含めることを推奨
トラブルシューティング
Section titled “トラブルシューティング”権限エラーの場合
Section titled “権限エラーの場合”# サービスアカウントに必要な権限を付与gcloud projects add-iam-policy-binding [PROJECT_ID] \ --member="serviceAccount:[SERVICE_ACCOUNT_EMAIL]" \ --role="roles/datastore.importExportAdmin"エクスポートが失敗する場合
Section titled “エクスポートが失敗する場合”# Cloud Storageバケットの存在確認gsutil ls gs://nerikosodev.appspot.com/
# バケットへの書き込み権限確認gsutil acl get gs://nerikosodev.appspot.com/