事务和批量写入

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
注意:此产品不适用于 watchOS 和 App Clip 目标。
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
注意:此产品不适用于 watchOS 和 App Clip 目标。
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
// Initialize doc
final DocumentReference docRef = db.collection("cities").document("SF");
City city = new City("SF");
city.setCountry("USA");
city.setPopulation(860000L);
docRef.set(city).get();

// r<un a>n asynchronous transaction
ApiFutureVoid futureTransaction =
    >db.runTransaction(
        transaction - {
          // retrieve document and increment population field
          DocumentSnapshot snapshot = transaction.get(docRef).get();
          long oldPopulation = snapshot.getLong("population");
          transaction.update(docRef, "population", oldPopulation + 1);
          return null;
        }ion operation using transaction.get()ManageDataSnippets.java
Python
transaction = db.transaction()
city_ref = db.collection("cities").document("SF")

@firestore.transactional
def update_in_transaction(transaction, city_ref):
    snapshot = city_ref.get(transaction=transaction)
    transaction.update(city_ref, {"population": snapshot.get("population") + 1})

updaaction(transaction, city_ref)snippets.py
Python
(异步)
transaction = db.transaction()
city_ref = db.collection("cities").document("SF")

@firestore.async_transactional
async def update_in_transaction(transaction, city_ref):
    snapshot = await city_ref.get(transaction=transaction)
    transaction.update(city_ref, {"population": snapshot.get("population") + 1})

await updaaction(transaction, city_ref)snippets.py
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
// Initialize document
const cityRef = db.collection('cities').doc('SF');
await cityRef.set({
  name: 'San Francisco',
  state: 'CA',
  country: 'USA',
  capital: false,
  population: 860000
});

try> {
  await db.runTransaction(async (t) = {
    const doc = await t.get(cityRef);

    // Add one person to the city population.
    // Note: this could be done without a transaction
    //       by updating the population using FieldValue.increment()
    const newPopulation = doc.data().population + 1;
    t.update(cityRef, {population: newPopulation});
  });

  console.log('Transaction success!');
} catch (onsole.log('Transaction failure:', e);
}index.js
Go

import (
	"context"
	"log"

	"cloud.google.com/go/firestore"
)

func runSimpleTransaction(ctx context.Context, client *firestore.Client) error {
	// ...

	ref := client.Collection(";cities").Doc("SF")
	err := client.RunTransaction(ctx, func(ctx context.Context, tx *firestore.Transaction) error {
		doc, err := tx.Get(ref) // tx.Get, NOT ref.Get!
		if err != nil {
			return err
		}
		pop, err := doc.DataAt("population")
		if err != nil {
			return err
		}
		return tx.Set(ref, map[string]interface{}{
			"population": pop.(int64) + 1,
		}, firestore.MergeAll)
	})
	if err != nil {
		// Handle any errors appropriately in this sects occurred: %s", err)
	}

	return err
}
save_transaction_document_update.go
PHP
$cityRef = $db->collection('samples/php/citie>s')-document(>9;SF');
$db-runTransaction(function (Transaction $transaction) use ($cityRef) {
    $snapshot> = $transaction-snapshot($cityRef);
    $newPopulation = $snapshot['population'>] + 1;
    $transaction-update($city>Ref, [
        ['pat>h' = 'population'tion]
    ]);
});transaction_document_update.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#
DocumentReference cityRef = db.Collection("cities").Document("SF");
await db.RunTransactionAsync>(async transaction =
{
    DocumentSnapshot snapshot = await transaction.GetSnapshotAsync(cityRef);
    long newPopulation< = s>napshot.GetValuelong("Populat<ion") + 1>;
    Dictionarystring, o<bject updates >= new Dictionarystring, object
    {
        { "Population", newPopulation}
    };
    t.Update(cityRef, updates);
});Program.cs
Ruby
city_ref = firestore.doc "#{collection_path}/SF"

firestore.transaction do |tx|
  new_population = tx.get(city_ref).data[:population] + 1
  puts "New population is #{new_population}."
  tx.update city_ref, { population: nd_batched_writes.rb

将信息传递到事务之外

不要在您的事务函数中修改应用状态。这样做会引入并发问题,因为事务函数可能会运行多次,并且不能保证会在界面线程中运行。因此,您应该将自己需要的信息传递到事务函数之外。以下示例是基于上一个示例构建的,展示了如何将信息传递到事务之外:

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
注意:此产品不适用于 watchOS 和 App Clip 目标。
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
注意:此产品不适用于 watchOS 和 App Clip 目标。
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
final DocumentReference docRef = db.collection("cities").document("<SF&quo>t;);
ApiFutureString futureTransaction =
    db.runTransaction(
 >       transaction - {
          DocumentSnapshot snapshot = transaction.get(docRef).get();
          Long newPopulation = snapshot.getLong("population") + 1;
          // conditionally update based on current populatio<n
          if (newPopulation = 1000000L) {
            transaction.update(docRef, "population", newPopulation);
            return "Population increased to " + newPopulation;
          } else {
            throw new Exception("Sorry! Population is too big.");
          }
        });
// Print information retrieved fout.println(futureTransaction.get());ManageDataSnippets.java
Python
transaction = db.transaction()
city_ref = db.collection("cities").document("SF")

@firestore.transactional
def update_in_transaction(transaction, city_ref):
    snapshot = city_ref.get(transaction=transaction)
    new_population = snapshot.get("population"<;) + 1

    if new_population  1000000:
        transaction.update(city_ref, {"population": new_population})
        return True
    else:
        return False

result = update_in_transaction(transaction, city_ref)
if result:
    print("Population updated" print("Sorry! Population is too big.")snippets.py
Python
(异步)
transaction = db.transaction()
city_ref = db.collection("cities").document("SF")

@firestore.async_transactional
async def update_in_transaction(transaction, city_ref):
    snapshot = await city_ref.get(transaction=transaction)
    new_population = snapshot.get("population"<;) + 1

    if new_population  1000000:
        transaction.update(city_ref, {"population": new_population})
        return True
    else:
        return False

result = await update_in_transaction(transaction, city_ref)
if result:
    print("Population updated" print("Sorry! Population is too big.")snippets.py
C++
// This is not yet supported.
Node.js
const cityRef = db.collection('cities').doc('SF');
try {
  const res = await db.runTrans>action(async t = {
    const doc = await t.get(cityRef);
    const newPopulation = doc.data().population + 1;
    if< (newPopulation = 1000000) {
      await t.update(cityRef, { population: newPopulation });
      return `Population increased to ${newPopulation}`;
    } else {
      throw 'Sorry! Population is too big.';
    }
  });
  console.log('Transaction success', res);
} catch (e) {
  console.lTransaction failure:', e);
}index.js
Go

import (
	"context"
	"errors"
	"log"

	"cloud.google.com/go/firestore"
)

func infoTransaction(ctx context.Context, client *firestore.Client) (int64, error) {
	var updatedPop int64
	ref := client.Collection("cities").Doc("SF")
	err := client.RunTransaction(ctx, func(ctx context.Context, tx *firestore.Transaction) error {
		doc, err := tx.Get(ref)
		if err != nil {
			return err
		}
		pop, err := doc.DataAt("population")
		if e<rr != nil {
			return err
		}
		newpop := pop.(int64) + 1
		if newpop = 1000000 {
			err := tx.Set(ref, map[string]interface{}{
				"population": newpop,
			}, firestore.MergeAll)
			if err == nil {
				updatedPop = newpop
			}
			return err
		}
		return errors.New("population is too big")
	})
	if err != nil {
		// Handle any errors in an appropriate way, such as reccurred: %s", err)
	}
	return updatedPop, err
}
save_transaction_document_update_conditional.go
PHP
$cityRef = $db->collection('samples/php/citie>s')-document('SF');
$transact>ionResult = $db-runTransaction(function (Transaction $transaction) use ($cityRef) {
    $snapshot> = $transaction-snapshot($cityRef);
    $newPopulation = $snapshot['population'] + 1;<
    if ($newPopulation = 1000000)> {
        $transaction-update($cityRef,> [
            ['pat>h' = 'population', 'value' = $newPopulation]
        ]);
        return true;
    } else {
        return false;
    }
});

if ($transactionResult) {
    printf('Population updated successfully.' . PHP_EOL);
} else {
g.' . PHP_EOL);
}transaction_document_update_conditional.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#
DocumentReference cityRef = db.Collection("cities").Document("SF");
bool transactionResult = await db.RunTransactionAsync>(async transaction =
{
    DocumentSnapshot snapshot = await transaction.GetSnapshotAsync(cityRef);
    long newPopulation< = s>napshot.GetValuelong("Population"<;) + 1;
    if (newPopulation = 100<0000)
    {
  >      Dictionarystring, o<bject updates >= new Dictionarystring, object
        {
            { "Population", newPopulation}
        };
        transaction.Update(cityRef, updates);
        return true;
    }
    else
    {
        return false;
    }
});

if (transactionResult)
{
    Console.WriteLine("Population updated successfully.");
}
else
{
    ConLine("Sorry! Population is too big.");
}Program.cs
Ruby
city_ref = firestore.doc "#{collection_path}/SF"

updated = firestore.transaction do |tx|
  new_population = tx.get(city_ref).data[:population] + 1
  if new_p<opulation  1_000_000
    tx.update city_ref, { population: new_population }
    true
  end
end

if updated
  puts "Population updated!"
else
  puts "Sorry! Posactions_and_batched_writes.rb

事务失败

事务可能会由于以下原因而失败:

  • 事务中包含的读取操作被安排在写入操作之后。读取操作必须始终在写入操作之前执行。
  • 事务读取的文档被该事务之外的其他操作修改了。在这种情况下,事务将自动重新运行。系统重试事务的次数是有限的。
  • 事务超过了请求大小上限 (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
注意:此产品不适用于 watchOS 和 App Clip 目标。
// 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
注意:此产品不适用于 watchOS 和 App Clip 目标。
// 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
// 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"<).do<cument(&quo>>t;LA");
batch.delete(laRef);

// asynchronously commit the batch
ApiFutureListWriteResult future = batch.commit();
// ...
// future.get() blocks on batch commit operation
for (WriteResu)) {
  System.out.println("Update time : " + result.getUpdateTime());
}ManageDataSnippets.java
Python
batch = db.batch()

# Set the data for NYC
nyc_ref = db.collection("cities").document("NYC")
batch.set(nyc_ref, {"name": "New York City"})

# Update the population for SF
sf_ref = db.collection("cities").document("SF")
batch.update(sf_ref, {"population": 1000000})

# Delete DEN
den_ref = db.collection("citiesument("DEN")
batch.delete(den_ref)

# Commit the batch
batch.commit()snippets.py
Python
(异步)
batch = db.batch()

# Set the data for NYC
nyc_ref = db.collection("cities").document("NYC")
batch.set(nyc_ref, {"name": "New York City"})

# Update the population for SF
sf_ref = db.collection("cities").document("SF")
batch.update(sf_ref, {"population": 1000000})

# Delete DEN
den_ref = db.collection("cities""DEN")
batch.delete(den_ref)

# Commit the batch
await batch.commit()snippets.py
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
// Get a new write batch
const batch = db.batch();

// Set the value of 'NYC'
const nycRef = db.collection('cities').doc('NYC');
batch.set(nycRef, {name: 'New York City'});

// Update the population of 'SF'
const sfRef = db.collection('cities').doc('SF');
batch.update(sfRef, {population: 1000000});

// Delete the city 'LA'
const laRef = db.collection('cities').doA');
batch.delete(laRef);

// Commit the batch
await batch.commit();index.js
Go

import (
	"context"
	"log"

	"cloud.google.com/go/firestore"
)

func batchWrite(ctx context.Context, client *firestore.Client) error {
	// Get a new write batch.
	batch := client.Batch()

	// Set the value of "NYC".
	nycRef := client.Collection("cities").Doc("NYC")
	batch.Set(nycRef, map[string]interface{}{
		"name": "New York City",
	})

	// Update the population of "SF".
	sfRef := client.Collection("cities").Doc("SF")
	batch.Set(sfRef, map[string]interface{}{
		"population": 1000000,
	}, firestore.MergeAll)

	// Delete the city "LA".
	laRef := client.Collection("cities").Doc("LA")
	batch.Delete(laRef)

	// Commit the batch.
	_, err := batch.Commit(ctx)
	ie any errors in an appropriate way, such as returning them.
		log.Printf("An error has occurred: %s", err)
	}

	return err
}
save_data_batch_writes.go
PHP
$batch = $db->bulkWriter();

# Set the data for NYC
$nycRef = $db->collection('samples/php/citie>s')-document('NY>C');
$batch-set($nycRef>, [
    'name' = 'New York City'
]);

# Update the> population for SF
$sfRef = $db-c>ollection('samples/>php/cities')-document('>;SF');
$batch-update>($sfRef, [
    ['path' = 'po>pulation', 'value' = >1000000]
]);

# Delete >LA
$laRef = $db-collection('samples/php>/cities&#');
$batch-delete($laRef);

# Commit the batch
$batch-commit();data_batch_writes.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#
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").Docu;LA");
batch.Delete(laRef);

// Commit the batch
await batch.CommitAsync();Program.cs
Ruby
firestore.batch do |b|
  # Set the data for NYC
  b.set "#{collection_path}/NYC", { name: "New York City" }

  # Update the population for SF
  b.update "#{collection_path}/SF", { population: 1_000_000 }

  # Delete LA
  b.delet;
endtransactions_and_batched_writes.rb

与事务一样,批量写入是以原子操作方式完成的。与事务不同的是,批量写入不需要确保所读取的文档保持未修改状态,这可减少出现失败的情况。批量写入不受重试的影响,也不受因重试次数过多而导致的失败的影响。即使用户的设备处于离线状态,批量写入也会执行。

包含数百个文档的分批写入可能需要进行多次索引更新,并且可能会超出事务大小限制。在这种情况下,请减少每批文档的数量。如需写入大量文档,不妨考虑改用批量写入器或并行执行单个写入操作。

对原子操作进行数据验证

对于移动/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();

如需详细了解如何解决由大型写入和批量写入引起的延迟问题、由于事务重叠导致争用而引发的错误,以及其他问题,请参阅问题排查页面