Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to have relations many to many in redis

In an relational database, i have an user table, an category table and an user-category table which do many to many relationship.

What's the form of this structure in Redis?

like image 314
Ismael Vacco Avatar asked Jun 06 '12 03:06

Ismael Vacco


2 Answers

With Redis, relationships are typically represented by sets. A set can be used to represent a one-way relationship, so you need one set per object to represent a many-to-many relationship.

It is pretty useless to try to compare a relational database model to Redis data structures. With Redis, everything is stored in a denormalized way. Example:

# Here are my categories
> hset category:1 name cinema  ... more fields ...
> hset category:2 name music   ... more fields ...
> hset category:3 name sports  ... more fields ...
> hset category:4 name nature  ... more fields ...

# Here are my users
> hset user:1 name Jack   ... more fields ...
> hset user:2 name John   ... more fields ...
> hset user:3 name Julia  ... more fields ...

# Let's establish the many-to-many relationship
# Jack likes cinema and sports
# John likes music and nature
# Julia likes cinema, music and nature

# For each category, we keep a set of reference on the users
> sadd category:1:users 1 3
> sadd category:2:users 2 3
> sadd category:3:users 1
> sadd category:4:users 2 3

# For each user, we keep a set of reference on the categories
> sadd user:1:categories 1 3
> sadd user:2:categories 2 4
> sadd user:3:categories 1 2 4

Once we have this data structure, it is easy to query it using the set algebra:

# Categories of Julia
> smembers user:3:categories
1) "1"
2) "2"
3) "4"

# Users interested by music
> smembers category:2:users
1) "2"
2) "3"

# Users interested by both music and cinema
> sinter category:1:users category:2:users
1) "3"
like image 157
Didier Spezia Avatar answered Nov 03 '22 01:11

Didier Spezia


IMHO Redis is not for making structured querys(SQL) but for fast accesible data, what you could do is this: make a "table" with user_id as a key and the data is a list with friends, for example. Then you query for the user_id and process what you need. It's the opposite of normalization. If the order of data is importante, for example status updates, what you do is push and pop data into the lists. For example, the table "status" has user_id as key and the data is a list. You lpush data and then query the last 20 elements for example.

like image 32
AlfredoVR Avatar answered Nov 03 '22 00:11

AlfredoVR