简体   繁体   中英

Are Firestore transactions on multiple documents more efficient than updating each document one by one?

I have two different ways I can go through my database and update each document. There's this:

Firestore db = FirestoreClient.getFirestore();
    //get all documents where expiresOn is already passed
    ApiFuture<QuerySnapshot> future = db.collection("devices").whereLessThan("expiresOn", new Date()).get();
    List<QueryDocumentSnapshot> documents = future.get().getDocuments();
    for (DocumentSnapshot document : documents){
        logger.info(document.getId() + " => " + document.getData().toString());
        HashMap<String, Object> data = new HashMap<>();
        data.put("expiresOn", null);
        data.put("boughtUses", 0);
        document.getReference().update(data);
    }

or this:

    ApiFuture<String> transaction = db.runTransaction(
            new Transaction.Function<String>() {
                @Override
                public String updateCallback(Transaction transaction) throws Exception {
                    ApiFuture<QuerySnapshot> future = transaction.get(db.collection("devices").whereLessThan("expiresOn", new Date()));
                    List<QueryDocumentSnapshot> documents = future.get().getDocuments();
                    for (DocumentSnapshot document : documents){
                        HashMap<String, Object> data = new HashMap<>();
                        data.put("expiresOn", null);
                        data.put("boughtUses", 0);
                        transaction.update(document.getReference(), data);
                    }
                    return null;
                }
            }
    );
    logger.info(transaction.get());

In the first, I'm calling DocumentReference.update(), and in the second, I'm calling Transaction.update(). I know that DocumentReference.update() is called one by one, but what about Transaction.update()? Is that also going to be called one by one, or is it going to group all the writes together? Also, if it does group them, does it count as less writes for my usage?

I know that DocumentReference.update() is called one by one

That's correct.

Is that also going to be called one by one, or is it going to group all the writes together?

It will also be called one by one.

Also, if it does group them, does it count as less writes for my usage?

If think that the writes will be grouped together and you'll be charged only for a single write operation, no, you'll be charged one by one, for each document that you'll update.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM