0

I have TextView and I want to show player rank like Your Rank Is 6th

There is a collection that has 8 documents, Inside every document has field named player_name and player_score.

  1. player_name = Liam , player_score = 14
  2. player_name = Noah , player_score = 72
  3. player_name = Oliver , player_score = 18
  4. player_name = Elijah , player_score = 139
  5. player_name = William , player_score = 419
  6. player_name = James , player_score = 832
  7. player_name = Benjamin , player_score = 1932
  8. player_name = Lucas , player_score = 6

Let us suppose I signed in by James account, So the TextView should show me this result after using OrderBy Descending on Firestore -> Your Rank Is 2nd

How can I do it?

Note 1 : Is that will cost me 1800 reads in my quota because in fact I have more than 1800 documents not 8?

Note 2 : Every document name is player id

Taha Sami
  • 1,565
  • 1
  • 16
  • 43

1 Answers1

1

You can query the leaderboard like this:

CollectionReference citiesRef = db.collection("players");
citiesRef.orderBy("player_score").limit(10);

As you can see I have set the limit of documents to retrieve to 10 (i.e. top 10 users with highest scores) so I'll be charged 10 reads only. You get charged for amount of documents you are retrieving/reading. Firestore automatically indexes single fields so the queries are fast. You can get a detailed explanation here.

Do note that if you don't have that .limit() set then Firestore will pull all the documents in that collection and costing you that many reads.

Coming to the part where you need to show the user's rank, that cannot be done by the query I mentioned above instead you'll have to paginate the query as mentioned here. Although that may incur additional reads.

Dharmaraj
  • 47,845
  • 8
  • 52
  • 84
  • If I was have 400,000 players in Firestore and I want to get new player rank who joined recently that will cost me 400,000 reads right? – Taha Sami Jun 06 '21 at 08:18
  • @AKJA if you use the startAfter method then no but again it's hard to predict where the user is in the leaderboard. – Dharmaraj Jun 06 '21 at 08:26
  • 1
    I hope Firebase team find solution to us in next updates. Thank You. – Taha Sami Jun 06 '21 at 08:39
  • 1
    Dan documented the options for storing such leaderboard/rankings here: https://stackoverflow.com/questions/46720997/leaderboard-ranking-with-firebase – Frank van Puffelen Jun 06 '21 at 15:02