【问题标题】:Firestore - Recursively Copy a Document and all it's subcollections/documentsFirestore - 递归复制文档及其所有子集合/文档
【发布时间】:2021-07-27 22:25:31
【问题描述】:
我们使用 Google 的 Firestore 存储嵌入式机器配置数据。因为这些数据控制着可配置的页面流和许多其他东西,所以它被分割成许多子集合。在这个系统中,每台机器都有它自己的顶级文档。然而,当我们将机器添加到机队时,这需要很长时间,因为我们必须手动将所有这些数据复制到多个文档中。有谁知道如何在 Python 中递归地复制 Firestore 文档、它的所有子集合、他们的文档、子集合等。您将拥有顶级文档的引用以及新顶级文档的名称。
【问题讨论】:
标签:
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 的一半)。