Firestore 新数据库 - 如何备份

Firestore new database - How do I backup

google firestore 数据库服务是否提供备份? 如果是这样,我如何备份数据库以及在出现错误时如何恢复?

2018 年 7 月更新:Cloud Firestore 现在支持托管数据导入和导出。有关详细信息,请参阅文档:

https://firebase.google.com/docs/firestore/manage-data/export-import


[此处为 Googler] 不,目前我们不提供托管备份或 import/export 服务。这是我们将来肯定会提供的东西,我们只是没有为最初的 Beta 版本做好准备。

现在最好的备份方法是使用我们的 Java/Python/Node.js/Go 服务器 SDK 编写您自己的脚本,从每个集合下载所有文档并编写它们应该相当简单如果需要,请返回。

https://www.npmjs.com/package/firestore-backup

是专门为此创建的工具。

(我没有创建它,只是添加在这里因为人们会发现这个问题)

我正在使用以下变通方法来进行每日 Firestore 备份:

我在全局安装了这个:https://www.npmjs.com/package/firestore-backup-restore

我有一个看起来像这样的 cron 作业:

0 12 * * *  cd ~/my/backup/script/folder && ./backup-script.sh

我的备份-script.sh 看起来像这样:

#!/bin/sh

. ~/.bash_profile

export PATH=/usr/local/bin/

dt=$(/bin/date '+%d-%m-%Y %H:%M:%S');
echo "starting backup for $dt"
firestore-backup-restore -a ~/path/to/account/credentials/file.json -B ./backups/"$dt"

我编写了一个遍历数据库 collections/documents 并将所有内容导出到单个 json 文件中的工具。此外,它还将导入相同的结构(对 cloning/moving Firestore 数据库有帮助)。它作为 NPM 包发布。欢迎试用并提供一些反馈。

https://www.npmjs.com/package/node-firestore-import-export

更新:现在可以使用 Cloud Firestore 管理的导出和导入服务备份和恢复 Firebase Firestore

您通过以下方式完成:

  1. Create a Cloud Storage bucket for your project - 确保它是 us-central1 或 2 中的区域/多区域类型的存储桶

  2. 使用 gcloud config set project [PROJECT_ID]

    为您的项目设置 gcloud

出口

全部导出调用 gcloud firestore export gs://[BUCKET_NAME] 或者 导出特定集合 使用 gcloud firestore export gs://[BUCKET_NAME] --collection-ids='[COLLECTION_ID_1]','[COLLECTION_ID_2]'

导入

通过调用全部导入 gcloud firestore import gs://[BUCKET_NAME]/[EXPORT_PREFIX]/ [BUCKET_NAME] 和 [EXPORT_PREFIX] 指向导出文件的位置。例如 - gcloud firestore import gs://exports-bucket/2017-05-25T23:54:39_76544/

通过调用导入特定集合gcloud firestore import --collection-ids='[COLLECTION_ID_1]','[COLLECTION_ID_2]' gs://[BUCKET_NAME]/[EXPORT_PREFIX]/

完整说明可在此处获得: https://firebase.google.com/docs/firestore/manage-data/export-import

使用Python 2.

的解决方案

https://github.com/RobinManoli/python-firebase-admin-firestore-backup

上进行分叉

首先安装和设置 Firebase Admin Python SDK:https://firebase.google.com/docs/admin/setup

然后将其安装在您的 python 环境中:

pip install firebase-admin

安装 Firestore 模块:

pip install google-cloud-core
pip install google-cloud-firestore

