【问题标题】:App hangs when adding a large number of documents to Firestore (e.g. 1000+ documents) at once一次向 Firestore 添加大量文档(例如 1000 多个文档)时,应用程序挂起
【发布时间】:2020-08-19 16:38:33
【问题描述】:
我正在尝试允许用户从客户端向 Firestore 批量添加一堆文档。当文档不多但有大量文档(例如 1000 多个文档)时,它可以正常工作,它会添加所有文档然后挂起。如果我关闭然后重新打开应用程序,我会看到所有文档都已根据需要添加。
我正在使用以下内容逐个添加每个文档:
self.collection.document(noteID).setData(record.dictionary)
是否有原因导致在大量添加大量文档后会挂起但在较小的集合上可以正常工作?有没有办法将一堆文档批量添加到 Firestore,以免它们挂起?
【问题讨论】:
标签:
swift
firebase
google-cloud-firestore
【解决方案1】:
这是因为每次写入都会生成一个需要执行的事务,并且您的应用在等待每个事务响应时挂起。
要在一个动作中编写大量文档,官方文档中的建议是使用Batch Writes。
只要考虑到每批可能会占用 tpo 500 次写入。
要在批量写入上添加数据,您可以这样做:
let batch = self.batch()
//set Documents to add
let doc1 = self.collection(<COLLECTION>).document(noteID)
batch.setData(record.dictionary, forDocument: doc1)
//commit the batch
batch.commit() { err in
if let err = err {
print("Error writing batch \(err)")
} else {
print("Batch write succeeded.")
}
}