0

I have some difficulties building a query for selecting data in firebase database. My database structure is like this:

enter image description here

I need to get all users which have contact ghopper. Here the result is alovelace and eclarke. But I really have no idea how to do this simple query in Java.

Thank you for your help!

AL.
  • 36,815
  • 10
  • 142
  • 281
Binev
  • 266
  • 4
  • 15

1 Answers1

2

You'd use Firebase Database queries for that:

DatabaseReference usersRef = FirebaseDatabase.getInstance().ref("users");
Query query = usersRef.orderByChild("contacts/ghopper").equalTo(true);
// My top posts by number of stars
query.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
            System.out.println(snapshot.getKey());
        }
    }

But this requires that you define an index for each user, which doesn't scale. That is because the structure you have now is meant to allow to easily determine the users for a chat room, and you're trying the opposite.

To efficiently allow getting the chat rooms for a user, you should structure your data so that it also keep a list of users for each chat room. This is often called a secondary/reversed/inverted index.

For more examples of this see:

Community
  • 1
  • 1
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • thanks, I am actually puzzled about the structure I should use here. Is it better idea to store the full data into contacts (for example name)? – Binev Mar 22 '17 at 14:27