如何在Redis中存储排序的对象集?

Jav*_*cal 6 hash sortedset redis

我想知道如何在Redis中存储对象列表。那就是我有这样的钥匙。

users:pro
{ 
name: "Bruce", age: "20", score: 100,
name: "Ed", age: "22", score: 80
}
Run Code Online (Sandbox Code Playgroud)

我将在其中存储哈希列表作为特定键的值的位置。我想将该score字段用作排序集中的得分字段。我该怎么做?

我见过为键编写一个散列,但是如果我想要多个散列并且散列之一必须用作已排序集的分数字段,该怎么办?

Ita*_*ber 6

由于Redis不支持嵌套数据结构,因此使用单个密钥存储所有哈希将需要进行一些序列化。结果将如下所示:

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"
Run Code Online (Sandbox Code Playgroud)

相应的排序集将是:

key: users:pro.by_scores
         |
         +---> scores:    80           100
         +---> values: "name:Ed"   "name:Bruce"

> ZADD users:pro.by_scores 80 "name:Ed" 100 "name:Bruce"
Run Code Online (Sandbox Code Playgroud)

注意1:此方法要求每个用户使用唯一的ID,当前使用的name属性可能会出现问题。

注意2:为避免序列化(和反序列化),可以考虑为每个用户使用专用密钥。那意味着要做:

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"
Run Code Online (Sandbox Code Playgroud)