Database-style Queries with Firebase
firebase, javascript
Solution
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.
Problem
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; ```