Ism*_*cco 15 many-to-many redis
在关系数据库中,我有一个用户表,一个类别表和一个多对多关系的用户类别表.在redis中有这种结构的更好的形式是什么?
Did*_*zia 37
使用Redis,关系通常由集合表示.集合可用于表示单向关系,因此每个对象需要一个集合来表示多对多关系.
尝试将关系数据库模型与Redis数据结构进行比较是没有用的.使用Redis,一切都以非规范化的方式存储.
例:
# Here are my categories
> hmset category:1 name cinema ... more fields ...
> hmset category:2 name music ... more fields ...
> hmset category:3 name sports ... more fields ...
> hmset category:4 name nature ... more fields ...
# Here are my users
> hmset user:1 name Jack ... more fields ...
> hmset user:2 name John ... more fields ...
> hmset 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
Run Code Online (Sandbox Code Playgroud)
一旦我们有了这个数据结构,就很容易使用set代数查询它:
# 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"
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
9002 次 |
最近记录: |