iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
📌

Updating Firestore with Transactions in firebase-admin-python

に公開

Suppose the scenario is that you want to retrieve documents from a collection in order of their updates, but you want to avoid duplicates even when executing in parallel.

Key Points

  1. The scope wrapped with the @firestore.transactional decorator becomes the transaction boundary.
  2. Instruct get/set operations on the firestore.client().transaction() object.

Sample

from firebase_admin import firestore

def dequeue(size):
    db = firestore.client()

    @firestore.transactional
    def get_and_update(transaction):
        docs = db.collection('queue').order_by('updated_at').limit(size).get(transaction=transaction)
        ids = []
        for doc in docs:
            transaction.update(doc.reference, {'updated_at': firestore.SERVER_TIMESTAMP})
            ids.append(doc.id)
        return ids

    ids = get_and_update(db.transaction())
    return ids

Discussion