表結構:
CREATE TABLE employee
(
name TEXT,
age SMALLINT,
phone TEXT,
bornDate DATE,
createDate timestamp,
PRIMARY KEY ((bornDate),name, age,phone, createDate)
)
WITH compression = {
'chunk_length_in_kb' : 256,
'class' : 'LZ4Compressor',
'enabled' : true
} ;
select * from employee;
1.主鍵順序查詢限制
Cassandra對查詢的支持很弱,只支持主鍵列及索引列的查詢,而且主鍵列還有各種限制,不過查詢弱歸弱,但它還是支持索引和排序的。
cassandra:
索引列 支持 like
只有主鍵支持 group by
cassandra主鍵是一個partition key主鍵和多個clustering key複合主鍵,而主鍵的查詢順序必須與定義表結構時一致.
也就是說下面這種查詢錯的
select * from employee where age = 1 and name = '張三' and bornDate='1999-01-01'
而正確寫法應該是這樣
select * from employee where bornDate = '1999-01-01' and name ='張三' and age=1;
2. 分區主鍵查詢限制
cassandra中分區主鍵只能以 等號或in查詢,不能使用範圍查詢
也就是不能以出生日期進行範圍查詢
select * from employee where bornDate >='1999-01-01' and name='張三';
必須以出生日期in查詢,由於in查詢其實效率並不是太好,所以在表設計時應當注意
select * from employee where bornDate in ('1999-01-01','1999-01-02') and name = '張三';
3.範圍主鍵查詢限制
cassandra中範圍查詢只能放在條件查詢的最後一個位置,例如,如果範圍查詢age,則就不能添加phone查詢條件
也就是這麼寫法是錯的
select * from employee where bornDate = '2019-01-01' and name ='張三' and age >18 and phone = '123456'
當然也並不是不能這麼做,不過那樣必須加上ALLOW FILTERING
,
也就是下面這種寫法是沒問題的
select * from employee where bornDate = '2019-01-01' and name ='張三' and age >18 and phone = '123456' allow filtering;
4.排序規則
cassandra在創建表時設置一個排序規則,默認以此進行規則排序,如當前表,默認以正序age,正序bornDate和倒序createDate, 手動設置倒序只有一種方式,即將所有排序字段全部顛倒,也就是必須像這樣
select * from employee where bornDate in ('1999-01-01') and name = '張三' order by age desc, bornDate desc, createDate asc
5.排序對分區主鍵條件的限制
cassandra中只要使用排序,無論是使用默認排序規則還是相反排序規則,分區主鍵只能使用等於查詢,(可以使用in,但是隻能IN一個數據),
所以這樣寫就是錯誤
select * from employee where bornDate in ('1999-01-01','1999-01-02') and name = '張三' order by age desc, bornDate desc, createDate asc
應該
select * from employee where bornDate in ('1999-01-01') and name = '張三' order by age desc, bornDate desc, createDate asc
或
select * from employee where bornDate = '1999-01-01' and name = '張三' order by age desc, bornDate desc, createDate asc
6.使用In和Order by 時需要全局關閉分頁,
Cluster.Builder()
.AddContactPoints(cassandraUrls)
// 設置pageSize爲最大值,這樣代表爲關閉分頁,可以使用in 和order by
.WithQueryOptions(new QueryOptions().SetPageSize(int.MaxValue))
.Build();
總結:
1.查詢字段
Cassandra只支持主鍵列及索引列的查詢,而且主鍵列還有各種限制。
2.索引
支持索引查詢
索引列 支持 like
3.分組查詢:
只有主鍵支持 group by
4.鍵的限制:
• cassandra的查詢必須在主鍵列上,或者查詢的字段有二級索引。
• 對於(A,B)形式的主鍵,假如查詢條件不帶分區鍵A,則查詢語句需要開啓allow filtering。
• 對於((A,B),C,D)形式的主鍵,可以認爲是第2點的變種。A,B必須同時出現在查詢條件中(A和B合在一起決定分區),且C,D不可以跳躍,像where A and B and D的查詢是非法的。
• 以上查詢不考慮範圍查詢的情況。
• 所以因爲第三點的關係,parition key字段過多會對以後的查詢造成很大困擾,在建表的時候首先一定要考慮好數據模型,以免後期掉坑。
• 此外假如與spark集成的話,可以在一定程度上規避掉上面非法查詢的問題,通過sparksql可以近似實現關係型數據庫sql的查詢,而不用考慮查詢中一定要帶上所有partition key字段
5.二級索引:
Cassandra之中的索引的實現相對MySQL的索引來說就要簡單粗暴很多了。他實際上是自動偷偷新創建了一張表格,同時將原始表格之中的索引字段作爲新索引表的Primary Key!並且存儲的值爲原始數據的Primary Key