在redis中创建结构

时间:2015-04-13 09:51:56

标签: redis

在Redis中创建以下数据结构。

Users [24: {username: 'test', email: 'test@test.com', used_c: 125, 
           posts: [42: {title: 'Hello', posted_at: '2015-05-03'},
                   43: {title: 'Hello1', posted_at: '2015-05-02'}]}]

一种方法是使用复杂的密钥:

set users:24 {username: 'test', emai: 'test@test.com', used_c: 125}
set users:24:posts:42 {title: 'Hello', posted_at: '2015-05-03'}
set users:24:posts:43 {title: 'Hello1', posted_at: '2015-05-02'}

但是做上述事情会限制我很多。

我希望能够获得以下信息:

1. Get users (will list all my users with their data `username, email, used_c`)
2. Get users:24 (will list users data and all the posts)
3. Get posts (will list all the posts)
4. Get posts:42 (will posts data `title, posted_at`)

1 个答案:

答案 0 :(得分:1)

我建议您稍微以不同方式存储数据。

  1. 让每个用户都加入哈希 - user:<uid>,例如:HMSET user:24 username test email test@test.com used_c 125
    • 要获取所有用户(1),请使用SCAN迭代相关密钥,即:SCAN 0 user:*。对于返回的每个密钥,请使用相关字段HMGET
  2. 您可以通过多种不同的方式存储每个用户的帖子 - 为了简单起见(例如在删除时),请使用您存储用户的相同哈希来存储帖子。用户Hash中的每个帖子都包含两个字段 - 标题和日期: HMSET user:24 post:42:title Hello post:42:posted_at 2015-05-03 HMSET user:24 post:43:title Hello1 post:42:posted_at 2015-05-02

    • 通过合并HMGET user:24 username emailHSCAN user:24 0 post:*获取帖子本身来获取用户的帖子(很有可能做HGETALL但是如果有很多帖子可能会降低可扩展性)。
  3. 保留帖子的索引。索引中的每个条目都是帖子的ID,它指向相关用户的ID。您也可以使用哈希,例如:HSET posts_to_user 42 24 43 24

    • 通过HSCAN ning或HGETALL该字段
    • 获取所有帖子
  4. 要获取帖子的数据,请首先找到它所属的用户ID(即HGET posts_to_user 42),然后从用户的哈希(HMGET user:23 post:43:title post:43:posted_at)获取帖子的数据

    < / LI>

    注意:选择正确的数据结构取决于您的数据以及您希望如何获取数据。在我的回答中,我尽量保持尽可能简单,但还有其他方法可以做到这一点。例如,帖子可以各自存储在自己的Hash密钥中,使管理更加复杂,但获得了OTOH的可扩展性和灵活性。另一个例子是索引 - 您可以以不同方式构建数据和索引,以便post的获取效率更高。