事务和批量写入
Firestore 支持通过原子操作读取和写入数据。在一组原子操作中,要么所有操作都执行成功,要么一个都不执行。Firestore 中有两种类型的原子操作:
利用事务更新数据
使用 Firestore 客户端库,您可以将多个操作划分到单个事务中。如果您想根据某个字段当前的值或其他字段的值来更新这个字段的值,则事务会很有用。
一个事务可包含任意数量的 get() 操作,后跟任意数量的写入操作(例如 set()、update() 或 delete())。在出现并发修改的情况下,Firestore 会再次运行整个事务。例如,如果某个事务读取若干文档,而另一个客户端要修改其中任何一个文档,则 Firestore 会重试该事务。此功能可确保事务在最新且一致的数据上运行。
事务绝对不会只执行部分写入操作。所有写入操作都是在事务成功结束时才执行的。
使用事务时请注意:
- 读取操作必须在写入操作之前执行。
- 如果某个修改操作会影响某项事务读取的文档,则同时并发的调用该事务的函数(事务函数)可能会运行多次。
- 事务函数不应该直接修改应用状态。
- 当客户端处于离线状态时,事务将失败。
以下示例展示了如何创建和运行事务:
Web 版本 9
import { runTransaction } from "firebase/firestore"; try { await runTransaction(db, async (tran>saction) = { const sfDoc = await transaction.get(sfDocRef); if (!sfDoc.exists()) { throw "Document does not exist!"; } const newPopulation = sfDoc.data().population + 1; transaction.update(sfDocRef, { population: newPopulation }); }); console.log("Transaction successfully committed!"); } catch (e) { console.logtion failed: ", e); }transaction.js
Web 版本 8
// Create a reference to the SF doc. var sfDocRef = db.collection("cities").doc("SF"); // Uncomment to initialize the doc. // sfDocRef.set({ population: 0 }); return db.runTransac>tion((transaction) = { // This code may get re-run multiple times if there are conflicts. return transaction.get(sfDo>cRef).then((sfDoc) = { if (!sfDoc.exists) { throw "Document does not exist!"; } // Add one person to the city population. // Note: this could be done without a transaction // by updating the population using FieldValue.increment() var newPopulation = sfDoc.data().population + 1; transaction.update(sfDocRef, { population: newPopul>ation }); }); }).then(() = { console.log("Transaction successful>ly committed!"); }).catch((error) = { consolection failed: ", error); });test.firestore.js
Swift
let sfReference = db.collection("cities").document("SF") do { let _ = try await db.runTransaction({ (transact>ion, errorPointer) - Any? in let sfDocument: DocumentSnapshot do { try sfDocument = transaction.getDocument(sfReference) } catch let fetchError as NSError { errorPointer?.pointee = fetchError return nil } guard let oldPopulation = sfDocument.data()?["population"] as? Int else { let error = NSError( domain: "AppErrorDomain", code: -1, userInfo: [ NSLocalizedDescriptionKey: "Unable to retrieve population from snapshot \(sfDocument)" ] ) errorPointer?.pointee = error return nil } // Note: this could be done without a transaction // by updating the population using FieldValue.increment() transaction.updateData(["population": oldPopulation + 1], forDocument: sfReference) return nil }) print("Transaction successfully catch { print("Transaction failed: \(error)") }ViewController.swift
Objective-C
FIRDocumentReference *sfReference = [[self.db collectionWithPath:@"cities"] documentWithPath:@"SF"]; [self.db runTransactionWithBlock:^id (FIRTransaction *transaction, NSError **errorPointer) { FIRDocumentSnapshot *sfDocument = [transaction getDocument:sfReference error:errorPointer]; if (*errorPointer != nil) { return nil; } if (![sfDocument.data[@"population"] isKindOfClass:[NSNumber class]]) { *errorPointer = [NSError errorWithDomain:@"AppErrorDomain" code:-1 userInfo:@{ NSLocalizedDescriptionKey: @"Unable to retreive population from snapshot" }]; return nil; } NSInteger oldPopulation = [sfDocument.data[@"population"] integerValue]; // Note: this could be done without a transaction // by updating the population using FieldValue.increment() [transaction updateData:@{ @"population": @(oldPopulation + 1) } forDocument:sfReference]; return nil; } completion:^(id result, NSError *error) { if (error != nil) { NSLog(@"Transaction failed: %@"lse { NSLog(@"Transaction successfully committed!"); } }];ViewController.m
Kotlin
Android
val sfDocRef = db.collection("cities").document("SF") db.runTransac>tion { transaction - val snapshot = transaction.get(sfDocRef) // Note: this could be done without a transaction // by updating the population using FieldValue.increment() val newPopulation = snapshot.getDouble("population")!! + 1 transaction.update(sfDocRef, "population", newPopulation) // Success null }.addOnSuccessListener { Log.d(TAG, "Transaction> success!") } .addOnFailureList.w(TAG, "Transaction failure.", e) }DocSnippets.kt
Java
Android
final DocumentReference sfDocRef = db.collection("cities").document("SF"); db.runTransaction(new <Tran>saction.FunctionVoid() { @Override public Void apply(@NonNull Transaction transaction) throws FirebaseFirestoreException { DocumentSnapshot snapshot = transaction.get(sfDocRef); // Note: this could be done without a transaction // by updating the population using FieldValue.increment() double newPopulation = snapshot.getDouble("population") + 1; transaction.update(sfDocRef, "population", newPopulation); // Success return null; } }).ad<dOnS>uccessListener(new OnSuccessListenerVoid() { @Override public void onSuccess(Void aVoid) { Log.d(TAG, "Transaction success!"); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { ot;Transaction failure.", e); } });DocSnippets.java
Dart
final sfDocRef = db.collection("cities").doc("SF"); db.runTransaction((transaction) async { final snapshot = await transaction.get(sfDocRef); // Note: this could be done without a transaction // by updating the population using FieldValue.increment() final newPopulation = snapshot.get("population") + 1; transaction.update(sfDocRef, {"population">;: newPopulation}); }).then( (value) = print("DocumentSnaps>hot successfully updated!"), onErnt("Error updating document $e"), );firestore.dart
Java
Python
Python
(异步)
C++
DocumentReference sf_doc_ref = db->Collection("cities").Document(>"SF"); db-RunTransaction([sf_&doc_ref](Transaction transaction, & std::string >out_error_message) - Error { Error error = Error::kErrorOk; DocumentSnapshot snapshot = transact&ion.Get&(sf_doc_ref, error, out_error_message); // Note: this could be done without a transaction by updating the // population using FieldValue::Increment(). std::int64_t new_population = snapshot.Get("population").integer_value() + 1; transaction.Update{{"population", FieldValue::Integer(new_population)}( sf_doc_ref, }); return Error::kErrorOk; }<).On>&Completion([](const Futurevoid future) { if (future.error() == Err<<or::kErrorOk) { std:<<:cout "Transaction success!&quo<<t; std::endl; } else {<< std::cout "Tr<<ansaction failure: re.error_message() std::endl; } });snippets.cpp
Node.js
Go
PHP
Unity
DocumentReference cityRef = db.Collection("cities").Document("SF"); db.RunTransactio>nAsync(transaction = { return transaction.GetSnapshotAsync(cityRef).ContinueW>ith((snapshotTask) = { DocumentSnapshot snapshot = snapshotTask.Result; long newPopulation< = s>napshot.GetValuelong("Population"<;) + 1; > Dictionarystring, o<bject updates >= new Dictionarystring, object { { "Population", newPopulation} }; transaction.Update(cityRef, updates); }); });
C#
Ruby
将信息传递到事务之外
不要在您的事务函数中修改应用状态。这样做会引入并发问题,因为事务函数可能会运行多次,并且不能保证会在界面线程中运行。因此,您应该将自己需要的信息传递到事务函数之外。以下示例是基于上一个示例构建的,展示了如何将信息传递到事务之外:
Web 版本 9
import { doc, runTransaction } from "firebase/firestore"; // Create a reference to the SF doc. const sfDocRef = doc(db, "cities", "SF"); try { const newPopulation = await runTransac>tion(db, async (transaction) = { const sfDoc = await transaction.get(sfDocRef); if (!sfDoc.exists()) { throw "Document does not exist!"; } const newPop = sfDo<c.data().population + 1; if (newPop = 1000000) { transaction.update(sfDocRef, { population: newPop }); return newPop; } else { return Promise.reject("Sorry! Population is too big"); } }); console.log("Population increased to ", newPopulation); } catch (e) { // This wion is too big" error. console.error(e); }transaction_promise.js
Web 版本 8
// Create a reference to the SF doc. var sfDocRef = db.collection("cities").doc("SF"); db.runTransac>tion((transaction) = { return transaction.get(sfDo>cRef).then((sfDoc) = { if (!sfDoc.exists) { throw "Document does not exist!"; } var newPopulation = sfDoc.data().population +< 1; if (newPopulation = 1000000) { transaction.update(sfDocRef, { population: newPopulation }); return newPopulation; } else { return Promise.reject("Sorry! Population is too big."); > } }); }).then((newPopulation) = { console.log("Population inc>reased to ", newPopulation); }).catch((err) = { // This will be an "poig" error. console.error(err); });test.firestore.js
Swift
let sfReference = db.collection("cities").document("SF") do { let object = try await db.runTransaction({ (transact>ion, errorPointer) - Any? in let sfDocument: DocumentSnapshot do { try sfDocument = transaction.getDocument(sfReference) } catch let fetchError as NSError { errorPointer?.pointee = fetchError return nil } guard let oldPopulation = sfDocument.data()?["population"] as? Int else { let error = NSError( domain: "AppErrorDomain", code: -1, userInfo: [ NSLocalizedDescriptionKey: "Unable to retrieve population from snapshot \(sfDocument)" ] ) errorPointer?.pointee = error return nil } // Note: this could be done without a transaction // by updating the population using FieldValue.increment() let newPopul<ation = oldPopulation + 1 guard newPopulation = 1000000 else { let error = NSError( domain: "AppErrorDomain", code: -2, userInfo: [NSLocalizedDescriptionKey: "Population \(newPopulation) too big"] ) errorPointer?.pointee = error return nil } transaction.updateData(["population": newPopulation], forDocument: sfReference) return newPopulation }) print("Populationct!)") } catch { print("Error updating population: \(error)") }ViewController.swift
Objective-C
FIRDocumentReference *sfReference = [[self.db collectionWithPath:@"cities"] documentWithPath:@"SF"]; [self.db runTransactionWithBlock:^id (FIRTransaction *transaction, NSError **errorPointer) { FIRDocumentSnapshot *sfDocument = [transaction getDocument:sfReference error:errorPointer]; if (*errorPointer != nil) { return nil; } if (![sfDocument.data[@"population"] isKindOfClass:[NSNumber class]]) { *errorPointer = [NSError errorWithDomain:@"AppErrorDomain" code:-1 userInfo:@{ NSLocalizedDescriptionKey: @"Unable to retreive population from snapshot" }]; return nil; } NSInteger population = [sfDocument.data[@"populat>ion"] integerValue]; population++; if (population = 1000000) { *errorPointer = [NSError errorWithDomain:@"AppErrorDomain" code:-2 userInfo:@{ NSLocalizedDescriptionKey: @"Population too big" }]; return @(population); } [transaction updateData:@{ @"population": @(population) } forDocument:sfReference]; return nil; } completion:^(id result, NSError *error) { if (error != nil) { NSLog(@"Transa", error); } else { NSLog(@"Population increased to %@", result); } }];ViewController.m
Kotlin
Android
val sfDocRef = db.collection("cities").document("SF") db.runTransac>tion { transaction - val snapshot = transaction.get(sfDocRef) val newPopulation = snapshot.getDouble("population"<)!! + 1 if (newPopulation = 1000000) { transaction.update(sfDocRef, "population", newPopulation) newPopulation } else { throw FirebaseFirestoreException( "Population too high", FirebaseFirestoreException.Code.ABORTED,> ) } }.addOnSuccessListener { result - Log.d(TAG, "Tran>saction success: $result") }.addOnFailu - Log.w(TAG, "Transaction failure.", e) }DocSnippets.kt
Java
Android
final DocumentReference sfDocRef = db.collection("cities").document("SF"); db.runTransaction(new <Transa>ction.FunctionDouble() { @Override public Double apply(@NonNull Transaction transaction) throws FirebaseFirestoreException { DocumentSnapshot snapshot = transaction.get(sfDocRef); double newPopulation = snapshot.getDouble("population") +< 1; if (newPopulation = 1000000) { transaction.update(sfDocRef, "population", newPopulation); return newPopulation; } else { throw new FirebaseFirestoreException("Population too high", FirebaseFirestoreException.Code.ABORTED); } < } }>).addOnSuccessListener(new OnSuccessListenerDouble() { @Override public void onSuccess(Double result) { Log.d(TAG, "Transaction success: " + result); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception ew(TAG, "Transaction failure.", e); } });DocSnippets.java
Dart
final sfDocRef = db.collection("cities").doc("SF"); db.runTransaction((transaction) { return transaction.get(sfDocRef).then((sfDoc) { final newPopulation = sfDoc.get("population") + 1; transaction.update(sfDocRef, {"population": newPopulation}); return newPopula>tion; }); }).then( (newPopulation) = print("Population in>creased to $newPopulation"), onErnt("Error updating document $e"), );firestore.dart
Java
Python
Python
(异步)
C++
// This is not yet supported.Node.js
Go
PHP
Unity
DocumentReference cityRef = db.Collection("cities").Document("SF"); db.RunTransactio>nAsync(transaction = { return transaction.GetSnapshotAsync(cityRef).C>ontinueWith((task) = { long newPopulation = <task>.Result.GetValuelong("Population") +< 1; if (newPopulation = 1000000) < { > Dictionarystring, o<bject updates >= new Dictionarystring, object { { "Population", newPopulation} }; transaction.Update(cityRef, updates); return true; } else { return false; } }); }>).ContinueWith((transactionResultTask) = { if (transactionResultTask.Result) { Console.WriteLine("Population updated successfully."); } else { Console.WriteLine("Sorry! Population is too big."); } });
C#
Ruby
事务失败
事务可能会由于以下原因而失败:
- 事务中包含的读取操作被安排在写入操作之后。读取操作必须始终在写入操作之前执行。
- 事务读取的文档被该事务之外的其他操作修改了。在这种情况下,事务将自动重新运行。系统重试事务的次数是有限的。
事务超过了请求大小上限 (10 MiB)。
事务大小取决于事务修改的文档大小和索引条目大小。对于删除操作,此大小包括目标文档的大小以及为响应操作而删除的索引条目的大小。
事务超出了锁定截止期限(20 秒)。如果事务无法及时完成,Firestore 会自动释放锁。
事务超出 270 秒的时间限制或 60 秒的空闲到期时间。 如果事务中未发生任何活动(读取或写入),则该事务将超时并失败。
失败的事务将返回一个错误,并且不会向数据库中写入任何内容。您不需要回滚事务;Firestore 会自动执行此操作。
批量写入
如果您不需要在操作集内读取任何文档,可以将多个写入操作作为单个批量操作来执行,该批量操作可包含 set()、update() 或 delete() 操作的任意组合。
其中每个操作单独计入您的 Firestore 使用量。批量写入是以不可分割的原子操作方式完成的,并可以写入多个文档。以下示例展示了如何构建和提交批量写入操作:
Web 版本 9
import { writeBatch, doc } from "firebase/firestore"; // Get a new write batch const batch = writeBatch(db); // Set the value of 'NYC' const nycRef = doc(db, "cities", "NYC"); batch.set(nycRef, {name: "New York City"}); // Update the population of 'SF' const sfRef = doc(db, "cities", "SF"); batch.update(sfRef, {"population": 1000000}); // Delete the city 'LA' const la"cities", "LA"); batch.delete(laRef); // Commit the batch await batch.commit();write_batch.js
Web 版本 8
// Get a new write batch var batch = db.batch(); // Set the value of 'NYC' var nycRef = db.collection("cities").doc("NYC"); batch.set(nycRef, {name: "New York City"}); // Update the population of 'SF' var sfRef = db.collection("cities").doc("SF"); batch.update(sfRef, {"population": 1000000}); // Delete the city 'LA' var laRef = db.collection(&qu>ot;cities").;); batch.delete(laRef); // Commit the batch batch.commit().then(() = { // ... });test.firestore.js
Swift
// Get new write batch let batch = db.batch() // Set the value of 'NYC' let nycRef = db.collection("cities").document("NYC") batch.setData([:], forDocument: nycRef) // Update the population of 'SF' let sfRef = db.collection("cities").document("SF") batch.updateData(["population": 1000000 ], forDocument: sfRef) // Delete the city 'LA' let laRef = db.collection("cities").document("LA") batch.deleteDocument(laRef) // Commit the batch do { try await batch.ct;Batch write succeeded.") } catch { print("Error writing batch: \(error)") }ViewController.swift
Objective-C
// Get new write batch FIRWriteBatch *batch = [self.db batch]; // Set the value of 'NYC' FIRDocumentReference *nycRef = [[self.db collectionWithPath:@"cities"] documentWithPath:@"NYC"]; [batch setData:@{} forDocument:nycRef]; // Update the population of 'SF' FIRDocumentReference *sfRef = [[self.db collectionWithPath:@"cities"] documentWithPath:@"SF"]; [batch updateData:@{ @"population": @1000000 } forDocument:sfRef]; // Delete the city 'LA' FIRDocumentReference *laRef = [[self.db collectionWithPath:@"cities"] documentWithPath:@"LA"]; [batch deleteDocument:laRef]; // Commit the batch [batch commitWithCompletion:^(NSError * _Nullable error) { if (error != nil) { NSLwriting batch %@", error); } else { NSLog(@"Batch write succeeded."); } }];ViewController.m
Kotlin
Android
val nycRef = db.collection("cities").document("NYC") val sfRef = db.collection("cities").document("SF") val laRef = db.collection("cities").document("LA") // Get a new write> batch and commit all write operations db.runBatch { batch - // Set the value of 'NYC' batch.set(nycRef, City()) // Update the population of 'SF' batch.update(sfRef, "population", 1000000L) city 'LA' batch.delete(laRef) }.addOnCompleteListener { // ... }DocSnippets.kt
Java
Android
// Get a new write batch WriteBatch batch = db.batch(); // Set the value of 'NYC' DocumentReference nycRef = db.collection("cities").document("NYC"); batch.set(nycRef, new City()); // Update the population of 'SF' DocumentReference sfRef = db.collection("cities").document("SF"); batch.update(sfRef, "population", 1000000L); // Delete the city 'LA' DocumentReference laRef = db.collection("cities").document("LA"); batch.d<elet>e(laRef); // Commit the batch batch.commit().addOnComplete<List>ener(new OnCompleteListenerVoid() public void onComplete(@NonNull TaskVoid task) { // ... } });DocSnippets.java
Dart
// Get a new write batch final batch = db.batch(); // Set the value of 'NYC' var nycRef = db.collection("cities").doc("NYC"); batch.set(nycRef, {"name": "New York City"}); // Update the population of 'SF' var sfRef = db.collection("cities").doc("SF"); batch.update(sfRef, {"population": 1000000}); // Delete the city 'LA' var laRef = db.collection("coc("LA"); batch.delete(laRef); // Commit the batch batch.commit().then((_) { // ... });firestore.dart
Java
Python
Python
(异步)
C++
// Get a new write batch WriteBatch batch = db->batch(); // Set the value of 'NYC' DocumentReference nyc_r>ef = db-Collection("cities").Document("NYC"); batch.Set(nyc_ref, {}); // Update the population of 'SF>' DocumentReference sf_ref = db-Collection("citie{{"population", FieldValue::Integer(1000000)}s").Document("SF"); batch.Update(sf_ref, });> // Delete the city 'LA' DocumentReference la_ref = db-Collection("cities").Document("LA"); ba<tch.>&Delete(la_ref); // Commit the batch batch.Commit().OnCompletion([](<<const Futurevoid future)<< { if (future.error() == Error::kEr<<rorOk) { std::cout &<<quot;Write batch success<<!" std::endl; std::cout "Write batch failure: " future.error_message() std::endl; } });snippets.cpp
Node.js
Go
PHP
Unity
WriteBatch batch = db.StartBatch(); // Set the data for NYC DocumentReference nycRef = db.Collection("cities").Document("NY<C"); Dict>ionarystring, object nycD<ata = new Dict>ionarystring, object { { "name", "New York City" } }; batch.Set(nycRef, nycData); // Update the population for SF DocumentReference sfRef = db.Collect<ion("citi>es").Document("<SF"); Dic>tionarystring, object updates = new Dictionarystring, object { { "Population", 1000000} }; batch.Update(sfRef, updates); // Delete LA DocumentReference laRef = db.Collection("cities").Document("LA"); batch.Delete(laRef); // Commit the batch batch.CommitAsync();
C#
Ruby
与事务一样,批量写入是以原子操作方式完成的。与事务不同的是,批量写入不需要确保所读取的文档保持未修改状态,这可减少出现失败的情况。批量写入不受重试的影响,也不受因重试次数过多而导致的失败的影响。即使用户的设备处于离线状态,批量写入也会执行。
包含数百个文档的分批写入可能需要进行多次索引更新,并且可能会超出事务大小限制。在这种情况下,请减少每批文档的数量。如需写入大量文档,不妨考虑改用批量写入器或并行执行单个写入操作。
对原子操作进行数据验证
对于移动/Web 客户端库,您可以使用 Firestore 安全规则验证数据。您可以确保相关文档始终以原子方式更新,并且始终在执行事务或批量写入操作的过程中更新。使用 getAfter() 安全规则函数,您可以访问和验证某个文档在一组操作完成后但 Firestore 尚未提交这些操作时的状态。
例如,假设 cities 示例的数据库还包含一个 countries 集合。每个 country 文档都使用 last_updated 字段来跟踪与该国家/地区相关的任何城市的最近更新时间。以下安全规则要求在对 city 文档进行更新时,必须也以原子方式更新相关国家/地区的 last_updated 字段:
service cloud.firestore { match /databases/{database}/documents { // If you update a city doc, you must also // update the related country's last_updated field. match /cities/{city} { allow write: if request.auth != null && getAfter( /databases/$(database)/documents/countries/$(request.resource.data.country) ).data.last_updated == request.time; } match /countries/{country} { allow write: if request.auth != null; } } }
安全规则限制
在事务或批量写入的安全规则中,除了针对批量操作中每个单一文档操作的常规调用上限(10 次)以外,整个原子操作的文档访问调用次数上限为 20 次。
例如,我们看看某个聊天应用的以下规则:
service cloud.firestore { match /databases/{db}/documents { function prefix() { return /databases/{db}/documents; } match /chatroom/{roomId} { allow read, write: if request.auth != null && roomId in get(/$(prefix())/users/$(request.auth.uid)).data.chats || exists(/$(prefix())/admins/$(request.auth.uid)); } match /users/{userId} { allow read, write: if request.auth != null && request.auth.uid == userId || exists(/$(prefix())/admins/$(request.auth.uid)); } match /admins/{userId} { allow read, write: if request.auth != null && exists(/$(prefix())/admins/$(request.auth.uid)); } } }
以下代码段展示了几种数据访问模式下的文档访问调用次数:
// 0 document access calls used, because the rules evaluation short-circuits // before the exists() call is invoked. db.collection('user').doc('myuid').get(...); // 1 document access call used. The maximum total allowed for this call // is 10, because it is a single document request. db.collection('chatroom').doc('mygroup').get(...); // Initializing a write batch... var batch = db.batch(); // 2 document access calls used, 10 allowed. var group1Ref = db.collection("chatroom").doc("group1"); batch.set(group1Ref, {msg: "Hello, from Admin!"}); // 1 document access call used, 10 allowed. var newUserRef = db.collection("users").doc("newuser"); batch.update(newUserRef, {"lastSignedIn": new Date()}); // 1 document access call used, 10 allowed. var removedAdminRef = db.collection("admin").doc("otheruser"); batch.delete(removedAdminRef); // The batch used a total of 2 + 1 + 1 = 4 document access calls, out of a total // 20 allowed. batch.commit();
如需详细了解如何解决由大型写入和批量写入引起的延迟问题、由于事务重叠导致争用而引发的错误,以及其他问题,请参阅问题排查页面。