【问题标题】:Firestore - Recursively Copy a Document and all it's subcollections/documentsFirestore - 递归复制文档及其所有子集合/文档
【发布时间】:2021-07-27 22:25:31
【问题描述】:

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

【问题讨论】:

  • 您好,您能否详细说明您如何更新 Firestore 的所有文档?就像您如何构建数据一样。例如,您的数据是否结构化以使用查找? [1]您是否在一个程序中更新所有文档?如果是这样,您是否尝试过借助 Cloud Firestore 函数触发器将其解耦?[2] 使用这些触发器,您可以定义异步函数来监听文档更改并划分计算工作量。 [1] youtube.com/watch?v=i1n9Kw3AORw&t=438s [2] firebase.google.com/docs/functions/…

标签: python google-cloud-firestore firebase-admin


【解决方案1】:

你可以使用这样的东西递归地从一个集合读写到另一个集合:

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

【讨论】:

    猜你喜欢
    • 2020-01-22
    • 2021-01-08
    • 2021-08-12
    • 2021-09-17
    • 1970-01-01
    • 1970-01-01
    • 2020-04-16
    • 2018-11-01
    • 2018-10-21
    相关资源
    最近更新 更多