Thijs Koerselman
Thijs Koerselman

Reputation: 23271

How to do batched writes as part of a transaction

I found myself in a situation where I want to perform some operations on the database that should be handled in a single transaction. One of those operations is injecting > 500 documents, so this is throwing an error because it's hitting

maximum 500 writes allowed per request

In order to work around that, you could use batched writes, but I can't figure out how to do batched writes as part of a transaction. It seems like transaction.commit() is not a thing and in the docs transactions and batched writes appear to be two separate concepts.

Upvotes: 1

Views: 1348

Answers (2)

Alex Mamo
Alex Mamo

Reputation: 138814

Generally speaking, we are using transactions to have consistent data. The recommendation that you get:

you could use batched writes

It is for the exact same reason. Unfortunately, you cannot mix them. You have to choose one or the other. Realistic speaking, both the batch and the transaction are used for atomic updates.

A transaction is similar to batch and as the docs states:

All of the operations succeed, or none of them are applied.

The main difference between a batch write and a transaction is that a batch just writes, while a transaction reads and right after then writes.

So the solution in your case is to use Firestore batched-writes to perform 500 operation at a time.

Upvotes: 4

Renaud Tarnec
Renaud Tarnec

Reputation: 83058

As you have most probably read in the doc:

The Transaction object passed to a transaction's updateFunction provides the methods to read and write data within the transaction context.

and this object, in the Client SDKs, has only four methods: get(), set(), update() and delete() which all take a single Firestore Document as parameter.

With the Node.js Server SDK for Google Cloud Firestore, you will note that there is an additional method, getAll(), which "retrieves multiple documents from Firestore. Holds a pessimistic lock on all returned documents".


So, at the time of writing, there is no possibility, to "mix" a Transaction and a Batched Write.

Upvotes: 0

Related Questions