0
votes

Every time the user retrieves the Firebase Realtime Database messages, he would like only the last 50 messages from the messaging node to be retrieved (read) through the Realtime Database rules. How to do this?

Message node structure:

+ chats
   + regionChat (ex: eua)
      + idChat (ex: 534854923)
         + messages
            + idMessage1
            + idMessage2
            + idMessage3
            + idMessage4
            + idMessage5
            ...

I saw this in the firebase documentation, but I can't adapt my data structure:

messages: {
  ".read": "query.orderByKey &&
            query.limitToFirst <= 50"
}

At the moment my rules are like this:

{
  "rules": {
    ".read": true,
    ".write": true
  }
}
2
That's not an appropriate use of Firebase Rules as Rules are not filters. Rules are used to secure your data and ensure the right kind of data is read/written. You would limit the amount of data to be read with your query. take a look at Filtering Data: limitToLast(). - Jay

2 Answers

0
votes

you need to enhance your "query"

this should work

{
  "rules": {
    ".read": "query.limitToFirst <= 50",
    ".write": true
  }
}
0
votes

Or, instead of using the rules, you can do it via Query.

DatabaseReference myReference = FirebaseDatabase.getInstance().getReference();

myReference = myReference().child("chats")...child("messages");
Query query = myReference.orderByID().limitToFirst(20).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()) {
                //
                for (DataSnapshot issue : dataSnapshot.getChildren()) {
                    // do something with the  data
                }
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });