Hello Michael,
Thank you for the response. My use case is a chat application on a mobile device. In the application, I want to have a screen that gives a summary of unread messages for a given user. I have tried different approaches but this query has always been a challenge.
Using firestore's new better queries and rules, I came up with the following query and structure:
There is a collection of all messages. Each message document contains an 'isUnread' map that has every user id that has that message as unread. The value of user id key is the creation date of the message.
So a message would look like this:
message {
text: 'Hello. This is a message',
createdAt: 1506020743055,
isUnread: {
QLGqZs526rf5Bj6g1lRqzhJq0e82: 1506020743055,
H8azi90yo4WovxUD4l22Pj2feCc2: 1506020743055,
...
},
}
And the query would look like this:
// Getting all messages that are unread for a user in one one fetch:
db.collection('messages').where(`isUnread.${userId}`, '>', 0).orderBy(`isUnread.${userId}`).get()
Now my concern about this, is that the size of message documents scales with the number of users. It is still a single fetch so, I expect it to stay fast. But the main concern becomes data usage on mobile devices. Now if I could use select to not have to download the 'isUnread' map and just have the server do filtering I would not have to worry about this scaling. Now I can understand how this might mess up caching, due to the client not having the 'isUnread' map but I think I would be okay with this. Also offline and local writes are not necessarily a concern for me.
I tried other approaches in the past:
I found that a single fetch works much better than multiple round trips. The performance is okay on web but suffers greatly on react native (I think this was due to the react native bridge being invoked for http requests). To have a single fetch on old firebase, I denormalized message data so that there is a unread messages path for each user with the message data duplicated. The problem with this approach is that every time someone writes a message it has be written for each user. Again the main concern is the data usage on mobile devices. There could be hundreds of users for a chat. The firestore approach should have better scaling.
Do you have any suggestions?
Thanks for you time,
Kristian