Home > Enterprise >  How to retrieve all documents from a collection in Firestore optimizing reads?
How to retrieve all documents from a collection in Firestore optimizing reads?

Time:09-28

Basically I'm having an issue with the amount of reads that I get from using the following code:

 public Iterable<Contract> findAllExpired(){
    List<Contract> empList = new ArrayList<Contract>();
    CollectionReference collaborator = fb.getFirestore().collection("Contracts");
    ApiFuture<QuerySnapshot> querySnapshot = collaborator.get();
    try {
        for (DocumentSnapshot doc : querySnapshot.get().getDocuments()) {   
            Contract emp = doc.toObject(Contract.class);
            if (emp.isExpired()) {
                empList.add(emp);
            }
        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
    }

Currently, I have 30 documents in my DB, is there a way in which I can retrieve those documents without causing the Firestore to count the query as 30 reads but as only one?

CodePudding user response:

Firestore charges for document reads, so if you're reading 30 documents from the server, you will be charged for 30 document reads.

If you want to read fewer documents, consider merging the information from those 30 documents into fewer documents. For example, if you add a "30 most recent contracts" document to the collection, with information about the 30 most recent contracts, you will only need to read that one document to get the information.

CodePudding user response:

You're reading all 30 documents, because you have created a CollectionReference object and not a Query. A CollectionReference is basically a query without any constraints. When you're attaching a listener to it, you're getting as a result, all the documents that exist in that particular collection. If you want to read fewer documents, as also @FrankvanPuffelen mentioned in his answer, you can merge that data in fewer documents, or even in a single document if it fits in the 1 Mib document maximum limitation, or, you can limit the amount of data that you get, by calling Query#limit(long limit) which:

Creates and returns a new Query that only returns the first matching documents up to the specified number.

In addition, if you intend to add to your collection a number of documents that is much bigger than a user can see/read, then I recommend you implement pagination, as explained in my answer from the following post:

It's for Android, but almost the same mechanism can be used when creating apps with Java.

  • Related