How to index Firebase Realtime Database for leaderboard and get current user’s rank?
I’m using Firebase Realtime Database to store user data for a game. I want to implement a leaderboard based on the highest score.
My current database structure looks like this:
{
"users": {
"Guest0009f30": {
"levelContainer": {
"currentLevel": 12,
"highestScore": 1938
}
},
"Guest0009f80": {
"levelContainer": {
"currentLevel": 16,
"highestScore": 1894
}
}
}
}
What I want to achieve
- Retrieve the top 10 users ordered by
highestScore. - Retrieve the current user’s rank in the leaderboard (even if they are not in the top 10).
What I’ve tried
I added an index rule:
{
"rules": {
"users": {
".read": true,
".write": true,
"$uid": {
".indexOn": ["levelContainer/highestScore"]
}
}
}
}
And my query in C#:
var task = _reference.Child("users")
.OrderByChild("levelContainer/highestScore")
.LimitToLast(20)
.GetValueAsync();
This gives me the top 20 users, but I cannot figure out how to get the current user’s position/rank if they are not in the top 20.
Question
- What is the correct way to index my database for this leaderboard use case?
- How can I query Firebase Realtime Database to get both:
- The top N users, and
- The current user’s rank, even if they are outside the top N?
select levelContainer/highestScore from myTable t order by case when t.user=currentUser then 0 else 1 end, levelContainer/highestScore desc.