Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Database-style Queries with Firebase

Is there a fast way to perform database-style queries with Firebase?

For example:

Given a firebase reference users with fields user_id, name, and age, what would be the best way to do a query similar to this:

SELECT name FROM users WHERE `user_id`=147; 

and

SELECT COUNT(*) FROM users WHERE age=21; 
like image 252
Matt Robertson Avatar asked Jul 20 '12 22:07

Matt Robertson


People also ask

Is Firebase good for queries?

If your data model needs something more than a single join query, never choose firebase. It is highly suggested not to choose Firebase for android application if your intended operation is to perform deep and complex querying.

Can I use SQL with Firebase?

It is not possible to use Firebase in this way. Firebase is a real-time object store. It is not a SQL database and is not intended to be a replacement for one. It completely lacks mechanisms such as JOINs, WHERE query filters, foreign keys, and other tools relational databases all provide.

Does Firebase have schema?

Firebase security rules, this video does an amazing job explaining them, are a way in which you can sort of create schemas. An important consideration when using these rules is that if you're using the Firestore Admin SDK (used for backend code) then your rules will be bypassed.


1 Answers

In general, no. Firebase is essentially a "realtime database", constantly streaming updates to you as data changes, so it's more difficult to do general-purpose querying. For now, there are a couple of (admittedly limited) querying primitives that are provided. See the Queries/Limits page in the docs.

You can often work around these limitations through a variety of approaches:

  • Use location names and priorities intelligently. If you structure your data as /users/[userid]/name, you can accomplish your first "query" by just retrieving /users/147/name. If you know you'll want to query by age, you can use age as the priority for user nodes and then do "usersRef.startAt(21).endAt(21).on('child_added', ...)" to get all users age 21. You still have to count them manually.
  • Do client-side querying. If the entire data set is smallish, you may be able to retrieve the entire data set and then filter / process it manually on the client.
  • Run a separate server. It can connect to Firebase, sync data and then answer "queries" for clients. It can still communicate to clients through Firebase, and Firebase can still be the primary data store, but your separate server can do the work to perform queries quickly.

We intend to improve on this over time, as we realize it's a weak spot compared to the flexible querying provided by traditional relational database systems.

like image 105
Michael Lehenbauer Avatar answered Sep 22 '22 06:09

Michael Lehenbauer