Home > Software design >  Reducing the amount of reads in a where query
Reducing the amount of reads in a where query

Time:06-11

I have recently implemented firebase into my project and I have created a user collection, this collection has a document for each user and each document has about 8 fields, when my user launches the app, I am trying to pull the document that corresponds to his data, so im doing the following query:

async function getUserData() {
        
        const _collection = collection(db, "users")
        const _query = query(_collection, where("userid", "==", uniqueUserID))
        const querySnapshot = await getDocs(_query)
        querySnapshot.forEach((doc) => {
            console.log(doc.data())
        })
        setLoadingStatus(false)
    }

This query works and gives me the corresponding user data, but the problem is, if the user is too far down the collection, this will execute 8 reads per document until it gets to the corresponding user, I have tried to implement a cache system using a lastModified but I still need to read the document data for that field and it will end up using more or less the same amount of reads. My question is: How do I reduce the amount of read operations that get executed when im trying to compare values in the documents, I have also thought of adding an a like so a_uniqueUserID so it gets ordered alphabetically and takes the first spot of the document but it's hacky. EDIT: Here is what my structure looks like: enter image description here

CodePudding user response:

I think you are misunderstanding the definition of a document and a field. When you read a document, you always get all fields out of it. The snapshot contains everything read, even if you don't use it. There is no additional cost per field, other than the storage required to hold it all. In your screenshot, you show 5 documents, and one of those documents have 8 fields.

You are probably misunderstanding the metrics in the console. When you read and write documents using the console, those are also billed as reads and writes - use of the console is not "free". What you are seeing is a combination of what your app is doing in combination with what you're doing in the console.

  • Related