如何利用 Google Firebase 数据库中的过滤器和子元素

2024-01-01

Working on an Android app that is using the new Firebase Database framework. It has data objects that are modeled like this: enter image description here Where the Top parent (1234-4321) is the 'chat room', the data object are the 'chat messages', and the numbered items (0, 1, 2) are the 'individual message'.

我可以毫无困难地获取整个数据库并通过侦听器读取它:

FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference();
myRef.addChildEventListener(this);
myRef.addValueEventListener(this);

我能够以这种方式得到一个独生子:

FirebaseDatabase database = FirebaseDatabase.getInstance();
String id = "1234-4321";
DatabaseReference myRef = database.getReference().child(id);
myRef.addChildEventListener(this);
myRef.addValueEventListener(this);

但我一生都无法弄清楚如何获取同一类型的多个对象。我的意思是,用户将能够获得多个聊天室(IE,“1234-4321”和“1234-4432”),但我认为做到这一点的唯一方法是:

1) 循环 onChildAdded 或 onDataChange 侦听器,通过匹配 String id 分离出项目并更新它们。然而,这是极其低效的,因为我正在解析整个数据库,该数据库可能非常大

@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
    if(dataSnapshot != null){
        try {
            ChatObjectV2 objectV2 = (ChatObjectV2) dataSnapshot.getValue();
            //Check here for ids and loop through everything
        } catch (Exception e){
            e.printStackTrace();
        }
    }
}

or

2)要添加一个特定的子对象,但如果我尝试添加更多的子对象,当我希望它“更宽”时,它会“更深”地进入嵌套对象。

//This won't work because it is going 'deeper' instead of 'wider'
String id = "1234-4321";
String id2 = "1234-4432";
Query myQuery = myRef.child(id).child(id2);

然后以相同的方式在侦听器中循环,但是,我需要为每个聊天室创建一个不同的 DatabaseReference,这是非常低效的。

看起来解决方案可能是使用filters https://firebase.google.com/docs/database/android/retrieve-data#filtering_data,但我一生都无法弄清楚如何在现有的 FirebaseDatabase 和 DatabaseReference 对象中利用它们。有谁知道如何使过滤器适用于我在此处列出的数据模式/模型?

谢谢您的帮助!


我将尝试在这些示例中向您解释过滤的基本用法:

//获取前两个聊天室s

Query chatRoomsQuery = databaseReference.limitToLast(2);

//获取最后两个聊天室

Query chatRoomsQuery = databaseReference.limitToFirst(2)

//获取所有活跃的id

Query chatRoomsQuery = databaseReference.orderByChild("active").equalTo(true);

这只是一个基本示例,我鼓励您仔细阅读这个博客 https://firebase.googleblog.com/2014/11/firebase-now-with-more-querying.html。这令人惊奇地解释了高级查询。

或者,您也可以通过这些文档 https://www.firebase.com/docs/android/guide/retrieving-data.html#section-ordered-data。它们与您分享的不同。

请告诉我这是否是您正在寻找的。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何利用 Google Firebase 数据库中的过滤器和子元素 的相关文章