您的位置:首页 > 其它

Cassandra 的 cql入门使用

2016-06-28 23:03 267 查看
安装完Cassandra后我们就开始体验一下这个数据库的查询吧,传统的关系数据库使用的sql进行查询,而Cassandra使用的cql.
cql语法还是很多的,这里不一一详细阐述了,也没这个必要,具体的文档数不胜数,这里只是把最最常用的查询功能列举出来.
首先打开命令行(或是powershell)进入Cassandra安装目录下的bin文件夹,执行cqlsh

.\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;

system_traces  system

结果显示查询到2个keyspace,红字表示部分.然后我们手动自己创建一个keyspace:

//创建keyspace
cqlsh> CREATE KEYSPACE IF NOT EXISTS myCas WITH REPLICATION = {'class': 'SimpleStrategy','replication_factor':1};
cqlsh> describe keyspaces;

mycas   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)


可以看出删除也只能按照条件进行删除.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: