Search code examples
collectionsgoogle-cloud-firestoretradeoff

Advantages of firestore sub-collections


The firestore docs don't have an in depth discussion of the tradeoffs involved in using sub-collections vs top-level collections, but do point out that they are less flexible and less 'scalable'. Given that you sacrifice flexibility in setting up your data in sub-collections, there must be some definite plus sides besides a mentally satisfying structure.

For example how does the time for a firestore query on a single key across a large collection compare with getting all items from a much smaller collection?

Say we want to query a large collection 'People' for all people in a family unit. Alternatively, partition the data by family in the first place into family units.

People -> person: {family: 'Smith'}

versus

Families -> family: {name:'Smith'} -> People -> person

I would expect the latter to be more efficient, but is this correct? Are the any big-O estimates for each? Any other advantages of sub-collections (eg for transactions)?


Solution

  • I’ ve got some key points about subcollections that you need to be aware of when modeling your database.

    1 – Subcollections give you a more structured database.

    2 - Queries are indexed by default: Query performance is proportional to the size of your result set, not your data set. So does not matter the size of your collection, the performance depends on the size of your result set.

    3 – Each document has a max size of 1MB. For instance, if you have an array of orders in your customer document, it might be a good idea to create a subcollection of orders to each customer because you cannot foresee how many orders a customer will have. By doing this you don’t need to worry about the max size of your document.

    4 – Pricing: Firestore charges you for document reads, writes and deletes. Therefore, when you create many subcollections instead of using arrays in the documents, you will need to perform more read, writes and deletes, thus increasing your bill.