(来自

Python代码

# -*- coding: UTF-8 -*-

import firebase_admin
from firebase_admin import credentials, firestore
import json

cred = credentials.Certificate('xxxxx-adminsdk-xxxxx-xxxxxxx.json') # from firebase project settings
default_app = firebase_admin.initialize_app(cred, {
    'databaseURL' : 'https://xxxxx.firebaseio.com'
})

db = firebase_admin.firestore.client()

# add your collections manually
collection_names = ['myFirstCollection', 'mySecondCollection']
collections = dict()
dict4json = dict()
n_documents = 0

for collection in collection_names:
    collections[collection] = db.collection(collection).get()
    dict4json[collection] = {}
    for document in collections[collection]:
        docdict = document.to_dict()
        dict4json[collection][document.id] = docdict
        n_documents += 1

jsonfromdict = json.dumps(dict4json)

path_filename = "/mypath/databases/firestore.json"
print "Downloaded %d collections, %d documents and now writing %d json characters to %s" % ( len(collection_names), n_documents, len(jsonfromdict), path_filename )
with open(path_filename, 'w') as the_file:
    the_file.write(jsonfromdict)

我遇到了同样的问题并创建了一个小的 npm 包,它允许您使用 Cloud Functions 创建计划备份。它使用 Firestore 的新 import/export 功能。

const firestoreBackup = require('simple-firestore-backup')
exports.firestore_backup = functions.pubsub.schedule('every 24 hours').onRun(firestoreBackup.createBackupHandler())

查看完整的readme设置方法,超级简单!

这是我的 Android Java 代码,用于轻松备份任何 fire 存储数据收集

首先使用此方法读取采集数据并存储到移动设备存储中的序列化文件

private void readCollection(){
        ServerSide.db.collection("Collection_name")
                .get()
                .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                        if (task.isSuccessful()) {
                            HashMap alldata = new HashMap();
                            for (QueryDocumentSnapshot document : task.getResult()) {
                                alldata.put(document.getId(),document.getData());
//                                ServerSide.db.collection("A_Sentences_test").document(document.getId())
//                                        .set(document.getData());
                            }
                            try {
                                FileOutputStream fos = openFileOutput("filename.txt", Context.MODE_PRIVATE);
                                ObjectOutputStream os = new ObjectOutputStream(fos);
                                os.writeObject(alldata);
                                os.close();
                                fos.close();
                                Toast.makeText(MainActivity.this, "Stored", Toast.LENGTH_SHORT).show();

                                FileInputStream fis = openFileInput("filename.txt");
                                ObjectInputStream is = new ObjectInputStream(fis);
                                HashMap ad = (HashMap) is.readObject();
                                is.close();
                                fis.close();
                                Log.w("All data",ad+" ");

                            }catch (Exception e){
                                Log.w("errrrrrrrr",e+"");
                            }
                        } else {
                            Log.d("Colllllllllll", "Error getting documents: ", task.getException());
                        }
                    }
                });
    }

之后您可以检查logcat数据是否被正确序列化。这是恢复代码

private void writeData(){
        try {
            FileInputStream fis = openFileInput("filename.txt");
            ObjectInputStream is = new ObjectInputStream(fis);
            HashMap ad = (HashMap) is.readObject();
            is.close();
            fis.close();
            for (Object s : ad.keySet()){
                ServerSide.db.collection("Collection_name").document(s.toString())
                        .set(ad.get(s));
            }
            Log.w("ddddddddd",ad+" ");
        }catch (Exception e){
            e.printStackTrace();
        }
    }

希望这会有所帮助

问题老了,项目很好,但我对备份有一些担忧。

1-对于 blaze 计划用户(免费)官方解决方案是禁止使用的。

2-由于免费用户每天有 50k 的读取配额,该限制在实时和大型数据库中可能是个问题。

3-据我检查,大多数项目没有时间限制,每次下载相同的数据是 运行。

4-将集合保存为文件夹,将每个文档保存为单独的文件,并且只获取更新的文档并直接替换文件不是更好吗?

我可能会实施自己的解决方案,但只是想知道您的想法:)

本地备份

  1. firestore-import-export

This is the one I use for "one-off", local backups, and what I generally recommend. (most straight-forward if you want a single JSON file)

  1. firestore-backup-restore

Drawbacks:

  1. Hasn't been updated in a long time.

其他选项:(不推荐)

  1. python-firebase-admin-firestore-backup

Drawbacks:

  1. Backup only; cannot restore from the backups it creates.
  2. Hasn't been updated in a long time.
  1. firestore-backup

Drawbacks:

  1. Backup only; cannot restore from the backups it creates.

云备份

  1. 官方gcloud backup commands.

Drawbacks:

  1. The backup files are difficult/infeasible to parse. (update: how to )
  2. You have to set up the gcloud cli. (update: or use the cloud shell to run the commands)
  3. It doesn't backup locally; instead, it backs up to the cloud, which you can then download. (could also be considered an advantage, depending on what you want)

请注意,对于 gcloud 备份命令,您有多个选项可以选择如何将它们自动安排到 运行。几个选项是 shown here.