我想知道如何在Redis中存储对象列表。也就是说,我有一个类似于这样的键。
users:pro
{
name: "Bruce", age: "20", score: 100,
name: "Ed", age: "22", score: 80
}
我希望将一系列哈希值作为特定键的值进行存储。我想使用score
字段作为排序集合中的分数字段。如何实现这一点?
我看到可以把单个哈希值放在键中,但如果我想要多个哈希值,并且其中一个哈希字段必须充当排序集合的分数字段,该怎么办呢?
在Redis中使用一个键存储所有哈希需要进行一定的序列化,因为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"
key: users:pro.by_scores
|
+---> scores: 80 100
+---> values: "name:Ed" "name:Bruce"
> ZADD users:pro.by_scores 80 "name:Ed" 100 "name:Bruce"
注意 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"
users:pro:101
代替users:pro:Ed
,其中101
是唯一的标识符。 - JavaTechnicalHSET users:pro:101 id 101
)- 尽管这是"去规范化",但这使得数据处理变得更加容易。 - Itamar Haber
HSET
只能存储一个哈希,现在如何在同一个键中存储多个哈希? - JavaTechnicalRedis
的新手,所以无法理解。 - JavaTechnical