NoSql之旅--Cassandra的Cql簡介(二)


安裝完Cassandra后我們就開始體驗一下這個數據庫的查詢吧,傳統的關系數據庫使用的sql進行查詢,而Cassandra使用的cql.

cql語法還是很多的,這里不一一詳細闡述了,也沒這個必要,具體的文檔數不勝數,這里只是把最最常用的查詢功能列舉出來.

首先打開命令行(或是powershell)進入Cassandra安裝目錄下的bin文件夾,執行cqlsh.bat(powershell下執行cqlsh也ok).這里我進入的是powershell.

//進入cql客戶端,powershell中直接用cqlsh登陸即可,cmd和命令行下需要使用cqlsh.bat進入
PS D:\apache-cassandra-2.1.7\bin> .\cqlsh Connected to Test Cluster at 127.0.0.1:9042. [cqlsh 5.0.1 | Cassandra 2.1.7 | CQL spec 3.2.0 | Native protocol v3] Use HELP for help. WARNING: pyreadline dependency missing. Install to enable tab completion. cqlsh>

先介紹一下keyspace,中文直譯為鍵值空間,實際是一種命名空間的概念,這個和關系數據庫中的數據庫的地位類似.然后我們查詢一下有哪些keyspace:

//顯示keyspace
cqlsh> describe keyspaces; mykeyspace simplex system_traces system

結果顯示查詢到4個keyspace,紅字表示部分.然后我們手動自己創建一個keyspace:

//創建keyspace
cqlsh> CREATE KEYSPACE IF NOT EXISTS myCas WITH REPLICATION = {'class': 'SimpleStrategy','replication_factor':1}; cqlsh> describe keyspaces; mycas mykeyspace simplex system_traces system

可以看到已經成功創建名字為mycas的keyspace.我們使用剛創建的keyspace:

//選擇keyspace
cqlsh> use mycas; cqlsh:mycas>

我們在當前keyspace下創建一個表user,並顯示當前keyspace下的所有表:

//創建表
cqlsh:mycas> CREATE TABLE user ( id int, user_name varchar, PRIMARY KEY (id) ); cqlsh:mycas> describe tables; user

結果所示,當前keyspace下只有我們剛剛創建的user表.向表中插入一條數據:

//向表中添加數據
cqlsh> use mycas; cqlsh:mycas> INSERT INTO users (id,user_name) VALUES (1,'zhangsan'); cqlsh:mycas> select * from users; id | user_name ----+----------- 1 | zhangsan

然后我們進行一下簡單的條件查詢:

//從表中查詢數據
cqlsh:mycas> select * from users where id=1; id | user_name ----+----------- 1 | zhangsan (1 rows) cqlsh:mycas> select * from users where user_name='zhangsan'; InvalidRequest: code=2200 [Invalid query] message="No secondary indexes on the restricted columns support the provided o perators: "

可以看出查詢主鍵可以,但是查詢沒有索引的user_name卻無法查詢.

我們創建一個索引后再次嘗試:

//創建索引
cqlsh:mycas> create index on users(user_name); cqlsh:mycas> select * from users where user_name='zhangsan'; id | user_name ----+----------- 1 | zhangsan

試一下更新:

//更新表中數據
cqlsh:mycas> update users set user_name='lisi'; SyntaxException: <ErrorMessage code=2000 [Syntax error in CQL query] message="line 1:33 mismatched input ';' expecting K _WHERE"> cqlsh:mycas> update users set user_name='lisi' where id=1; cqlsh:mycas> select * from users; id | user_name ----+----------- 1 | lisi

可以看出只能按照條件進行更新.

試一下刪除:

//刪除表中數據
SyntaxException: <ErrorMessage code=2000 [Syntax error in CQL query] message="line 1:17 mismatched input ';' expecting K _WHERE"> cqlsh:mycas> delete from users where id=1; cqlsh:mycas> select * from users; id | user_name ----+----------- (0 rows)

可以看出刪除也只能按照條件進行刪除.

更多具體的命令可以參看Cassandra的官方cql文檔,非常全面.


免責聲明!

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



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