JavaTechnical
JavaTechnical

Reputation: 9347

How to store sorted set of objects in redis?

I would like to know how to store a list of objects in Redis. That is I have a key like this.

users:pro
{ 
name: "Bruce", age: "20", score: 100,
name: "Ed", age: "22", score: 80
}

Where I will want to store a list of hashes as value of a particular key. I would like to use the score field as the score field in the sorted set. How could I accomplish this?

I have seen writing a putting a single hash for a key, but what if I want multiple hashes and one of the hash fields must act as a score field for the sorted set?

Upvotes: 10

Views: 6032

Answers (1)

Itamar Haber
Itamar Haber

Reputation: 49942

Using a single key to store all your hashes will require some serialization as Redis doesn't support nested data structures. The result would 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 mandates a unique ID per-user, currently the name property is used which could be problematic.

Note 2: to avoid the serialization (and deserialization), you can consider using a dedicated key per user. That means doing:

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"

Upvotes: 8

Related Questions