Cassandra数据库与Cql实战笔记

简介: Cassandra数据库与Cql实战笔记

启动数据库

[zdaxctid@node3 bin]$ pwd
/home/database/apache-cassandra-3.11.7/bin
#启动数据库
[zdaxctid@node3 bin]$ ./cassandra

成功标志:

查看数据库节点启动成功状态

[zdaxctid@node3 bin]$ ./nodetool status
Datacenter: datacenter1
=======================
Status=Up/Down
|/ State=Normal/Leaving/Joining/Moving
--  Address         Load       Tokens       Owns (effective)  Host ID                               Rack
DN  192.168.10.11   ?          256          100.0%            3240fa95-cc32-40f9-8c5d-ff53b9b86adc  rack1
UN  192.168.10.141  405.56 KiB  256          100.0%            468c9c1c-a1d4-4eda-a59a-31793df44d10  rack1
[zdaxctid@node3 bin]$

关闭数据库

杀掉数据库进程相关的pid号即可!!

[root@node3 ~]# kill -9 106206
[root@node3 ~]# ps -ef | grep cassandra
root     119880 103558  0 10:39 pts/3    00:00:00 grep --color=auto cassandra
[root@node3 ~]#

使用cqlsh工具

[zdaxctid@node3 bin]$ ./cqlsh 192.168.10.141 9042
Connected to Test Cluster at 192.168.10.141:9042.
[cqlsh 5.0.1 | Cassandra 3.11.7 | CQL spec 3.4.4 | Native protocol v3]
Use HELP for help.
cqlsh>

常见命令

查看集群信息

cqlsh> describe cluster;
Cluster: Test Cluster
Partitioner: Murmur3Partitioner
cqlsh> DESCRIBE tables;
Keyspace system_schema
----------------------
tables     triggers    views    keyspaces  dropped_columns
functions  aggregates  indexes  types      columns        
Keyspace system_auth
--------------------
resource_role_permissons_index  role_permissions  role_members  roles
Keyspace system
---------------
available_ranges          peers               batchlog        transferred_ranges
batches                   compaction_history  size_estimates  hints             
prepared_statements       sstable_activity    built_views   
"IndexInfo"               peer_events         range_xfers   
views_builds_in_progress  paxos               local         
Keyspace system_distributed
---------------------------
repair_history  view_build_status  parent_repair_history
Keyspace system_traces
----------------------
events  sessions
Keyspace flowmonitoringsystem
-----------------------------
auth_28_tcp_alarm_value  auth_28_tcp_flow                auth_28_node
auth_28_alarm_config     auth_28_business_number_index   user        
auth_28_server           auth_ip_alarm_config          
auth_28_link             auth_28_thrice_hand_shake     
auth_28_second           auth_28_second_alarm_history  
auth_28_mode_config      auth_28_tcp_flow_alarm_history
auth_28_second_history   ywzd_user                     
cqlsh> use system_traces;
Invalid syntax at line 1, char 18
  use system_traces;
                   ^
cqlsh> use system_traces;
cqlsh:system_traces> DESCRIBE tables
events  sessions
cqlsh:system_traces> describe sessions
CREATE TABLE system_traces.sessions (
    session_id uuid PRIMARY KEY,
    client inet,
    command text,
    coordinator inet,
    coordinator_port int,
    duration int,
    parameters map<text, text>,
    request text,
    started_at timestamp
) WITH bloom_filter_fp_chance = 0.01
    AND caching = {'keys': 'ALL', 'rows_per_partition': 'NONE'}
    AND comment = 'tracing sessions'
    AND compaction = {'class': 'org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy', 'max_threshold': '32', 'min_threshold': '4'}
    AND compression = {'chunk_length_in_kb': '64', 'class': 'org.apache.cassandra.io.compress.LZ4Compressor'}
    AND crc_check_chance = 1.0
    AND dclocal_read_repair_chance = 0.0
    AND default_time_to_live = 0
    AND gc_grace_seconds = 0
    AND max_index_interval = 2048
    AND memtable_flush_period_in_ms = 3600000
    AND min_index_interval = 128
    AND read_repair_chance = 0.0
    AND speculative_retry = '99PERCENTILE';
cqlsh:system_traces> show
Improper show command.
cqlsh:system_traces> SHOW 
Improper SHOW command.
cqlsh:system_traces> quit;
[zdaxctid@node3 bin]$ ./cqlsh 192.168.10.141 9042
Connected to Test Cluster at 192.168.10.141:9042.
[cqlsh 5.0.1 | Cassandra 3.11.7 | CQL spec 3.4.4 | Native protocol v3]
Use HELP for help.
cqlsh> show
Improper show command.
cqlsh> showkey
   ... 
   ... ;
SyntaxException: line 1:0 no viable alternative at input 'showkey' ([showkey]...)
cqlsh> 
cqlsh> show host
Connected to Test Cluster at 192.168.10.141:9042.
cqlsh> show session
Improper show command.
cqlsh> show version
[cqlsh 5.0.1 | Cassandra 3.11.7 | CQL spec 3.4.4 | Native protocol v3]
cqlsh>

数据定义命令

数据操作命令

操作健空间

创建Keyspace

语法

cqlsh> create keyspace school with replication={'class':'SimpleStrategy','replication_factor':3};
school         system_auth  system_distributed  flowmonitoringsystem
system_schema  system       system_traces     
cqlsh> describe school;
CREATE KEYSPACE school WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '3'}  AND durable_writes = true;
cqlsh>

连接健空间

cqlsh> use school;
cqlsh:school> alter keyspace school with replication={'class':'SimpleStrategy','replication_factor':1};

删除健空间

cqlsh:school> drop keyspace school;
cqlsh:school> 
cqlsh:school> 
cqlsh:school> describe keyspaces;
system_schema  system              system_traces       
system_auth    system_distributed  flowmonitoringsystem
cqlsh:school>

创建表

创建语句类似于sql语句!

create table student(
  id int primary key,
    name text,
    age int,
    gender tinyint,
    address text,
    interest set<text>,
    phone list<text>,
    education map<text,text>
);
cqlsh:test> create table student(
        ... id int primary key,
        ...     name text,
        ...     age int,
        ...     gender tinyint,
        ...     address text,
        ...     interest set<text>,
        ...     phone list<text>,
        ...     education map<text,text>
        ... );
Warning: schema version mismatch detected; check the schema versions of your nodes in system.local and system.peers.
cqlsh:test> describe test
CREATE KEYSPACE test WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '1'}  AND durable_writes = true;
CREATE TABLE test.student (
    id int PRIMARY KEY,
    address text,
    age int,
    education map<text, text>,
    gender tinyint,
    interest set<text>,
    name text,
    phone list<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', 'max_threshold': '32', 'min_threshold': '4'}
    AND compression = {'chunk_length_in_kb': '64', 'class': 'org.apache.cassandra.io.compress.LZ4Compressor'}
    AND crc_check_chance = 1.0
    AND dclocal_read_repair_chance = 0.1
    AND default_time_to_live = 0
    AND gc_grace_seconds = 864000
    AND max_index_interval = 2048
    AND memtable_flush_period_in_ms = 0
    AND min_index_interval = 128
    AND read_repair_chance = 0.0
    AND speculative_retry = '99PERCENTILE';
cqlsh:test> describe tables;
student
cqlsh:test>

主键

create table testTab(
  key_part_one int,
  key_part_two int,
  key_clust_one int,
  key_clust_two int,
  key_clust_three uuid,
  name text,
  primary key((key_part_one,key_part_two),key_clust_one,key_clust_two,key_clust_three)
);
cqlsh:test> use test01;
cqlsh:test01> create table testTab(
          ... key_part_one int,
          ... key_part_two int,
          ... key_clust_one int,
          ... key_clust_two int,
          ... key_clust_three uuid,
          ... name text,
          ... primary key((key_part_one,key_part_two),key_clust_one,key_clust_two,key_clust_three)
          ... );
Warning: schema version mismatch detected; check the schema versions of your nodes in system.local and system.peers.
cqlsh:test01> 
cqlsh:test01> 
cqlsh:test01> describe tables;
testtab
cqlsh:test01> select * from testab
          ... ;
InvalidRequest: Error from server: code=2200 [Invalid query] message="unconfigured table testab"
cqlsh:test01> select * from testtab;
 key_part_one | key_part_two | key_clust_one | key_clust_two | key_clust_three | name
--------------+--------------+---------------+---------------+-----------------+------
(0 rows)
cqlsh:test01>

表修改

添加列

cqlsh:test> alter table testtab add email text;

cqlsh:test> describe keyspaces;
system_schema  system              test           test01              
system_auth    system_distributed  system_traces  flowmonitoringsystem
cqlsh:test> describe tables;
testtab  student
cqlsh:test> alter table testtab add email text;
Warning: schema version mismatch detected; check the schema versions of your nodes in system.local and system.peers.
cqlsh:test> 
cqlsh:test> describe testtab;
CREATE TABLE test.testtab (
    key_part_one int,
    key_part_two int,
    key_clust_one int,
    key_clust_two int,
    key_clust_three uuid,
    email text,
    name text,
    PRIMARY KEY ((key_part_one, key_part_two), key_clust_one, key_clust_two, key_clust_three)
) WITH CLUSTERING ORDER BY (key_clust_one ASC, key_clust_two ASC, key_clust_three ASC)
    AND 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', 'max_threshold': '32', 'min_threshold': '4'}
    AND compression = {'chunk_length_in_kb': '64', 'class': 'org.apache.cassandra.io.compress.LZ4Compressor'}
    AND crc_check_chance = 1.0
    AND dclocal_read_repair_chance = 0.1
    AND default_time_to_live = 0
    AND gc_grace_seconds = 864000
    AND max_index_interval = 2048
    AND memtable_flush_period_in_ms = 0
    AND min_index_interval = 128
    AND read_repair_chance = 0.0
    AND speculative_retry = '99PERCENTILE';
cqlsh:test>
删除列

cqlsh:test> alter table testtab drop email;

cqlsh:test> alter table testtab drop email;
Warning: schema version mismatch detected; check the schema versions of your nodes in system.local and system.peers.
cqlsh:test> describe testtab;
CREATE TABLE test.testtab (
    key_part_one int,
    key_part_two int,
    key_clust_one int,
    key_clust_two int,
    key_clust_three uuid,
    name text,
    PRIMARY KEY ((key_part_one, key_part_two), key_clust_one, key_clust_two, key_clust_three)
) WITH CLUSTERING ORDER BY (key_clust_one ASC, key_clust_two ASC, key_clust_three ASC)
    AND 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', 'max_threshold': '32', 'min_threshold': '4'}
    AND compression = {'chunk_length_in_kb': '64', 'class': 'org.apache.cassandra.io.compress.LZ4Compressor'}
    AND crc_check_chance = 1.0
    AND dclocal_read_repair_chance = 0.1
    AND default_time_to_live = 0
    AND gc_grace_seconds = 864000
    AND max_index_interval = 2048
    AND memtable_flush_period_in_ms = 0
    AND min_index_interval = 128
    AND read_repair_chance = 0.0
    AND speculative_retry = '99PERCENTILE';
cqlsh:test>
删除表

cqlsh:test> drop table testtab;

cqlsh:test> drop table testtab;
Warning: schema version mismatch detected; check the schema versions of your nodes in system.local and system.peers.
cqlsh:test> 
cqlsh:test> describe tables;
student
cqlsh:test> select * from testtab;
InvalidRequest: Error from server: code=2200 [Invalid query] message="unconfigured table testtab"
cqlsh:test>
清空表
cqlsh:test> truncate student;

添加数据

INSERT INTO student (id,address,age,gender,name,interest, phone,education) VALUES (1011,'中山路21号',16,1,'Tom',{'游泳', '跑步'},['010-88888888','13888888888'],{'小学' : '城市第一小学', '中学' : '城市第一中学'})

INSERT INTO student (id,address,age,gender,name,interest, phone,education) VALUES (1012,'朝阳路19号',17,2,'Jerry',{'看书', '电影'},['020-66666666','13666666666'],{'小学' :'城市第五小学','中学':'城市第六中学'});

数据过期时间

using ttl 30

数据30秒以后清空!

INSERT INTO student (id,address,age,gender,name,interest, phone,education) VALUES (1013,'朝阳路19号',17,2,'Linghu',{'看书', '电影'},['020-66666666','13666666666'],{'小学' :'城市第五小学','中学':'城市第六中学'})using ttl 30;

查询数据

cqlsh:test> select * from student where id = 1011;

更新数据

更新简单数据

更新表中的数据:

cqlsh:test> update student set gender = 0 where id = 1011;

更新set类型数据

在student表中,interest列是set类型

添加一个元素

update和+

cqlsh:test> update student set interest = interest+{'打太极'} where id = 1011;

删除一个元素

update和-

cqlsh:test> update student set interest = interest-{'打太极'} where id = 1011;

删除所有元素

update或者delete命令

UPDATE student SET interest = {} WHERE student_id = 1012;
DELETE interest FROM student WHERE student_id = 1012;

更新list类型数据

在student中phone就是list类型

使用UPDATA命令向list插入值

cqlsh:test> UPDATE student SET phone = [‘020-66666666’, ‘13666666666’,‘1714873054’] WHERE id = 1012;

在list前面插入值

cqlsh:test> UPDATE student SET phone = [ ‘030-55555555’ ] + phone WHERE id = 1012;

在list后面插入值

cqlsh:test> UPDATE student SET phone = phone + [ ‘040-33333333’ ] WHERE id = 1012;

#使用UPDATA命令向list插入值
cqlsh:test> UPDATE student SET phone = ['020-66666666', '13666666666','1714873054'] WHERE id = 1012;
cqlsh:test> select * from student;
 id   | address    | age | education                                        | gender | interest         | name  | phone
------+------------+-----+--------------------------------------------------+--------+------------------+-------+-----------------------------------------------
 1011 | 中山路21号 |  16 | {'中学': '城市第一中学', '小学': '城市第一小学'} |      0 | {'游泳', '跑步'} |   Tom |               ['010-88888888', '13888888888']
 1012 | 朝阳路19号 |  17 | {'中学': '城市第六中学', '小学': '城市第五小学'} |   null | {'电影', '看书'} | Jerry | ['020-66666666', '13666666666', '1714873054']
(2 rows)
#在list前面插入值
cqlsh:test> UPDATE student SET phone = [ '030-55555555' ] + phone WHERE id = 1012;
cqlsh:test> select * from student;
 id   | address    | age | education                                        | gender | interest         | name  | phone
------+------------+-----+--------------------------------------------------+--------+------------------+-------+---------------------------------------------------------------
 1011 | 中山路21号 |  16 | {'中学': '城市第一中学', '小学': '城市第一小学'} |      0 | {'游泳', '跑步'} |   Tom |                               ['010-88888888', '13888888888']
 1012 | 朝阳路19号 |  17 | {'中学': '城市第六中学', '小学': '城市第五小学'} |   null | {'电影', '看书'} | Jerry | ['030-55555555', '020-66666666', '13666666666', '1714873054']
(2 rows)
#在list后面插入值
cqlsh:test> UPDATE student SET phone = phone + [ '040-33333333' ]  WHERE id = 1012;
cqlsh:test> select * from student;
 id   | address    | age | education                                        | gender | interest         | name  | phone
------+------------+-----+--------------------------------------------------+--------+------------------+-------+-------------------------------------------------------------------------------
 1011 | 中山路21号 |  16 | {'中学': '城市第一中学', '小学': '城市第一小学'} |      0 | {'游泳', '跑步'} |   Tom |                                               ['010-88888888', '13888888888']
 1012 | 朝阳路19号 |  17 | {'中学': '城市第六中学', '小学': '城市第五小学'} |   null | {'电影', '看书'} | Jerry | ['030-55555555', '020-66666666', '13666666666', '1714873054', '040-33333333']
(2 rows)
cqlsh:test>
更新map类型数据

map输出顺序取决于map类型。

使用insert和update命令
cqlsh:test> update student set education = {'中学':'桐梓一中','小学':'南天门'} where id = 1012;
cqlsh:test> select * from student;
 id   | address    | age | education                                        | gender | interest         | name  | phone
------+------------+-----+--------------------------------------------------+--------+------------------+-------+-------------------------------------------------------------------------------
 1011 | 中山路21号 |  16 | {'中学': '城市第一中学', '小学': '城市第一小学'} |      0 | {'游泳', '跑步'} |   Tom |                                               ['010-88888888', '13888888888']
 1012 | 朝阳路19号 |  17 |           {'中学': '桐梓一中', '小学': '南天门'} |   null | {'电影', '看书'} | Jerry | ['030-55555555', '020-66666666', '13666666666', '1714873054', '040-33333333']
(2 rows)
cqlsh:test>
删除元素
可以用DELETE 和 UPDATE 删除Map类型中的数据

使用DELETE删除数据可以用DELETE 和 UPDATE 删除Map类型中的数据

使用DELETE删除数据

cqlsh:test> delete education['中学'] from student where id = 1012;
cqlsh:test> select * from student;
 id   | address    | age | education                                        | gender | interest         | name  | phone
------+------------+-----+--------------------------------------------------+--------+------------------+-------+-------------------------------------------------------------------------------
 1011 | 中山路21号 |  16 | {'中学': '城市第一中学', '小学': '城市第一小学'} |      0 | {'游泳', '跑步'} |   Tom |                                               ['010-88888888', '13888888888']
 1012 | 朝阳路19号 |  17 |                               {'小学': '南天门'} |   null | {'电影', '看书'} | Jerry | ['030-55555555', '020-66666666', '13666666666', '1714873054', '040-33333333']
(2 rows)
cqlsh:test>
删除行

删除student中student_id=1012 的数据

cqlsh:test> delete from student where id = 1012;
cqlsh:test> select * from student;
 id   | address    | age | education                                        | gender | interest         | name | phone
------+------------+-----+--------------------------------------------------+--------+------------------+------+---------------------------------
 1011 | 中山路21号 |  16 | {'中学': '城市第一中学', '小学': '城市第一小学'} |      0 | {'游泳', '跑步'} |  Tom | ['010-88888888', '13888888888']
(1 rows)
cqlsh:test>

create table authtype(

id int primary key,

auth_type text,

foreing key (auth_type) references hostinfo (id)

);

delete from student where id = 1012;

cqlsh:test> select * from student;

id | address | age | education | gender | interest | name | phone

------±-----------±----±-------------------------------------------------±-------±-----------------±-----±--------------------------------

1011 | 中山路21号 | 16 | {‘中学’: ‘城市第一中学’, ‘小学’: ‘城市第一小学’} | 0 | {‘游泳’, ‘跑步’} | Tom | [‘010-88888888’, ‘13888888888’]

(1 rows)

cqlsh:test>


目录
相关文章
|
2天前
|
存储 缓存 关系型数据库
MySQL事务日志-Redo Log工作原理分析
事务的隔离性和原子性分别通过锁和事务日志实现,而持久性则依赖于事务日志中的`Redo Log`。在MySQL中,`Redo Log`确保已提交事务的数据能持久保存,即使系统崩溃也能通过重做日志恢复数据。其工作原理是记录数据在内存中的更改,待事务提交时写入磁盘。此外,`Redo Log`采用简单的物理日志格式和高效的顺序IO,确保快速提交。通过不同的落盘策略,可在性能和安全性之间做出权衡。
1529 4
|
18小时前
|
编解码 Java 程序员
写代码还有专业的编程显示器?
写代码已经十个年头了, 一直都是习惯直接用一台Mac电脑写代码 偶尔接一个显示器, 但是可能因为公司配的显示器不怎么样, 还要接转接头 搞得桌面杂乱无章,分辨率也低,感觉屏幕还是Mac自带的看着舒服
|
29天前
|
弹性计算 人工智能 架构师
阿里云携手Altair共拓云上工业仿真新机遇
2024年9月12日,「2024 Altair 技术大会杭州站」成功召开,阿里云弹性计算产品运营与生态负责人何川,与Altair中国技术总监赵阳在会上联合发布了最新的“云上CAE一体机”。
阿里云携手Altair共拓云上工业仿真新机遇
|
6天前
|
人工智能 Rust Java
10月更文挑战赛火热启动,坚持热爱坚持创作!
开发者社区10月更文挑战,寻找热爱技术内容创作的你,欢迎来创作!
525 20
|
2天前
|
存储 SQL 关系型数据库
彻底搞懂InnoDB的MVCC多版本并发控制
本文详细介绍了InnoDB存储引擎中的两种并发控制方法:MVCC(多版本并发控制)和LBCC(基于锁的并发控制)。MVCC通过记录版本信息和使用快照读取机制,实现了高并发下的读写操作,而LBCC则通过加锁机制控制并发访问。文章深入探讨了MVCC的工作原理,包括插入、删除、修改流程及查询过程中的快照读取机制。通过多个案例演示了不同隔离级别下MVCC的具体表现,并解释了事务ID的分配和管理方式。最后,对比了四种隔离级别的性能特点,帮助读者理解如何根据具体需求选择合适的隔离级别以优化数据库性能。
186 2
|
9天前
|
JSON 自然语言处理 数据管理
阿里云百炼产品月刊【2024年9月】
阿里云百炼产品月刊【2024年9月】,涵盖本月产品和功能发布、活动,应用实践等内容,帮助您快速了解阿里云百炼产品的最新动态。
阿里云百炼产品月刊【2024年9月】
|
21天前
|
存储 关系型数据库 分布式数据库
GraphRAG:基于PolarDB+通义千问+LangChain的知识图谱+大模型最佳实践
本文介绍了如何使用PolarDB、通义千问和LangChain搭建GraphRAG系统,结合知识图谱和向量检索提升问答质量。通过实例展示了单独使用向量检索和图检索的局限性,并通过图+向量联合搜索增强了问答准确性。PolarDB支持AGE图引擎和pgvector插件,实现图数据和向量数据的统一存储与检索,提升了RAG系统的性能和效果。
|
9天前
|
Linux 虚拟化 开发者
一键将CentOs的yum源更换为国内阿里yum源
一键将CentOs的yum源更换为国内阿里yum源
486 5
|
8天前
|
存储 人工智能 搜索推荐
数据治理,是时候打破刻板印象了
瓴羊智能数据建设与治理产品Datapin全面升级,可演进扩展的数据架构体系为企业数据治理预留发展空间,推出敏捷版用以解决企业数据量不大但需构建数据的场景问题,基于大模型打造的DataAgent更是为企业用好数据资产提供了便利。
318 2
|
5天前
|
XML 安全 Java
【Maven】依赖管理,Maven仓库,Maven核心功能
【Maven】依赖管理,Maven仓库,Maven核心功能
200 2