Redis is conceptually different from traditional SQL databases that I use, and I'm trying to figure out if it is right for my project... I've been looking around but can't seem to find an answer to my question.
I have a set of Users that I need to store, each with a unique ID and several values (such as their name) associated with it. It seems like I can simply store those as a hash:
user:fef982dcfe1a7bcba4849b4c281bba95
"username" "andrewm" "name" "Andrew"
I also have a bunch of messages I want to store, each having a few properties such as the sender and recipient:
message:1a7bcba4849b4c281bfef98a952dcfeb
"sender" "fef982dcfe1a7bcba4849b4c281bba95" "recipient" "82dcfe1a7bcba4849b4c281bba95fef9" "message" "Hi!"
My question is, how would I go about retrieving all of the messages that are sent by a specific user (designated by a their hash). Should I be using a traditional relational database instead, or even a NoSQL database like MongoDB (which I've used before)? If so, does anyone have any suggestions for high performance stores? I won't be doing any true searching (i.e. MySQL LIKE
queries)-- just key value lookups, really.
It is certainly possible to model these data with Redis, but you need to think in term of data structures AND access paths. With Redis the access paths are not managed implicitly (like with indexes in RDBMS/MongoDB).
For the provided example, you could have:
Adding/deleting a message would mean maintaining the *:sent and *:received sets corresponding to the senders and recipients, on top of adding/deleting the message object itself.
Retrieving sent or received messages for a given user is just a SMEMBERS command, or a SORT if you want to retrieve also the properties of the message at the same time:
For the rationale about using sort, see:
Note 1: with Redis it is better to use integers as keys rather than UUID or hash codes (especially in sets), since they are stored in a more efficient way.
Note 2: if you need to order the messages, then lists must be used instead of sets. The consequence is only oldest messages can be removed, and only newset messages can be added in an efficient way. You would probably to also add a global list for all messages.