1

I'm using Firebase for an app and the built-in real-time capabilities seem well suited for instant messaging. I'm just having a hard time working out in my head how the database should be set up. Ideally, it's something like this:

messages: {
  <messageId>: {
    from: <userId>,
    to: <userId>,
    text: <String>,
    dateSent: <Date>
    dateRead: <Date>
  }
}

And that's all fine for sending messages, but reading message threads becomes difficult. I need to query the (potentially huge) list of messages for messages that match the current thread's sender and receiver, and then order those by dateSent. If that is possible with Firebase's new querying API, then I have yet to figure out exactly how to do it.

Community
  • 1
  • 1
delwin
  • 830
  • 2
  • 10
  • 15

1 Answers1

3

Querying a huge list of messages is never a good idea. If you want a fast-performing Firebase/NoSQL application, you'll need to model the data to allow fast look up.

In a chat scenario that typically means that you'll model your chat rooms into the data structure. So instead of storing one long list of messages, store the messages for each chat "room" separately.

messages
  <roomId>
    <messageId1>: "..."
    <messageId2>: "..."
    <messageId3>: "..."

Now you can access the messages for the chat without a query, just ref.child(roomId).on(....

If you want a persistent mapping that ensures the same two users end up in the same room, have a look at Best way to manage Chat channels in Firebase

Community
  • 1
  • 1
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • So this means I should basically use the Firebase chat example as a base, but restrict rooms to a discussion between two users? How would I prevent duplicate "rooms" being opened between the same two users? – delwin Mar 23 '16 at 17:06
  • See http://stackoverflow.com/questions/33540479/best-way-to-manage-chat-channels-in-firebase – Frank van Puffelen Mar 23 '16 at 17:12