简体   繁体   English

Firestore 新数据库 - 如何备份

[英]Firestore new database - How do I backup

Does the google firestore database service provides a backup? google firestore 数据库服务是否提供备份? If so, how do I backup the database and how do I restore in case of an error?如果是这样,我如何备份数据库以及在出现错误时如何恢复?

Update : It is now possible to backup and restore Firebase Firestore using Cloud Firestore managed export and import service更新:现在可以使用 Cloud Firestore 托管导出和导入服务备份和恢复 Firebase Firestore

You do it by:你这样做:

  1. Create a Cloud Storage bucket for your project - Make sure it's a regional in us-central1 or 2 / multi regional type of bucket为您的项目创建一个 Cloud Storage 存储分区 - 确保它是 us-central1 或 2 / 多区域类型的存储分区

  2. Set up gcloud for your project using gcloud config set project [PROJECT_ID]使用gcloud config set project [PROJECT_ID]为您的项目设置gcloud

EXPORT出口

Export all by calling gcloud firestore export gs://[BUCKET_NAME] Or Export a specific collection using gcloud firestore export gs://[BUCKET_NAME] --collection-ids='[COLLECTION_ID_1]','[COLLECTION_ID_2]'通过调用gcloud firestore export gs://[BUCKET_NAME]导出所有或使用gcloud firestore export gs://[BUCKET_NAME] --collection-ids='[COLLECTION_ID_1]','[COLLECTION_ID_2]'导出特定集合

IMPORT进口

Import all by calling gcloud firestore import gs://[BUCKET_NAME]/[EXPORT_PREFIX]/ where [BUCKET_NAME] and [EXPORT_PREFIX] point to the location of your export files.通过调用gcloud firestore import gs://[BUCKET_NAME]/[EXPORT_PREFIX]/导入所有内容,其中 [BUCKET_NAME] 和 [EXPORT_PREFIX] 指向导出文件的位置。 For example - gcloud firestore import gs://exports-bucket/2017-05-25T23:54:39_76544/例如 - gcloud firestore import gs://exports-bucket/2017-05-25T23:54:39_76544/

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

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

Update July 2018: Cloud Firestore now supports managed import and export of data. 2018 年 7 月更新:Cloud Firestore 现在支持数据的托管导入和导出。 See the documentation for more details:有关更多详细信息,请参阅文档:

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


[Googler here] No, right now we do not offer a managed backup or import/export service. [Googler here]不,目前我们不提供托管备份或导入/导出服务。 This is something we will definitely offer in the future, we just did not get it ready for the initial Beta release.这是我们将来肯定会提供的东西,我们只是没有为最初的 Beta 版本做好准备。

The best way to back up right now is to write your own script using our Java/Python/Node.js/Go server SDKs, it should be fairly straightforward to download all documents from each collection and write them back if you need to.现在最好的备份方法是使用我们的 Java/Python/Node.js/Go 服务器 SDK 编写您自己的脚本,从每个集合中下载所有文档并在需要时将它们写回应该相当简单。

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

Is a tool that has been created to do just this.是一种专为实现此目的而创建的工具。

(I did not create it, just adding it here as people will find this question) (我没有创建它,只是在这里添加它,因为人们会发现这个问题)

I am using the following work-around in order to have daily firestore backups:我正在使用以下解决方法来进行每日 Firestore 备份:

I installed this globally: https://www.npmjs.com/package/firestore-backup-restore我在全球安装了这个: https : //www.npmjs.com/package/firestore-backup-restore

I have a cron job that looks like this:我有一个看起来像这样的 cron 工作:

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

And my backup-script.sh looks like this:我的备份脚本.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"

Local backups本地备份

  1. firestore-import-export Firestore-进出口

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) (如果您想要单个 JSON 文件,则最直接)

  1. firestore-backup-restore firestore-备份-恢复

Drawbacks:缺点:

  1. Hasn't been updated in a long time.好久没更新了。

Additional options: (not recommended)附加选项:(不推荐)

  1. python-firebase-admin-firestore-backup 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 Firestore-备份

Drawbacks:缺点:

  1. Backup only;仅备份; cannot restore from the backups it creates.无法从它创建的备份中恢复。

Cloud backups云备份

  1. The official gcloud backup commands .官方gcloud 备份命令

Drawbacks:缺点:

  1. The backup files are difficult/infeasible to parse.备份文件难以解析/不可行。 (update: how to convert to a json file ) (更新:如何转换为json文件
  2. You have to set up the gcloud cli .您必须设置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) (也可以被认为是一种优势,取决于你想要什么)

Note that for the gcloud backup commands, you have multiple options on how to schedule them to run automatically.请注意,对于 gcloud 备份命令,您可以通过多种选择来安排它们自动运行。 A few options are shown here .此处显示了一些选项。

I've written a tool that traverses the collections/documents of the database and exports everything into a single json file.我编写了一个工具,可以遍历数据库的集合/文档并将所有内容导出到单个 json 文件中。 Plus, it will import the same structure as well (helpful for cloning/moving Firestore databases).此外,它还将导入相同的结构(有助于克隆/移动 Firestore 数据库)。 It's published as an NPM package.它作为 NPM 包发布。 Feel free to try it and give some feedback.随意尝试并提供一些反馈。

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

I had the same issue and created a small npm package which allows you to create a scheduled backup with Cloud Functions.我遇到了同样的问题并创建了一个小的 npm 包,它允许您使用 Cloud Functions 创建计划备份。 It uses the new import/export feature of Firestore.它使用 Firestore 的新导入/导出功能。

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

Checkout the full readme on how to set it up, it's super simple!查看有关如何设置它的完整自述文件,超级简单!

A solution using Python 2 .使用Python 2的解决方案。

Fork it on https://github.com/RobinManoli/python-firebase-admin-firestore-backuphttps://github.com/RobinManoli/python-firebase-admin-firestore-backup上分叉

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

Then install it in your python environment:然后在你的python环境中安装它:

pip install firebase-admin

Install the Firestore module:安装 Firestore 模块:

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

(from ImportError: Failed to import the Cloud Firestore library for Python ) (来自ImportError: Failed to import the Cloud Firestore library for Python

Python Code 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)

Here is my Android Java code for get backup easily for any fire store data collection这是我的 Android Java 代码,用于轻松获取任何消防商店数据收集的备份

First use this method to read the collection data and store in it to serialized file in the mobile device storage首先使用该方法读取集合数据并存储到移动设备存储中的序列化文件中

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());
                        }
                    }
                });
    }

After that you can check the logcat whether the data is serialized correctly.之后你可以检查logcat数据是否正确序列化。 and here is the restore code这是恢复代码

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();
        }
    }

Hope this would help希望这会有所帮助

Question is old, projects are nice but I have some concerns about the backup.问题很老,项目很好,但我对备份有些担忧。

1-For blaze plan users (free) official solution is off-limit. 1-对于 blaze 计划用户(免费)官方解决方案是禁止的。

2-Since Free users have 50k read quota per day that limit could be a problem in live and large databases. 2-由于免费用户每天有 50k 读取配额,该限制在实时和大型数据库中可能是一个问题。

3-As far as I examined most of the projects does not have a time limit or so, downloading same data every time it is run. 3-据我检查,大多数项目没有时间限制,每次运行时都下载相同的数据。

4-Wouldn't it be better to save collections as folders and every document as seperate file and and fetch only updated documents and replace file directly. 4-将集合保存为文件夹并将每个文档保存为单独的文件并且仅获取更新的文档并直接替换文件不是更好吗?

I will probably implement my own solution but just wondering your thoughts :)我可能会实施我自己的解决方案,但只是想知道您的想法:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何编写一个云 function,它在新用户通过身份验证后在 Firestore 数据库中创建一个用户? - How do I write a cloud function which creates a user in the Firestore database once a new user gets authenticated? 如何将我的 MAUI 应用程序连接到生产环境中的 Firestore 数据库? - How do I connect my MAUI app to a Firestore database in production? 我想根据输入的可用床数在 firestore 数据库中添加新列 - I want to add new column in the firestore database depending on how many beds available inputted Firestore - 如何将新的键值对添加到包含地图列表的文档中? - Firestore - How do I add a new key value pair to a document containing a list of maps? 如何使用 flutter 中的 JSONserializable 在 Cloud Firestore 数据库中设置嵌套字段 - How do I set up a nested field in a Cloud Firestore database using JSONserializable in flutter 如何使用 Flutter、Firebase - Firestore 数据库根据日期对数据进行分组和列出? - How do I Group and List data according to date using Flutter, Firebase - Firestore Database? 如何使用用户输入的文档名称在 firestore 中输入数据库? - How do i input database in firestore with user's input for name of the document? 如何在 Firestore 中实施数据库模式? - How can I enforce database schema in Firestore? 如何使用 StreamBuilder 显示我的 Cloud firestore 数据库中一个特定文档的数据? - How do I use StreamBuilder to display the data from ONE specific document in my Cloud firestore database? 如何在 firestore 中编写以下规则? - How do I write the follow rule in firestore?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM