Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter and sort on multiple values with Firebase

Tags:

firebase

I'm building a social app using Firebase. I store posts in Firebase like this:

posts: {
   "postid": {
      author: "userid" 
      text: "",
      date: "timestamp"
      category: "categoryid"
      likes: 23
   }
}

Each post belong to a category and it's possible to like posts.

Now, I'm trying to show posts that belong to a specific category, sorted by the number of likes. It's possible I also want to limit the filter by date, to show only the most recent, most liked posts in a category. How can I do this?

Firebase query functionality doesn't seem to support multiple queries like this, which seems strange...

like image 584
rodskagg Avatar asked Dec 05 '15 11:12

rodskagg


People also ask

How do you filter data in firebase realtime database?

We can filter data in one of three ways: by child key, by key, or by value. A query starts with one of these parameters, and then must be combined with one or more of the following parameters: startAt , endAt , limitToFirst , limitToLast , or equalTo .

What is orderByChild in firebase?

Firebase orderByChild once child_added is only giving one child. 0. Returning a single child's value on Firebase query using orderByChild and equalTo. 3. unspecified index when searching data with firebase cloud function on nested object running nested Query.


1 Answers

You can use only one ordering function with Firebase database queries, but proper data structure will allow you to query by multiple fields.

In your case you want to order by category. Rather than have category as a property, it can act as an index under posts:

posts: {
   "categoryid": {
       "postid": {
         author: "userid" 
         text: "",
         date: "timestamp",
         category: "categoryid",
         likes: 23
       }
   }
}

Now you can write a query to get all the posts underneath a specific category.

let postsRef = Firebase(url: "<my-firebase-app>/posts")
let categoryId = "my-category"
let categoryRef = postsRef.childByAppendingPath(categoryId)
let query = categoryRef.queryOrderedByChild("date")
query.observeEventType(.ChildAdded) { (snap: FDataSnapshot!) {
  print(snap.value)
}

The code above creates a reference for posts by a specific category, and orders by the date. The multiple querying is possible by the data structure. The callback closure fires off for each individual item underneath the specified category.

If you want to query further, you'll have to do a client-side filtering of the data.

like image 61
David East Avatar answered Oct 07 '22 01:10

David East