javascriptperformancegoogle-cloud-firestorenon-relational-database

How to select multiple document references in a single query?


I have two Firestore collections, one called parents and one called children. These collections are "related" in that parents have an array of child document references attached to them.

What I want to accomplish is: Get all children that are "related" to a single parent in a performant way.

What I tried: I came up with this code that works great functionally:

this.subscription = this.props.firebase.parent().onSnapshot((parent) => { // get a single parent

    let childrenPromises = (parent.data().children || []).map(child => this.props.firebase.child(child.id).get()); // build array of promises

    Promise.all(childPromises) // resolve all promises
        .then(children => {
            // children.data() has the data I need :)
        });
});

To summarize: I retrieve the list of child document references, and then using promises retrieve all of them individually. This works great, but bombards my db with query requests.

What I want to improve: Can I refactor this somehow into a single, more performant query? Ideally, it would be a single query to prevent so many requests against the db.

What I have tried: I have read through all of the Firestore docs and Stack Overflow posts I could find with no luck. I did read that de-normalizing the db is an option, but I would rather not, since multiple parents can by tied to children.

Any help or advice here is appreciated. Thanks!


Solution

  • No, it's not possible to query across differently-named collections in a single query. There is no "join" type operation.

    What are you are doing now is not really "bombarding" Firestore. It is built to keep up with many document reads, and all queries are pipelined over a single connection. There is not really an issue with performance or scalability here, unless you are requesting more data than you need. In fact, Cloud Firestore will simply not allow you to do anything that doesn't scale. All indexed operations scale massively.