Cassandra学习1 - 在Docker中运行,创建Keyspace,创建Table,并操作数据

最好的学习方式是动手实践,伴随着实践再来理解理论。遵循这样的原则我今天开始了Cassandra数据库学习的第一课。
在现实中Cassandra大概率要以Docker作为容器部署在Cloud上面。并且Docker也的确为我们提供了很多方便,省去了安装Cassandra的时间还有你为Cassandra寻找合适平台(OS)的麻烦。所以我决定还是用Docker来进行学习。如果你要参考我的步骤,请先去下载安装Docker。

在Docker中运行Cassandra

Cassandra在Docker hub上面有官方发布的image,https://hub.docker.com/_/cassandra
页面上有使用说明。下面是我运行的一个简化的步骤。

# 1 download image
docker pull cassandra

# 2 List all your current images
docker image ls

# 3 run immage and give my-cassandra as container's name 
docker run --name my-cassandra -d cassandra

# 4 check the status of container
docker container ps
or
docker container ls -a

查看container内的结构,cassandra和nodetool命令

# 1 execute shell command in running container, my-cassandra
docker exec -it my-cassandra /bin/bash
# -i, --interactive          Keep STDIN open even if not attached
# -t, --tty                  Allocate a pseudo-TTY

# 2 cassandra command. If you install cassandra by yourself you need this command to start cassandra instance, but now we don't need it.
which cassandra
/usr/sbin/cassandra

# 3 nodetool command. Using it to get current running status of all nodes
which nodetool
/usr/bin/nodetool

nodetool status
Datacenter: datacenter1
=======================
Status=Up/Down
|/ State=Normal/Leaving/Joining/Moving
--  Address     Load       Tokens       Owns (effective)  Host ID                               Rack
UN  172.17.0.2  103.63 KiB  256          100.0%            fbe2a31f-2a2c-4570-9bec-8caed7a1626e  rack1

CQL

CQL - Cassandra Query Language。和SQL类似,暂时把它当成SQL就可以。

# Run cql, we need cqlsh command in container
which cqlsh
/usr/bin/cqlsh

# Run cqlsh command to enter cql client
cqlsh
Connected to Test Cluster at 127.0.0.1:9042.
[cqlsh 5.0.1 | Cassandra 3.11.4 | CQL spec 3.4.4 | Native protocol v4]
Use HELP for help.
cqlsh> 

创建Keyspace

Keyspace - 相当于关系数据库中的Schema。
在cql client中运行,

# Create a keyspace
CREATE KEYSPACE IF NOT EXISTS easymall
WITH REPLICATION = {
    'class':'SimpleStrategy',
    'replication_factor':1
};
 
# Describe a keyspace
cqlsh> DESCRIBE easymall
CREATE KEYSPACE easymall WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '1'}  AND durable_writes = true;

# Switch between keyspaces
cqlsh> USE easymall;
cqlsh:easymall> 

创建Table

CREATE TABLE users (
user_id          UUID PRIMARY KEY,
first_name     TEXT,
last_name     TEXT,
added_date   TIMESTAMP,
);

# Example
cqlsh:easymall> CREATE TABLE users (
            ... user_id UUID PRIMARY KEY,
            ... first_name TEXT,
            ... last_name TEXT,
            ... added_date timestamp,
            ... );
cqlsh:easymall> DESCRIBE users;

CREATE TABLE easymall.users (
    user_id uuid PRIMARY KEY,
    added_date timestamp,
    first_name text,
    last_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', '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';

课后思考:

  1. cassandra都支持那些datatype?
  2. uuid 和 timeuuid,如何生成主键?

简单的数据操作

INSERT

INSERT INTO users (user_id,first_name,last_name,added_date) VALUES (uuid(),'Dehua','Liu',toTimeStamp(now()));

SELECT

SELECT * FROM users;

# Example:
cqlsh:easymall> SELECT * FROM users;

 user_id                              | added_date                      | first_name | last_name
--------------------------------------+---------------------------------+------------+-----------
 2212f08c-9c51-4def-a35d-d4f16d8b55cd | 2019-08-07 14:34:17.082000+0000 |      Dehua |       Liu

(1 rows)

TRUNCATE

Remove all data from table.

cqlsh:easymall> TRUNCATE users;
cqlsh:easymall> SELECT * FROM users;

 user_id | added_date | first_name | last_name
---------+------------+------------+-----------

(0 rows)

COPY

用来从table中以.csv格式导出、导入数据。它并不是唯一的方法。

# Export data from users table to /opt/users.csv
COPY users (user_id,first_name,last_name,added_date) TO '/opt/users.csv';
# Example
cqlsh:easymall> COPY users (user_id,first_name,last_name,added_date) TO '/opt/users.csv';
Using 1 child processes

Starting copy of easymall.users with columns [user_id, first_name, last_name, added_date].
Processed: 5 rows; Rate:       3 rows/s; Avg. rate:       6 rows/s
5 rows exported to 1 files in 0.895 seconds.

# After exit cqlsh
cat /opt/users.csv 
9d0004b3-dba9-422e-9389-5ad1e0f1060b,Dehua,Liu,2019-08-07 15:01:07.570+0000
fd83f6bb-d953-49e3-855e-d346164ee0a1,Xiao,Ming,2019-08-07 15:01:34.378+0000
2212f08c-9c51-4def-a35d-d4f16d8b55cd,Angla,Baby,2019-08-07 14:34:18.082+0000
2212f08c-9c51-4def-a35d-d4f16d8b55ae,Steven,Kim,2019-08-07 14:34:19.082+0000
2adc86f6-185f-4e77-a7f6-b82fbd83dfde,Da,Liu,2019-08-07 15:01:46.286+0000

反之,也可以用COPY导入数据,再创建一个结构和users一样的users_bak,

CREATE TABLE users_bak (
user_id          UUID PRIMARY KEY,
first_name     TEXT,
last_name     TEXT,
added_date   TIMESTAMP,
);

然后再运行

COPY users_bak (user_id,first_name,last_name,added_date) FROM '/opt/users.csv';
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值