首页 > 解决方案 > Firestore - 递归复制文档及其所有子集合/文档

问题描述

我们使用 Google 的 Firestore 来存储嵌入式机器配置数据。因为这些数据控制着一个可配置的页面流和许多其他的东西,所以它被分割成许多子集合。在这个系统中,每台机器都有它自己的顶级文档。但是,当我们将机器添加到机队时,需要很长时间,因为我们必须手动将所有这些数据复制到多个文档中。有谁知道如何在 Python 中递归地复制 Firestore 文档、它的所有子集合、他们的文档、子集合等。您将拥有顶级文档的引用以及新顶级文档的名称。

标签: pythongoogle-cloud-firestorefirebase-admin

解决方案


您可以使用这样的东西递归地从一个集合读取和写入另一个集合:

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 的一半)。


推荐阅读