http://docs.datastax.com/en/cql/3.1/pdf/cql31.pdf

CQL是Cassandra Query Language的缩写,目前作为Cassandra默认并且主要的交互接口。CQL和SQL比较类似,主要的区别是Cassandra不支持join或子查询,除了支持通过Hive进行批处理分析。要说这个Cassandra以前的接口主要是Thrift API,这个没有用过,不做评价。

Cassandra在CQL语言层面支持多种数据类型[12]

CQL类型 对应Java类型 描述
ascii String ascii字符串
bigint long 64位整数
blob ByteBuffer/byte[] 二进制数组
boolean boolean 布尔
counter long 计数器,支持原子性的增减,不支持直接赋值
decimal BigDecimal 高精度小数
double double 64位浮点数
float float 32位浮点数
inet InetAddress ipv4ipv6协议的ip地址
int int 32位整数
list List 有序的列表
map Map 键值对
set Set 集合
text String utf-8编码的字符串
timestamp Date 日期
uuid UUID UUID类型
timeuuid UUID 时间相关的UUID
varchar string text的别名
varint BigInteger 高精度整型

cqlsh语法

cqlsh [options] [host [port]]
python cqlsh [options] [host [port]] 

Options

-C, --color
Always use color output.
--debug
Show additional debugging information.
--cqlshrc path
Use an alternative cqlshrc file location, path. (Cassandra 2.1.1)
-e cql_statement, --execute cql_statement
Accept and execute a CQL command in Cassandra 2.1 and later. Useful for saving CQL output to a file.
-f file_name, --file=file_name
Execute commands from file_name, then exit.
-h, --help
Show the online help about these options and exit.
-k keyspace_name
Use the given keyspace. Equivalent to issuing a USE keyspace command immediately after starting cqlsh.
--no-color
Never use color output.
-p password
Authenticate using password. Default = cassandra.
-t transport_factory_name, --transport=transport_factory_name
Use the provided Thrift transport factory function.
-u user_name
Authenticate as user. Default = cassandra.
--version
Show the cqlsh version.

启动CQL命令是cqlsh,我下面的例子是window上的,cassandra版本是2.1.14

示例:

#debug
D:\soft\cassandra\apache-cassandra-2.1.-bin\bin>cqlsh.bat --debug
Using CQL driver: <module 'cassandra' from 'D:\soft\cassandra\apache-cassandra-2.1.14-bin\bin\..\lib\cassandra-driver-in
ternal-only-2.7..zip\cassandra-driver-2.7.\cassandra\__init__.py'>
Using connect timeout: seconds
Connected to Test Cluster at 127.0.0.1:.
[cqlsh 5.0. | Cassandra 2.1. | CQL spec 3.2. | Native protocol v3]
Use HELP for help.
WARNING: pyreadline dependency missing. Install to enable tab completion. #version
D:\soft\cassandra\apache-cassandra-2.1.-bin\bin>cqlsh.bat --version
cqlsh 5.0.
#Saving CQL output in a file导出
D:\soft\cassandra\apache-cassandra-2.1.-bin\bin>cqlsh.bat -e "select * from duansf.users">myoutput.txt

导出的文件如下:

D:\soft\cassandra\apache-cassandra-2.1.14-bin\bin>cqlsh.bat

结果:cqlsh Can't detect Python version!

安装python,我安装的是64位的2.7版本,并配置下环境变量path中增加python的安装根路径。安装好后再执行cqlsh.bat

D:\soft\cassandra\apache-cassandra-2.1.14-bin\bin>cqlsh.bat

D:\soft\cassandra\apache-cassandra-2.1.-bin\bin>cqlsh.bat
Connected to Test Cluster at 127.0.0.1:.
[cqlsh 5.0. | Cassandra 2.1. | CQL spec 3.2. | Native protocol v3]
Use HELP for help.
WARNING: pyreadline dependency missing. Install to enable tab completion.

一、创建keyspace

作为对照,你可以把keyspace理解成一个SQL数据库实例,当然它们毕竟是不同的:Cassandra的keyspace是用来定义数据是如何在节点间复制的。通常情况下,应该为一个应用程序建立一个keyspace。

CREATE KEYSPACE IF NOT EXISTS pimin_net
WITH REPLICATION = {'class': 'SimpleStrategy','replication_factor':};

上面语句的意思是判断是否存在keyspace,如果不存在则建立keyspace;使用的副本策略是简单策略,复制因子是1。暂时先不管里面深层次的东西,我们先按照简单原则实现。

二、创建表

虽然说Cassandra是面向列的分布式数据库,但是它也有表的概念。创建之前先use pimin_net。

USE pimin_net;

CREATE TABLE users (
id int,
user_name varchar,
PRIMARY KEY (id) );
 

这样就建立了一张用户表,为了简单起见,就只有两个字段,看起来和oracle、mysql这些是不是很像?

三、对表的CRUD

已经有了一张用户表,我们就向里面插入一些数据,对它进行查询、更新和删除操作。

INSERT INTO users (id,user_name) VALUES (,'china');
INSERT INTO users (id,user_name) VALUES (,'taiwan');
SELECT * FROM users;
结果:
cqlsh:pimin_net> SELECT * FROM users;

 id | user_name
----+----------- ( rows)
cqlsh:pimin_net> INSERT INTO users (id,user_name) VALUES (,'china');
cqlsh:pimin_net> INSERT INTO users (id,user_name) VALUES (,'taiwan');
cqlsh:pimin_net> SELECT * FROM users; id | user_name
----+-----------
| china
| taiwan ( rows)
cqlsh:pimin_net>
UPDATE users SET user_name = 'china2014' WHERE id = ;
SELECT * FROM users;
DELETE FROM users WHERE id = ;
SELECT * FROM users;

结果:

cqlsh:pimin_net> UPDATE users SET user_name = 'china2014' WHERE id = ;
cqlsh:pimin_net> SELECT * FROM users; id | user_name
----+-----------
| china2014
| taiwan ( rows)
cqlsh:pimin_net> DELETE FROM users WHERE id = ;
cqlsh:pimin_net> SELECT * FROM users; id | user_name
----+-----------
| taiwan ( rows)
cqlsh:pimin_net>

重要:不同于传统的RDBMS,Cassandra不能使用DELETE FROM users;这样的表达式,必须有WHERE条件!

重要:不同于传统的RDBMS,Cassandra不能使用DELETE FROM users;这样的表达式,必须有WHERE条件!

示例2:

cqlsh:usermanager> use duansf

1.创建keyspace

cqlsh:usermanager> create keyspace duansf WITH REPLICATION = {'class': 'SimpleStrategy','replication_factor':};

创建一个名为duansf的keyspace,副本策略SimpleStrategy,复制因子为1.

2.创建Column family

cqlsh>use duansf;
cqlsh:duansf> create columnfamily users(
key varchar primary key,
password varchar,
gender varchar,
session_token varchar,
state varchar,
birth_year bigint);

创建一个名为users的column family

...  KEY varchar PRIMARY KEY,该columnfamily下有一个Key

和5列

...  password varchar,

...  gende rvarchar,

...  session_token varchar,

...  state varchar,

...  birth_year bigint);

3.插入和检索Columns

cqlsh:duansf> insert into users(key,password) values('jsmith','chadsfl') using ttl 86400;

向passwod这一列插入数据

cqlsh:duansf> select * from users where key='jsmith';

 key    | birth_year | gender | password | session_token | state
--------+------------+--------+----------+---------------+-------
jsmith | null | null | chadsfl | null | null ( rows)
cqlsh:duansf>

向session_token这一列插入数据

