python - Firestore - 递归复制文档及其所有子集合/文档
问题描述
我们使用 Google 的 Firestore 来存储嵌入式机器配置数据。因为这些数据控制着一个可配置的页面流和许多其他的东西,所以它被分割成许多子集合。在这个系统中,每台机器都有它自己的顶级文档。但是,当我们将机器添加到机队时,需要很长时间,因为我们必须手动将所有这些数据复制到多个文档中。有谁知道如何在 Python 中递归地复制 Firestore 文档、它的所有子集合、他们的文档、子集合等。您将拥有顶级文档的引用以及新顶级文档的名称。
解决方案
您可以使用这样的东西递归地从一个集合读取和写入另一个集合:
def read_recursive(
source: firestore.CollectionReference,
target: firestore.CollectionReference,
batch: firestore.WriteBatch,
) -> None:
global batch_nr
for source_doc_ref in source:
document_data = source_doc_ref.get().to_dict()
target_doc_ref = target.document(source_doc_ref.id)
if batch_nr == 500:
log.info("commiting %s batched operations..." % batch_nr)
batch.commit()
batch_nr = 0
batch.set(
reference=target_doc_ref,
document_data=document_data,
merge=False,
)
batch_nr += 1
for source_coll_ref in source_doc_ref.collections():
target_coll_ref = target_doc_ref.collection(source_coll_ref.id)
read_recursive(
source=source_coll_ref.list_documents(),
target=target_coll_ref,
batch=batch,
)
batch = db_client.batch()
read_recursive(
source=db_client.collection("src_collection_name"),
target=db_client.collection("target_collection_name"),
batch=batch,
)
batch.commit()
写入是分批的,这样可以节省很多时间(在我的情况下,它完成的时间是 set 的一半)。
推荐阅读
- node.js - 我已经制作了正确的 Procfile,但在仪表板中没有看到工人测功机
- r - 将子文件夹中的excel文件合并到R中的一个数据框中
- flask - Flask 可选上传文件
- mod-security - ModSecurity规则中感叹号的含义
- selenium - Selenium 错误没有方法签名:org.openqa.selenium.chrome.ChromeDriver.find_element_by_class_name() 适用于参数
- python - 如何从 Python 的集合库中查看 deque 模块的源代码?
- ios - 将值从按钮传递到视图控制器字典
- node.js - 使用自定义文本输入触发 Google 自定义搜索引擎
- c++ - 我如何将 Cilk Plus Extensions 应用于这个简单的 C++ 代码?
- format - MIFARE 的 ATS 中的历史字节是什么以及在哪里?