【问题标题】:How to query lists based on their children's properties in Firebase?如何在 Firebase 中根据孩子的属性查询列表?
【发布时间】:2017-01-29 09:56:10
【问题描述】:

我为自己制作了一个爱好应用,因此我可以尝试使用 Firebase。该应用程序的想法是将 youtube 链接添加到播放列表,然后由远程客户端播放。我的数据如下所示:

 "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"
  }
}

每首歌曲的id都是由youtube的video id生成的,播放状态如下:

  • 0 = 待处理
  • 1 = 正在播放
  • 2 = 播放

因为客户端想知道新歌曲被添加到播放列表中,所以它会在这个列表中保持一个监听器,并在每次更新时过滤所有播放状态为 0 的歌曲,如下所示:

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) {
    }
});

然而,这非常低效,因为侦听器将收到有关播放列表中任何项目的任何更改的通知 - 根据使用情况,这可能会变得非常大。那么有没有办法让我的应用只收到播放状态值设置为 0 的歌曲更改的通知?

我检查了documentation,也找到了this old blog article that promised more powerful queries as an upcoming feature,但我仍然没有找到方法。

【问题讨论】:

    标签: android firebase firebase-realtime-database nosql


    【解决方案1】:

    你会使用:

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

    Firebase documentation on queries 对此进行了介绍。

    别忘了add an index to your Firebase rules,这样查询是在服务器端执行的:

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

    【讨论】:

    • 哦,是的,索引就是缺少的东西!坦克!
    猜你喜欢
    • 2017-06-04
    • 1970-01-01
    • 1970-01-01
    • 2018-01-25
    • 2017-12-28
    • 2021-04-22
    • 2017-07-24
    • 2019-03-23
    • 2019-05-01
    相关资源
    最近更新 更多