2014-01-12 65 views
1

我是Cassandra的新成員,並嘗試瞭解數據模型。所以我知道如果「鮑勃」跟隨「詹姆斯」如何插入。我也知道如何查詢以獲得所有跟隨「bob」的人的列表,並且我知道如何查詢以獲得「bob」跟隨者的列表。Cassandra DataModel查詢

我的問題是,鑑於下面,查詢是什麼樣子,如果我想知道「bob」是否跟隨「詹姆斯」? (是或否)

這是正確的查詢嗎?

SELECT * FROM followers WHERE username="bob" AND following="james" 

我是否需要設置第二個索引關於以下才能執行上述查詢?

-- User storage 
CREATE TABLE users (username text PRIMARY KEY, password text); 

-- Users user is following 
CREATE TABLE following (
    username text, 
    followed text, 
    PRIMARY KEY(username, followed) 
); 

-- Users who follow user 
CREATE TABLE followers (
    username text, 
    following text, 
    PRIMARY KEY(username, following) 
); 

回答

1

在這種情況下不需要二級索引。你總是可以使用cqlsh shell來測試這種快速的想法。

cqlsh> use ks; 
cqlsh:ks> CREATE TABLE followers (
     ...  username text, 
     ...  following text, 
     ...  PRIMARY KEY(username, following) 
     ...); 
cqlsh:ks> INSERT INTO followers (username, following) VALUES ('bob', 'james'); 
cqlsh:ks> SELECT * FROM followers WHERE username='bob' and following='james'; 

username | following 
----------+----------- 
     bob |  james 

爲什麼你沒有做的次級指數(也不應該,如果你想進行這種查詢的規模化)的原因是因爲「下」被指定爲聚集鍵。這意味着'跟隨'描述了分區中數據的佈局,這意味着我們可以非常快速地對'跟隨'進行過濾。另外,如果頻繁執行的查詢需要二級索引(允許過濾),這表明您應該重新考慮您的數據模型。