NoSQL一般是反范式的,比如提倡數據冗余,使得不至於寫出非常復雜的SQL語句。
Cassandra之中一共包含下面5中Key:
- Primary Key: 用來獲取某一行的數據,可以是一列或多列
PRIMARY KEY(key_part_one, key_part_two)
key_part_one - partition key
key_part_two - clustering key
PRIMARY KEY((k_part_one,k_part_two), k_clust_one, k_clust_two, k_clust_three)
復合的partition key, 復合的clustering key
- Partition Key: (用來進行分區的)Cassandra會對partition key做一個hash計算,並自己決定將記錄放到哪個NODE。 partition key 可以是單一主鍵,也可以是復合主鍵。但是主鍵不能重復。
Cassandra會給每一行數據一個timestamp,如果有多行數據,Cassandra會取時間最新的數據返回
- Composite Key:
- Compound Key:
- Clustering Key: 主要用於進行Range Query(范圍查找). 並且使用的時候需要按照建表順序進行提供信息。
-- 創建表 -- 注意state 這個field CREATE TABLE users ( mainland text, state text, uid int, name text, zip int, PRIMARY KEY ((mainland), state, uid) ) -- 插入一些值 insert into users (mainland, state, uid, name, zip) VALUES ( 'northamerica', 'washington', 1, 'john', 98100); insert into users (mainland, state, uid, name, zip) VALUES ( 'northamerica', 'texas', 2, 'lukas', 75000); insert into users (mainland, state, uid, name, zip) VALUES ( 'northamerica', 'delaware', 3, 'henry', 19904); insert into users (mainland, state, uid, name, zip) VALUES ( 'northamerica', 'delaware', 4, 'dawson', 19910); insert into users (mainland, state, uid, name, zip) VALUES ( 'centraleurope', 'italy', 5, 'fabio', 20150); insert into users (mainland, state, uid, name, zip) VALUES ( 'southamerica', 'argentina', 6, 'alex', 10840);
有效的查詢:
select * from users where mainland = 'northamerica' and state > 'ca' and state < 'ny';
(mainland), state, uid 構成聯合主鍵,其中mainland是partition key,是hash實現的,所以用=;而state 和UID是clustering key, 是sortedMap實現的可以用於做范 圍查找。 原理參考:
|
1
|
Map<RowKey, SortedMap<ColumnKey, ColumnValue>>
|
無效的查詢:
-- 沒有提供stat 信息 select * from users where mainland = 'northamerica' and uid < 5;
Cassandra 整體數據可以理解成一個巨大的嵌套的Map。 只能按順序一層一層的深入,不能跳過中間某一層~
create table stackoverflow ( key_part_one text, key_part_two int, data text, PRIMARY KEY(key_part_one, key_part_two) ); select * from stackoverflow where key_part_one = ‘ronaldo’; // 這個正確,沒有問題 select * from stackoverflow where key_part_two = 9 ALLOW FILTERING // 一定要有allow filterring
PRIMARY KEY((col1, col2), col3, col4))
正確的where查詢條件:
- col1 and col2
- col1 and col2 and col3
- col1 and col2 and col3 and col4
無效的where查詢條件:
col1 (這樣Cassandra無法找到在哪一行)
col1 and col2 and col4
anything that does not contain both col1 and col2
總結:
Cassandra之中的存儲,是2-level nested Map(2級嵌套map)
Partition Key –> Custering Key –> Data
partition key: 可以在where中使用 eq and in
clustering key: 可以在where中使用 < <= = >= > in
