Cassandra之中一共包含下面5種Key:
- Primary Key
- Partition Key
- Composite Key
- Compound Key
- Clustering Key
首先,
Primary key 是用來獲取某一行的數據, 可以是一列或者多列(復合列 composite)
Primary = Partition Key + [Clustering Key] (Clustering Key 可選)
Clustering keys 包括下面兩種情況:
(1) composite key
(2) compound key
1
2
3
4
5
6
7
8
9
10
11
12
|
-- 一列
create table stackoverflow (
key text PRIMARY KEY,
data text
);
-- 復合列
create table stackoverflow (
key_part_one text,
key_part_two int,
data text,
PRIMARY KEY(key_part_one, key_part_two)
);
|
在上面復合列的table之中,全稱: Composite Primary Key
並且:
(1) key_part_one –> partition key
(2) key_part_two –> clustering key
注意: partition key, clustering key 都可以是復合列。
Partition Key : Cassandra會對partition key 做一個hash計算,並自己決定將這一條記錄放在哪個node
Partition Key的設計,可以完全的借用MySQL的主鍵。
Cassandra會給每一行數據一個timestamp,如果有多行數據,Cassandra會取時間最新的數據返回!
Clustering Key : 主要用於進行Range Query. 並且使用的時候需要按照建表順序進行提供信息!
參考下面代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
-- 創建表
-- 注意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);
xxxx more
insert into users (mainland, state, uid, name, zip)
VALUES ( 'southamerica', 'argentina', 6, 'alex', 10840);
|
有效的查詢:
1
|
select * from users where mainland = 'northamerica' and state > 'ca' and state < 'ny';
|
本質是先node上查找后,然后range篩選!