Skip to content
Advertisement

How to get children keys from Firebase without downloading their children?

I have a Firebase database with a node “items” that has many children and I would like to import a list of the children keys. Since each child contains quite some data that I am not interested in for this purpose, I would like to download only the children keys (to minimize the amount of data transferred). For illustration, suppose I have the following data structure:

enter image description here

Then I would like to get the id’s of all the users, so 5Aoz6ZaB9QS7o9M4lsdbh07VGA02 etc. But without downloading the other user data such as the messages, name, proposed and score.

Advertisement

Answer

To get the ids of those users, please use the following code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("users");
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String uid = ds.getKey();
            Log.d("TAG", uid);
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
usersRef.addListenerForSingleValueEvent(valueEventListener);

The output will be:

5Aoz6ZaB9QS7o9M4lsdbh07VGA02
// the other ids

When you attach a listener on a specific node, you get all the data beneath that node. This is how Firebase Realtime database works and unfortanately this behaviour cannot be changed. But there is an workaround in which you can create another separate node in which you can add all those ids separately. The new node should look something like this:

Firebase-root
   |
   --- userIds
          |
          --- 5Aoz6ZaB9QS7o9M4lsdbh07VGA02: true
          |
          --- //other ids

In this case, if you attach a listener on userIds node, you’ll get only the desired data and nothing more. The code to get those ids is simmilar with the code above, but instead of using .child("users") you need to use .child("userIds"). The output will be the same.

If you want another behaviour, you can consider using Cloud Firestore where this behaviour isn’t an issue anymore.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement