Reputation: 13
I'm new to Redis, I have this task where I have to model a one-to-many relationship given the following entities:
A person(Bob,Tom,Sam) who can receive one or many messages, a message is characterized by the "text" and the "data".
What I have done is this:
SADD Bob:messages "Bob:message:1" "Bob:message:2" "Bob:message:3"
Where Bob:messages is the key of the set, and "Bob:message:1" "Bob:message:2" etc are the messages associated to Bob.
The messages are saved as Hash-sets each has-set represents a message of Bob:
HMSET Bob:message:1 text "Hi Bob" data "20/12/2019:13:23"
HMSET Bob:message:2 text "Give me the keys" data "20/12/2019:13:24"
HMSET Bob:message:3 text "Bye Bob" data "20/12/2019:13:25"
The keys in the hash-sets are the values of the previous set.
Is this enough to model the one-to-many relationship?
Upvotes: 1
Views: 3260
Reputation: 31528
A set is enough to model a one to many relationship. But it is not the only way to model such a relationship. You can also use a lost or a sortedset or even a stream to model such a relationship. The natural question is which one to use, and the answer is it depends.
If it is important to store messages in the order they were received, you would perhaps use a list. If you want to read most recent messages received by a user, a list would make sense.
On the other hand, if messages had a concept of likes or upvotes, and you want to find messages by the number of likes - a sorted set would make more sense.
Upvotes: 2