如何在Redis中存储排序的对象集? [英] How to store sorted set of objects in redis?

查看:289
本文介绍了如何在Redis中存储排序的对象集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何在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
}

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

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?

推荐答案

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

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"

对应的排序集为:

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属性,这可能会出现问题.

Note 1: this approach mandates a unique ID per-user, currently the name property is used which could be problematic.

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

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"

这篇关于如何在Redis中存储排序的对象集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