How to store a sorted set of objects in redis?
I would like to know how to store a list of objects in Redis. That is, I have such a key.
users:pro
{
name: "Bruce", age: "20", score: 100,
name: "Ed", age: "22", score: 80
}
Where I want to store a list of hashes as a specific key value. I would like to use a field score
as a score field in a sorted set. How could I do this?
I've seen it write one hash for the key, but what if I want multiple hashes and one of the hash fields to act as an evaluation field for the sorted set?
source to share
Using a single key to store all of your hashes will require some serialization as Redis does not support nested data structures. The result will be the following:
key: users:pro
|
+-----> field value
name:Bruce "age: 20, score: 100"
name:Ed "age: 22, score: 80"
> HMSET users:pro name:Bruce "age: 20, score: 100" name:Ed "age:22, score:80"
The corresponding sorted set would be:
key: users:pro.by_scores
|
+---> scores: 80 100
+---> values: "name:Ed" "name:Bruce"
> ZADD users:pro.by_scores 80 "name:Ed" 100 "name:Bruce"
Note 1 : This approach requires a unique identifier for each user, a property is currently in use name
that can be problematic.
Note 2 . To avoid serialization (and deserialization), you might consider using a dedicated key for each user. It means:
key: users:pro:Bruce
|
+-----> field value
age 20
score 100
key: users:pro:Ed
|
+-----> field value
age 22
score 80
> HMSET users:pro:Bruce age 20 score 100
> HMSET users:pro:Ed age 22 score 80
key: users:pro.by_scores
|
+---> scores: 80 100
+---> values: "users:pro:Ed" "users:pro:Bruce"
> ZADD users:pro.by_scores 80 "users:pro:Ed" 100 "users:pro:Bruce"
source to share