2012-06-06 55 views

回答

27

使用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 

一旦我們有了這個數據結構,很容易使用集代數它來查詢:

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

謝謝!我是Redis的新手,這非常有趣:) – starikovs

+0

我們如何得到類別名稱smembers類別:2:這樣的用戶,因爲它給出了類別編號 – vaibhav

4

恕我直言,Redis不是用於製作結構化查詢(SQL),但是對於快速訪問數據,您可以做的是: 用user_id作爲關鍵字創建一個「表」,例如數據是與朋友的列表。然後你查詢user_id並處理你需要的東西。這與正常化相反。如果數據的順序是重要的,例如狀態更新,則所做的是將數據推入並彈出列表。例如,表「status」具有user_id作爲鍵,數據是一個列表。例如,你輸入數據然後查詢最後20個元素。