Lion789 Lion789 - 1 month ago 14
Android Question

How to grab multiple paths and sort them and bring back the result in firebase?

Hey guys so I am trying to understand how I can take a list of Ids, and then ask for Firebase to take each path and sort them by date and bring me back the top 20 all in one Firebase call. At the moment I am doing this by looping through the ids and grabbing each path - adding the items to a list then sorting them.

However this is inefficient especially as the list gets bigger.

My data looks something like this:

follows: {
UserId :{
projId1: true,
projId2: true
}
}

projects: {
projId1 :{
title: SomeText,
date: TimeStamp
}
}

Answer

A Firebase query runs at one specific location and it can only order on data that exists at fixed paths under the children of that location. There is no way to sort a Firebase query on data that exists at a different path.

So in your case, if you are loading data from /follows/$uid, there is not way to order the results on data from the /projects nodes.

That leaves you with two options:

  1. sort the data on the client

  2. at the sort properties to the follows children

Sorting data on the client is a valid option as long as your data set is not too large and you're not filtering too much.

But to allow sorting on the server, you'll have to duplicate the relevant properties under the node where you query:

follows: {
  UserId :{
    projId1: TimeStamp,
    projId2: TimeStamp
  }
}

projects: {
  projId1 :{
    title: SomeText,
    date: TimeStamp
  }
}

With this structure you can order then projects on timestamp with

Query query = database.child(user.getUid()).orderByValue();
query.addChildEventListener(...