Cassandra查詢操作趟坑記錄


例子表

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
        } AND CLUSTERING ORDER BY (age asc, bornDate asc, createDate desc )

1.主鍵順序查詢限制

​ 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();


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM