Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to batch read firebase documents

I am making a mobile app using flutter with firebase as my backend.

I have a collection of user document that stores user information. one of the fields is an array of references (reference documents in another collection) which I want to use in an operation like batch that in that would then allow be to read all the documents.

I know batch only allows writes to the database, My second option would be Transaction, which requires writes after reads which I am trying to avoid.

Is there a way to read multiple documents in one operation without having to use Transaction?

like image 947
William Avatar asked Jan 03 '20 03:01

William


People also ask

How do I read firestore files?

To read a single document, we can use DocumentReference's get() method that returns a Task<DocumentSnapshot>, while reading multiple documents from a collection or Query, we can use Firestore Query's get() method that returns an object of type Task<QuerySnapshot>. Both methods read the data only once.

Which function is used to fetch data from the Firebase document?

The Get() function in Go unmarshals the data into a given data structure. Notice that we used the value event type in the example above, which reads the entire contents of a Firebase database reference, even if only one piece of data changed.

What is Firebase batch?

There are two types of atomic operations in Cloud Firestore: Transactions: a transaction is a set of read and write operations on one or more documents. Batched Writes: a batched write is a set of write operations on one or more documents.

How many reads can firestore handle?

10 for single-document requests and query requests. 20 for multi-document reads, transactions, and batched writes. The previous limit of 10 also applies to each operation.


2 Answers

Firestore doesn't offer a formal batch read API. As Frank mentions in his comment, there is a way to use IN to fetch multiple documents from a single collection using their IDs. However, all of the documents must be in the same collection, and you can't exceed 10 documents per query. You might as well just get() for each document individually, as the IN query has limitations, and isn't guaranteed to execute any faster than the individual gets. Neither solution is guaranteed to be "consistent", so any one of the documents fetched could be "more fresh" than the others at any given moment in time.

like image 98
Doug Stevenson Avatar answered Sep 18 '22 07:09

Doug Stevenson


Firestore has a REST API that allows you to do batch GETs with document paths that may be what you need.

See https://firebase.google.com/docs/firestore/reference/rest/v1beta1/projects.databases.documents/batchGet

like image 35
Jacob Wright Avatar answered Sep 21 '22 07:09

Jacob Wright