0

I have a game in python which takes info about the user and even stores the points. I wanted to make a leaderboard for it and so I decided to use Firebase and write the data into the database. I would just like the arrangement of the data to be in descending order based on the points limited upto the Top 20 ranks because the data is just randomly arranged now. Help will be appreciated. Thanks! enter image description here

My code:

#Example Set
ref = db.reference('/')
ref.set({
    'Data':
        {

        'user'+str(userCounter): {
            'Username':userid,
            "Points": highscore
            }
        }

    })

#Updating Data
if current_score > highscore:
    ref = db.reference('Data')
    emp_ref = ref.child('user'+str(id))

    emp_ref.update({
        "Points": current_score
        })
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
PradMaster
  • 83
  • 10

2 Answers2

2

Use the following query to retrieve the top 20 people in point list.

data_ref = db.reference('data')
snapshot = data_ref.order_by_child('Points').limit_to_first(20).get()
for key in snapshot:
    print(key)

Made query with the help of docs

Ashish
  • 6,791
  • 3
  • 26
  • 48
  • though when i tried once it said - AttributeError: module 'firebase_admin.db' has no attribute 'collection'. Is there any fix?? – PradMaster Dec 07 '20 at 14:10
  • This answer is for Cloud Firestore, while you're using the Realtime Database. While both databases are part of Firebase, they're completely separate, and the security rules for one don't apply to the other. To fix the error, you will have to set the rules for the Realtime Database. For a walkthrough of how to do that, see https://stackoverflow.com/a/52129163 – Frank van Puffelen Dec 07 '20 at 15:44
  • @FrankvanPuffelen, prad see i update the answer might help you – Ashish Dec 07 '20 at 16:47
  • @Ashish now it says : firebase_admin.exceptions.InvalidArgumentError: Index not defined, add ".indexOn": "Points", for path "/Data", to the rules. I've even added ".indexOn": "Points" to the rules but it doesn't seem to change anything – PradMaster Dec 07 '20 at 17:10
  • 1
    Thanks for that update Ashish. And I upvoted for you using the docs. I completely forgot we have Python samples there. – Frank van Puffelen Dec 07 '20 at 18:42
1

The Firebase Realtime Database does not support descending ordering. If you want to display the items from the database in descending order, you have two options:

  1. Reverse the results client-side before displaying them.
  2. Storing an inverted value int he database, and use that in the query. So in your case that'd mean you add a negativePoints value in the database and sort on that, but then still use the existing points property in the display of course.

Also see:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • but when i update the data the updated data comes up first in order...so how do I arrange it at the client side? – PradMaster Dec 07 '20 at 16:43