[英]App hangs when adding a large number of documents to Firestore (e.g. 1000+ documents) at once
I am trying to allow a user to mass add a bunch of documents to Firestore from the client side.我试图允许用户从客户端向 Firestore 批量添加一堆文档。 It works fine when there aren't that many documents but when there a ton (eg 1000+ documents), it adds all of the documents and then just hangs.
当没有那么多文档但有大量文档(例如 1000 多个文档)时,它可以正常工作,它会添加所有文档然后挂起。 If I close and then reopen the app, I see that all of the documents have been added as desired.
如果我关闭然后重新打开应用程序,我会看到所有文档都已根据需要添加。
I am adding each document one by one using the following:我正在使用以下内容一一添加每个文档:
self.collection.document(noteID).setData(record.dictionary)
Is there a reason why this would hang after mass adding a bunch of documents but work fine on smaller sets?在大量添加一堆文档但在较小的集合上可以正常工作后,这是否会挂起? Is there a way to batch add a bunch of documents to Firestore so that they don't hang?
有没有办法将一堆文档批量添加到 Firestore,以免它们挂起?
This happends because each write is generating a transaction that need to be executed, and your app hangs as it is waiting for each transaction to respond.这是因为每次写入都会生成一个需要执行的事务,并且您的应用程序在等待每个事务响应时挂起。
to write tons of documents in one action the recomendation in the official documentatipon is to use Batch Writes .在一个动作中编写大量文档,官方文档中的建议是使用Batch Writes 。
Just take in consideration that each batch can take up tpo 500 writes.只需考虑到每批可以占用 tpo 500 次写入。
to Add data on Batch writes you can do it like this:要在批量写入上添加数据,您可以这样做:
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.")
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.