简体   繁体   中英

Firebase/NoSQL schema for an instant messaging system

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM