如何在Redis中建立多对多关系 [英] how to have relations many to many in redis

查看:822
本文介绍了如何在Redis中建立多对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在关系数据库中,我有一个用户表,一个类别表和一个用户类别表,它们之间存在多对多关系. 在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 better form of have this structure in redis?

推荐答案

在Redis中,关系通常由集合表示.一组可用于表示单向关系,因此每个对象需要一组来表示多对多关系.

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.

尝试将关系数据库模型与Redis数据结构进行比较几乎没有用.使用Redis,所有内容均以非规范化方式存储.

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.

示例:

# 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

一旦有了这种数据结构,就可以很容易地使用集合代数查询它:

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"

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

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