0

I am a beginner on Firebase and I want to know the correct way on how to display random data from my database. I have this node called "Users" having this structure:

Users
  |---- ISbxAeNkkIcTpeL8GNBx3CbxU7F2
  |        |
  |        |---- Username: "user1"
  |        |
  |        |---- Email: "example@gmail.com"
  |        |
  |        |---- Index: 1
  |
  |--- d3FvVpsDu6UIVLBdUWxRN8GWZQB2
           |
           |---- Username: "user2"
           |
           |---- Email: "example2@gmail.com"
           |
           |---- Index: 2

Since Firebase has no function to retrieve random data, I came up with this code: (simplified, not exactly the code)

for (int i = 1; i <= 20; i++) {
     //generate a random index
     int random = new Random().nextInt((totalUserCount - 1) + 1) + 1;

     FirebaseDatabase.getInstance()
       .getReference("Users")
       .orderByChild("Index")
       .equalTo(random)
       .addListenerForSingleValueEvent(new ValueEventListener() {
          @Override
          public void onDataChange(@NonNull DataSnapshot snapshot) {
             for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
                 UserModel model = dataSnapshot.getValue(UserModel.class);
                 usersList.add(model);
             }
          }
     
          @Override
          public void onCancelled(@NonNull DatabaseError error) {
          }
       });
}

The code works but I wanted to know if this is the right practice since I think it is a bad practice to loop my queries. Also, I have seen several solutions to load the whole node and manage it client-side, but I do not want this because it will get slow once there are a lot of users.

Xghj
  • 37
  • 2
  • 6
  • Some things to consider: Generate all your IDs outside of the loop to eliminate duplicates. If there are less than X users in your database, just fetch all X users and randomise the order offline. Once you have all of your desired IDs, you could use an `in` query to do ten at a time. Reconsider how you are selecting entries though, as if you have users delete their account, you will have missing entries. Consider using a [Callable Cloud Function](https://firebase.google.com/docs/functions/callable) to generate a random list of user IDs instead. – samthecodingman Jan 03 '22 at 11:18
  • Check whether this question helps you https://stackoverflow.com/questions/46798981/firestore-how-to-get-random-documents-in-a-collection – RaBaKa 78 Jan 03 '22 at 11:22
  • Also, don't store email addresses like you are at the moment. Treat them like passwords/phone numbers and don't make them so easily publicly accessible. If you need to "search by email", store a hash of it instead. If you follow [Gravatar's guidelines](https://en.gravatar.com/site/implement/hash/), you can even use Gravatar's profile pictures. – samthecodingman Jan 03 '22 at 11:22

0 Answers0