Reputation: 33
My Firebase Database has got to following data:
datas=[
{ "category" : "Content Server", "hits" : 1, "bytes" : 17308 },
{ "category" : "Content Server", "hits" : 1, "bytes" : 47412 },
{ "category" : "Search Engines", "hits" : 1, "bytes" : 7601 },
{ "category" : "Content Server", "hits" : 1, "bytes" : 24210 },
{ "category" : "Internet Services", "hits" : 1, "bytes" : 3690 },
{ "category" : "Search Engines", "hits" : 6, "bytes" : 613036 },
{ "category" : "Search Engines", "hits" : 1, "bytes" : 2858 }
];
How can we make in Firebase Database equivalent of this SQL query?:
SELECT category, sum(hits), sum(bytes)
FROM datas
GROUP BY category
Upvotes: 3
Views: 3239
Reputation: 599766
Firebase is a NoSQL database. Trying to 1:1 map SQL paradigms to a NoSQL database is a guaranteed way to cause you pain.
Most NoSQL databases have more limited querying abilities and Firebase is definitely not exception to that. This means that you'll often have to model your data in a way that allows the queries that your application needs.
For this specific use-case, I'd recommend modifying the data structure to reflect the actual hierarchy and aggregate data you are trying to access:
categoryAggregates:
"Content Server": { hitsCount: 3, bytesCount: 88930 }
"Internet Services": { hitsCount: 1, bytesCount: 3690 }
"Search Engines": { hitsCount: 3, bytesCount: 1233673 }
Adding such a structure ends up duplicating the data and makes updating it more complex/expensive. But you can probably imagine that accessing the aggregates becomes dead-cheap with such a structure. This again is a common pattern with NoSQL databases, they're optimized for read-performance at the cost of more complicated/expensive writes.
I recommend reading about NoSQL data modeling first, watching our video series Firebase for SQL developers next and then reading some of the questions that have already tried this.
Upvotes: 3