简体   繁体   中英

Global and friends-only leaderboard ranking using Cloud Firestore

I need to perform two different queries in my app.

  1. Display a global leaderboard (rank all users based on points)
  2. Display a leaderboard only among friends of the currently logged-in user.

Currently, I have structured my database as follows.

Users (collection):
    user_id (document):
        ...
        points: number
        ...

        Friends (sub-collection):
            user_id (document):
                name: string
                points: number

This approach works for populating the global leaderboard as it's just:

db.collection("Users")
            .orderBy("points", Query.Direction.DESCENDING)
            .limit(10)
            .get()

Displaying a leaderboard among friends of a user also works in this case, but updating points of a user becomes an expensive operation because of multiple duplication.

Is there a way to structure my database so I can efficiently query and update my users collection?

I think what you're doing now is probably the best way to go. Data duplication is normal for NoSQL type databases, and it's expected that you'll do multiple updates to keep everything in sync if something changes. That's totally normal.

The alternative is to keep all relevant data in a single collection somehow (don't use a subcollection to store friends), but then you'll end up with a different problem of eventually exceeding the capacity of the document that contains all the data for each user.

The bottom line here is that NoSQL databases like Firestore give you better scalability and faster queries at massive scale, at the expense of less flexible querying and more work keeping duplicated data up to date. If you would prefer more flexible querying and easier updates, then Firestore might not be the best database for your application.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM