How to store sorted set of objects in redis?

戏子无情 提交于 2019-12-07 04:59:02

问题


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?


回答1:


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"


来源:https://stackoverflow.com/questions/27614975/how-to-store-sorted-set-of-objects-in-redis

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!