连接cassandra

cqlsh ip地址
cqlsh -u 'cassandra' -p 'cassandra'

查看表空间

describe keyspaces; 
describe keyspace {keyspace};

使用:

use keyspace;

查看已有表

describe tables;
use table;

查看表结构

describe table table_name;

Cassandra 提供了三种集合类型,分别是Set,List,Map。

  • Set
CREATE TABLE users (
  user_id text PRIMARY KEY,
  first_name text,
  last_name text,
  emails set<text>
);

//插入数据
INSERT INTO users (user_id, first_name, last_name, emails) VALUES('frodo', 'Frodo', 'Baggins', {'f@baggins.com', 'baggins@gmail.com'});

//更新数据
UPDATE users SET emails = emails + {'fb@friendsofmordor.org'} WHERE user_id = 'frodo';

//查询数据
SELECT user_id, emails FROM users WHERE user_id = 'frodo';

//删除数据
DELETE emails FROM users WHERE user_id = 'frodo';
UPDATE users SET emails = emails - {'fb@friendsofmordor.org'} WHERE user_id = 'frodo';
UPDATE users SET emails = {} WHERE user_id = 'frodo'; 
  • List
//添加字段
ALTER TABLE users ADD top_places list<text>;

//增加数据
UPDATE users SET top_places = [ 'rivendell', 'rohan' ] WHERE user_id = 'frodo';
UPDATE users SET top_places = [ 'the shire' ] + top_places WHERE user_id = 'frodo';
UPDATE users SET top_places = top_places + [ 'mordor' ] WHERE user_id = 'frodo';

//更新数据
UPDATE users SET top_places[2] = 'riddermark' WHERE user_id = 'frodo';

//删除
DELETE top_places[3] FROM users WHERE user_id = 'frodo';
UPDATE users SET top_places = top_places - ['riddermark'] WHERE user_id = 'frodo';
  • Map
ALTER TABLE users ADD todo map<timestamp, text>;

//增加数据(insert省略)
UPDATE users SET todo =
  { '2012-9-24' : 'enter mordor', '2014-10-2 12:00' : 'throw ring into mount doom' } WHERE user_id = 'frodo';
INSERT INTO users (user_id, todo) VALUES ('frodo', { '2013-9-22 12:01' : 'birthday wishes to Bilbo', '2013-10-1 18:00': 'Check into Inn of Pracing Pony'}) ;

//更新数据
UPDATE users SET todo['2014-10-2 12:00'] = 'throw my precious into mount doom' WHERE user_id = 'frodo';
UPDATE users SET todo = todo + { '2013-9-22 12:01' : 'birthday wishes to Bilbo', '2013-10-1 18:00': 'Check into Inn of Pracing Pony'} WHERE user_id='frodo';

//删除
DELETE todo['2013-9-22 12:01'] FROM users WHERE user_id = 'frodo';
UPDATE users SET todo=todo - {'2013-9-22 12:01','2013-10-01 18:00:00-0700'} WHERE user_id='frodo';
  • 使用TTL
UPDATE users USING TTL <computed_ttl> SET todo['2012-10-1'] = 'find water' WHERE user_id = 'frodo';
INSERT INTO users (user_name, password) VALUES ('cbrown', 'ch@ngem4a') USING TTL 86400;

在设定的computed_ttl数值秒后,数据会自动删除。

  • 集合添加索引
CREATE INDEX ON users(emails); CREATE INDEX mymapvalues ON users(todo);
DROP INDEX mymapvalues; CREATE INDEX mymapkeys ON playlists (KEYS(todo));
  • 过滤集合中的数据
SELECT user_id FROM users WHERE todo CONTAINS 'birthday wishes to Bilbo';
SELECT user_id FROM users WHERE todo CONTAINS KEY '2013-09-23 12:01:00-0700';

参考文档

更多推荐