Redis and Querying Values

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:

user:<user hash> -> hash of user properties
user:<user hash>:sent -> set of <msg hash>
user:<user hash>:received -> set of <msg hash>
message:<msg hash> -> hash of message properties

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:

# Get a list of message hash codes only in one roundtrip
smembers user:<user hash>:received

# Get a list of message contents in one roundtrip
sort user:<user hash>:received by nosort get message:*->sender get message:*->message

For the rationale about using sort, see:

  • Getting multiple key values from Redis
  • Need help conceptualizing in Redis/NoSQL

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.

Tags:

Redis