What is really this denormalization all about when talking about Firebase Cloud Firestore? I read a few articles on the internet and some answers here on stackoverflow and most of the answers recommend this approach. How does this denormalization really help? Is it always necessary?
Is database flatten and denormalization the same thing?
It's my fist question and hope I'll find an answer that can help me understand the concept. I know is different, but I have two years of experience in MySQL.
The denormalization is not related only to Cloud Firestore, is a tehnique generally used in NoSQL databases.
Denormalization is the process of optimizing the performance of a NoSQL databases, by adding redundant data in other different places in the database. What I mean with adding redundant data, as @FrankvanPuffelen already mentioned in his comment, it means that we copy the exact same data that already exists in one place, in another place, to suit queries that may not even be possible otherwise. So denormalization helps cover up the inefficiencies inherent in relational databases.
Yes it does. It's also a quite common practice when it comes to Firebase because data duplication is the key to faster reads. I see you're new to NoSQL database, so for a better understanding, I recommend you see this video, Denormalization is normal with the Firebase Database. It's for Firebase realtime database but same principles apply to Cloud Firestore.
We don't use denormalization just for the sake of using it. We use it, only when it is definitely needed.
Let's take an example for that. Let's assume we have a database schema for a quiz app that looks like this:
We can flatten the database by simply moving the
tags
collection in a separate top-level collection like this:Now, to get all the tags that correspond to a specific question, you need to simply query the
tags
collection where the thequestionId
property holds the desired question id.Or you can flatten and denormalize the database in the same time, as you can see in the following schema:
See, the tag objects are the same as well in
users -> uid -> tags -> tagId
as intags -> tagId
. So we flatten data to group somehow existing data.For more information you can also take a look at:
Because you say you have a SQL background, try to think at a normalized design which will often store different but related pieces of data in separate logical tables, which are called relations. If these relations are stored physically as separate disk files, completing a query that draws information from several relations (join operations) can be slow. If many relations are joined, it may be prohibitively slow. Because in NoSQL databases, we do not have "JOIN" clauses, we have to create different workarounds to get the same behaviour.