cqlsh:duansf> insert into users(key,session_token) values('jsmith','test') using ttl ;
cqlsh:duansf> select * from users where key='jsmith'; key | birth_year | gender | password | session_token | state
--------+------------+--------+----------+---------------+-------
jsmith | null | null | chadsfl | test | null

3.向Column family中增加Column

cqlsh:duansf> alter table user add coupon_code varchar;

注意:其他已经存在的列不会进行更新。

4. 更改Column的元数据

cqlsh:duansf> alter table users alter coupon_code type int;
ConfigurationException: <ErrorMessage code= [Query invalid because of configuration issue] message="Cannot change co
upon_code from type text to type int: types are incompatible.">

注意:已经存在的数据不会转成此类型,新插入的数据才是该类型的。

5.使用TTL属性设置列的到期时间

cqlsh:duansf> update users using ttl  set password='asldkjsfsdf' where key = 'jsmith';

更新密码列的到期时间为5天。

6.删除列元数据

cqlsh:duansf> alter table users drop coupon_code;

7.索引Column

cqlsh:duansf> create index state_key on users(state);
cqlsh:duansf> create index birth_year_key on users(birth_year);

8.删除列或者行

cqlsh:duansf> delete session_token from users where key='jsmith';  //删除session_token列
cqlsh:duansf> select * from users; key | birth_year | gender | password | session_token | state
--------+------------+--------+-------------+---------------+-------
jsmith | null | null | asldkjsfsdf | null | null ( rows)
cqlsh:duansf> delete from users where key='jsmith'; //删除key=jsmith的行
cqlsh:duansf> select * from users; key | birth_year | gender | password | session_token | state
-----+------------+--------+----------+---------------+------- ( rows)
cqlsh:duansf>

9. 删除columnfamily和keyspace

cqlsh:duansf> drop columnfamily users;
cqlsh:duansf> insert into users(key,password) values('jsmith','chadsfl') using ttl ;
InvalidRequest: code= [Invalid query] message="unconfigured columnfamily users"
cqlsh:duansf>

删除keyspace

cqlsh:duansf> drop keyspace duansf;
cqlsh:duansf> use duansf;
InvalidRequest: code= [Invalid query] message="Keyspace 'duansf' does not exist"
cqlsh:duansf>

10.查看结构信息

cqlsh:usermanager> desc users;

CREATE TABLE usermanager.users (
key blob PRIMARY KEY,
age text,
name text
) WITH bloom_filter_fp_chance = 0.01
AND caching = '{"keys":"ALL", "rows_per_partition":"NONE"}'
AND comment = ''
AND compaction = {'class': 'org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy'}
AND compression = {'sstable_compression': 'org.apache.cassandra.io.compress.LZ4Compressor'}
AND dclocal_read_repair_chance = 0.1
AND default_time_to_live =
AND gc_grace_seconds =
AND max_index_interval =
AND memtable_flush_period_in_ms =
AND min_index_interval =
AND read_repair_chance = 0.0
AND speculative_retry = '99.0PERCENTILE';

CQL操作的更多相关文章

  1. Cassandra 之 入门

    1.到官网下载压缩包. http://cassandra.apache.org/download/ 我下载的是最新的 apache-cassandra-2.1.2-bin.tar.gz 另外:语言支持 ...

  2. cassandra 在window上的demo

    Cassandra   window使用 1.        下载:http://cassandra.apache.org/download/. 2.        解压后,bin目录下,cassan ...

  3. Cassandra 数据库, python cqlsh命令

    ★  cql操作数据库(cqlsh.bat: python cqlsh命令操作<优缺点:https://blog.csdn.net/vbirdbest/article/details/77662 ...

  4. Atitit.nosql api 标准化 以及nosql数据库的实现模型分类差异

    Atitit.nosql api 标准化 以及nosql数据库的实现模型分类差异 1. 常用的nosql数据库MongoDB  Cassandra1 1.1. 查询> db.blogposts. ...

  5. cassandra CQL 常用操作

    1. CQL客户端链接 bin/cqlsh ip username password 2. (1)建立keyspace语句,keyspace类似于 mysql 中的数据库,一个数据库中可以有很多表: ...

  6. CQL和SQL的CRUD操作比较

    数据进行CRUD操作时,CQL语句和SQL语句的异同之处. 1.建表 2.CRUD语句比较 3.总结 1.建表 在此之前先分别创建两张表,插入数据,用来测试然后进行比较 在SQL数据库里面创建表 在C ...

  7. cassandra CQL 3.0 怎样实现 dynamic column;

    1. cassandra有一个好的特点是列之间可以按照column key进行排序:这样当rowkey确定以后,对于同一个“行”的范围(range query)查找是很方便的:官方说法,每一个“行”( ...

  8. PLSQL_闪回操作4_Flashback Drop

    2014-06-25 Created By BaoXinjian

  9. Cassandra 数据模型 (基于CQL,解决胖列数量限制及灵活性问题)(1.1及以上版本)

    文中主要交代Cassandra的编程模型及数据结构. 由于Cassandra版本数次更新,网上中文的资料已经有点过时,比较有代表性的比如ebuy那篇文章都已经过时了,于是自己找资料,结合官方博客写一篇 ...

随机推荐

  1. C函数之memcpy()函数用法

    函数原型 void *memcpy(void*dest, const void *src, size_t n); 功能 由src指向地址为起始地址的连续n个字节的数据复制到以destin指向地址为起始 ...

  2. OSGi 的由来和本质特性

    OSGi 的由来 随着科技和需求的发展和变化,现在的软件变得越来越庞大.这样,随之而来的最大挑战就是软件在设计上的越来越复杂和维护上的越来越困难.为了解决这个问题,软件架构师将软件切分成比较小的并且易 ...

  3. 元组的cmp()内建函数

    >>> list1,list2=[,,'abc'] >>> cmp(list1,list2) - >>> cmp(list2,list1) > ...

  4. HTML,XML中的转义字符

    HTML中的转义字符 HTML中<, >,&等有特别含义,(前两个字符用于链接签,&用于转义),不能直接使用.使用这三个字符时,应使用他们的转义序列,如下所示: & ...

  5. noip2011普及组——统计单词数

    统计单词数 时间限制:1 s 内存限制:128MB [问题描述]一般的文本编辑器都有查找单词的功能,该功能可以快速定位特定单词在文章中的位置,有的还能统计出特定单词在文章中出现的次数.现在,请你编程实 ...

  6. android layout_weight 使用总结

    今天在使用androidlayout_weight的时候遇到点奇怪的问题,就上网查了一下,发现这篇文章很详细,就转了过来,谢谢分享者,写的很详细.  在 android开发中LinearLayout很 ...

  7. 【linux】CentOS安装mysql*.rpm提示conflicts with file from package的解决办法

    使用以下命令安装: rpm -ivh MySQL-server-5.6.19-1.linux_glibc2.5.x86_64.rpm 错误提示如下: Preparing...              ...

  8. [原]Linux系统管理使用技巧总结

    一.磁盘管理 1.查看磁盘空间大小 df可以查看一级文件夹大小.使用比例.档案系统及其挂入点,但对文件却无能为力. du可以查看文件及文件夹的大小.如果不带其他参数(-h表示human-readabl ...

  9. 解决关于jquery中$.get()方法总是报“HierarchyRequestError: Node cannot be inserted at the specified point in the hierarchy”错的方法

    解决关于jquery中$.get()方法总是报“HierarchyRequestError: Node cannot be inserted at the specified point in the ...

  10. UI-导航控制器的使用

    1.初始化导航栏控制器 2..设置导航栏的标题 3.跳到下一个页面 4.返回上一个页面 5.自定义返回页面 6.导航栏上的自定义返回按钮 7.两个导航栏显示隐藏的常用方法(当前页不显示)