Redisで多対多の関係を持つ方法 質問する

Redisで多対多の関係を持つ方法 質問する

リレーショナル データベースには、多対多の関係を持つユーザー テーブル、カテゴリ テーブル、およびユーザー カテゴリ テーブルがあります。

Redis におけるこの構造の形式は何ですか?

ベストアンサー1

Redis では、関係は通常セットで表されます。セットは一方向の関係を表すために使用できるため、多対多の関係を表すにはオブジェクトごとに 1 つのセットが必要です。

リレーショナル データベース モデルを Redis データ構造と比較するのはほとんど無意味です。Redis では、すべてが非正規化された方法で保存されます。例:

# 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

このデータ構造を取得したら、集合代数を使用して簡単にクエリを実行できます。

# 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"

おすすめ記事