John
John

Reputation: 634

Create structure in redis

Create the below data structure in Redis.

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

One way would be to use complex keys:

set users:24 {username: 'test', emai: '[email protected]', 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'}

But doing the above will restrict me a lot.

I would like to be able to get the following info:

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`)

Upvotes: 0

Views: 59

Answers (1)

Itamar Haber
Itamar Haber

Reputation: 49942

I suggest that you store your data a little differently.

  1. Keep each user in a Hash - user:<uid>, e.g.: HMSET user:24 username test email [email protected] used_c 125
    • To get all your users (1), iterate over the relevant keys using SCAN, i.e.: SCAN 0 user:*. For every key returned, do HMGET with the relevant fields.
  2. You can store the posts per user in several different ways - for simplicity (e.g. while deleting), use the same Hash that you're storing your user in to store the posts. Each post in the user Hash will consist of two fields - the title and the date: 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

    • Get the user's posts by combining HMGET user:24 username email and an HSCAN user:24 0 post:* for the posts themselves (it is tempting to do an HGETALL but if there are a lot of posts that could prove less scalable).
  3. Keep an index of the posts. Each entry in the index is the post's ID and it points to the relevant user's ID. You can use a Hash for that as well, e.g.: HSET posts_to_user 42 24 43 24

    • Get all posts by HSCANning or HGETALLing that field
  4. To get a post's data, first find the user ID it belongs to (i.e. HGET posts_to_user 42) and then get the post's data from the user's Hash (HMGET user:23 post:43:title post:43:posted_at)

Note: making the "right" choice of data structure depends on your data and how you want to fetch it. In my answer I tried keeping things as simple as possible but there are other ways for doing the same. For example, the posts could be stored each in its own Hash key, making management a little more complex but gaining scalability and flexibility OTOH. Another example is the index - you could build your data and index differently so that the post's fetch would be more efficient.

Upvotes: 1

Related Questions