spacitron
spacitron

Reputation: 2183

How to query lists based on their children's properties in Firebase?

I made myself a hobby app so I could experiment with Firebase. The idea of the app is to add youtube links to a playlist, which are then played by a remote client. My data looks something like this:

 "songs" : {
  "4sRxtvygyDo" : {
    "playStatus" : 2,
    "songtitle" : "Silent Alarm - Bloc Party (Full Album, High Quality)",
    "thumbnail" : "https://i.ytimg.com/vi/4sRxtvygyDo/default.jpg",
    "youtubeurl" : "https://www.youtube.com/watch?v=4sRxtvygyDo"
  },
  "ht-nFq3DjP0" : {
    "playStatus" : 2,
    "songtitle" : "We Were Promised Jetpacks: These Four Walls (Full Album)",
    "thumbnail" : "https://i.ytimg.com/vi/ht-nFq3DjP0/default.jpg",
    "youtubeurl" : "https://www.youtube.com/watch?v=ht-nFq3DjP0"
  },
  "xFWVFu2ASbE" : {
    "playStatus" : 0,
    "songaddedtime" : 1485642448454,
    "songtitle" : "Totorro - Home Alone [Full Album]",
    "thumbnail" : "https://i.ytimg.com/vi/xFWVFu2ASbE/default.jpg",
    "youtubeurl" : "https://www.youtube.com/watch?v=xFWVFu2ASbE"
  }
}

Each song's id is generated from the youtube's video id and has a play status as follows:

Because the client wants to know about new songs being added to the playlist, it keeps a listener to this list and at every update filters all the songs with a play status of 0 as follows:

playlistReference.addValueEventListener(new ValueEventListener() {

    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot song : dataSnapshot.getChildren()) {
            if (song.child("playStatus").getValue(Integer.class) == 0) {
                songPlayer.playNext(song.getKey());
                break;
            }
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
    }
});

This is however very inefficient because the listener will receive notifications for any change on any item in the playlist - which could grow very large depending on usage. So is there a way for my app to only be notified of changes to songs that have a play status value set to 0?

I checked in the documentation and I also found this old blog article that promised more powerful queries as an upcoming feature but I still haven't found a way to do this.

Upvotes: 0

Views: 73

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 600131

You'd use:

playlistReference.orderByChild("playStatus").equalTo(0).add...

This is covered in the Firebase documentation on queries.

Don't forget to add an index to your Firebase rules, so that the query is executed server-side:

{
  "rules": {
    "songs": {
      ".indexOn": "playStatus"
    }
  }
}

Upvotes: 3

Related Questions