1

I have a real time firebase database that stores a list of users and it's stored in the following format(Json)

{
"users" : {
"-L29HeOZCmYu9UGJLMQR" : {
  "name" : "John Doe",
  "phoneNumber" : "+555-1566",
  "points" : 21,
  "rank" : 10,
  "userId" : "-L29HeOZCmYu9UGJLMQR"
},
"-L2ASCuStoH7CTaqgBgG" : {
  "name" : "Jenna Rose",
  "phoneNumber" : "+555-3562",
  "points" : 96,
  "rank" : 0,
  "userId" : "-L2ASCuStoH7CTaqgBgG"
   },
....// A lot more users.
}

So my question is, how do I get the rank of the user in terms of the "points" variable? Also, how do I prepare a list of the top 10 or the top 100 etc..?

birukhimself
  • 193
  • 3
  • 14

1 Answers1

2

There is no way to get the rank of a specific user, without loading all users.

But you can get the top N users by using Firebase's query mechanism to sort and filter data. For example:

DatabaseReference ref = FirebaseDatabase.getInstance().getReference("users");
Query top10query = ref.orderByChild("points").limitToLast(10);
top10query.addChildEventListener(...

The children will be in ascending order. You'll have to revert them client-side, for example by adding each subsequent child to the top of the list.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Thanks @frank But is there a way to do this with firebase functions? If so, how? Sample code would be appreciated :) Because having to load all users is very resource intensive. – birukhimself Jan 12 '18 at 09:50
  • Cloud Functions is just another environment for running your code in. What is possible accessing the Firebase Database from Cloud Functions is pretty much the same as when you access it from the Android app directly. There is no magical "from Cloud Functions the database suddenly allows access by index". – Frank van Puffelen Jan 12 '18 at 15:12