Vinicius S.
Vinicius S.

Reputation: 75

Writing to same document in a WriteBatch causes multiple writes in Firebase?

I want to know if, in Firebase, I perform multiple updates to the same document in a batch, will it cause a single write or multiple writes?

For instance, in this example code (in javascript):

const doc = getDocumentReference();
batch.update(doc, { foo: "a" });
batch.update(doc, { bar: "b" });
batch.commit();

Will there be a single write to the document updating everything or there will be two writes, one for each update?

Does the answer change if one of the two operations is a "set" instead of an "update"?

Thanks in advance

Upvotes: 3

Views: 356

Answers (1)

vitooh
vitooh

Reputation: 4262

I haven't found any reference how the writes are counted, but I found it interesting and tried to figure it out by myself. I prepared test and looked on Metrics explorer on Google Cloud Platform (Firebase database are visible there as well) and it can show the writes_count.

I prepared following codes:

adding whole object at once:

let test = db.collection("test").doc("sdaasd3")
test.set({})

let update = {}
for (let i = 0; i < 100; i++) {
    update[i.toString()] = i;
}
test.update(update);

Then updating 100 times:

let test = db.collection("test").doc("sdaasd2")
test.set({})

for (let i = 0; i < 100; i++) {
    let update = {}
    update[i.toString()] = i;
    test.update(update)
}

And in by batch commit:

let test = db.collection("test").doc("sdaasd")
test.set({})
const batch = db.batch();


for (let i = 0; i < 100; i++) {
    let update = {}
    update[i.toString()] = i;
    batch.update(test, update)
}
batch.commit();

I performed them and it seems that batch commit is exactly the same as updating whole object at once and it takes 2 writes (I think one is set which I used to clear object in Firebase). While updating 100 times took 101 writes. Here as it looks (executed in order like in the post 12:57,01:01,01:07)

Test results

I am not sure, if this test was reliable enough to your needs, but you can use the Matrix explorer on GCP to analyze that on your own.

Upvotes: 2

Related Questions