一、安裝
1、下載下傳:
wget https://mirrors.tuna.tsinghua.edu.cn/apache/cassandra/3.11.4/apache-cassandra-3.11.4-bin.tar.gz
2、解壓
tar -xvf apache-cassandra-3.11.4-bin.tar.gz
3、修改配置
vim conf/cassandra.yaml
指定服務的位址和端口号
listen_address: 192.168.0.1
native_transport_port: 9042
遠端連接配接如thrift服務,配置端口:
rpc_port: 9160
4.以root 啟動
./cassandra -R //用root使用者啟動
5、關閉防火牆
systemctl stop firewalld.service
二、使用
1、建立 資料庫
create keyspace alarm
with replication={'class':'SimpleStrategy', 'replication_factor':2 }
and durable_writes=true
class:SimpleStrategy(簡單政策,一個資料中心) NetworkTopologyStrategy(網絡拓撲政策,多個資料中心)
replication_factor:副本數
durable_writes:是否持久寫入,預設為true
2、建立表table
包括表的檢視、建立和删除、字段的增加和修改、索引的建立和删除。
例子: 建立學生表
CREATE TABLE alarm.stu (
stu_id int PRIMARY KEY,
stu_age int,
stu_name text,
school map<text, text>,
cource_set set<text>,
teacher_list list<text>
);
#删除指定table
drop table alarm.stu
#修改table 增加字段
alter table alarm.stu add stu_age_1 text
#修改table 删除字段
alter table alarm.stu drop stu_age_1
#建立索引
create index stu_name_idx on alarm.stu(stu_name)
#删除索引
drop index alarm.stu_name_idx
3、資料操作
包括資料的增删改查,詳情檢視注釋,如下:
#插入資料
insert into alarm.stu(stu_id, stu_age, stu_name) values(2, 18,'張工');
#更新資料
update alarm.stu set stu_name='李四' where stu_id=1;
#檢視資料
select * from alarm.stu;
#删除列的值
delete stu_age from alarm.stu where stu_id=1;

#删除一行資料
delete from alarm.stu where stu_id=1;
#清空表資料
truncate alarm.stu;
4、資料類型
cassandra的資料類型
cassandra資料類型除了基本類型外,還添加了集合類型,如list、set、map。
下面列出常用的類型(第一列為cassandra中的類似,第二列為相應描述,第三列為java中的類型),
################## 常用字段類型 ##########################
int 32位整數 int
bigint 64整數 long
float 32位浮點數 flaot
counter 計數器,支援原子性增減,不能直接指派 long
double 64位浮點數 double
boolean 布爾 boolean
decimal 高精度小數 BigDecimal
list 清單 List
set 集合 Set
map 鍵值對 map
text utf8編碼的字元串 String
varchar 與text一樣
timestamp 日期 Date
4、導入導出資料
stu_file="tmp/stu_file.csv"
//下載下傳資料到指定csv檔案
copy alarm.stu(stu_id, stu_age, stu_name) to '${stu_file}';
//下載下傳資料到指定csv檔案 參數: pagesize=單個頁面的行數,預設1000 encoding=字元編碼,預設utf8 maxoutputsize=單個檔案最大行數, 預設-1,不限制
copy alarm.stu(stu_id, stu_age, stu_name) to '${stu_file}' with maxoutputsize=2;
//上傳資料到表中 參數: maxrows=導入最大行數 skiprows=跳過初始行數 skipcols=要忽略的列名,以逗号分隔
copy alarm.stu(stu_id, stu_age, stu_name) from '${stu_file}' with maxrows=5;