Clickhouse使用基础

bash 复制代码
# 查看操作系统版本
cat /etc/os-release

# clickhouse版本
clickhouse -V

# 登录clickhouse客户端
clickhouse-client -u xxx --password xxx -m 
# -m 或 --multiline:进入客户端后,运行输入多行sql语句

建表

sql 复制代码
# 创建数据库
CREATE DATABASE IF NOT EXISTS test;  --使用默认库引擎创建库
sql 复制代码
# 创建本地表
create table IF NOT EXISTS test.user_table (
	uid String comment '用户ID',
	sex String comment '性别',
	age UInt16 comment '年龄',
	phone String comment '联系电话'
)
engine = MergeTree()
order by uid;
  • 数据类型需要大写开头:String、UInt16
  • 表引擎类型也必须大写MergeTree
  • 如果没有指定主键,默认使用 order by 指定的字段
sql 复制代码
# 创建分布式表
-- 在集群中创建实际存放数据的本地表
create table test.user_event on cluster data_cluster(
	uid String comment '用户id',
	event String comment '事件名称',
	c_time DateTime comment '点击时间',
	dt Date comment '日期'
)
engine = MergeTree()
partition by dt 
order by uid;

--创建分布式表
create table test.user_event_distributed (
	uid String comment '用户id',
	eventString comment '事件名称',
	c_time DateTime comment '点击时间',
	dt Date comment '日期'
)
engine = Distributed('data_cluster', 'test', 'user_event', rand());
  • 分布式表需要选择Distributed 表引擎:
    • 第1个参数:集群名称
    • 第2个参数:数据库名
    • 第3个参数:数据表名
    • 第4个参数:分片key,数据被到不同服务器依据的字段,相同的值会被分配到同一台服务器

如果在创建分布式表test.user_event_distributed 时没有指定on cluster data_cluster,那么创建是本地表,后续的查询只能在建表的那个节点服务器查询数据

表变更

sql 复制代码
# 删除特定分区
alter table test.user_event 
on cluster data_cluster 
drop partition '2024-11-30';

alter table test.user_event 
on cluster data_cluster 
delete where dt > '2024-11-15';

alter table test.user_event 
on cluster data_cluster 
delete where dt='2024-11-30';

# 删除满足特定条件数据
alter table test.user_event 
on cluster data_cluster 
delete where user_id='u00001';

自定义函数

sql 复制代码
/**
 * 创建自定义函数 x_split
 * 分割字符串并把类型转换为整数
 */
CREATE FUNCTION x_split (x String)
RETURNS Array(UInt32)
AS
(
    arrayMap(
        (y) -> toUInt32(y), 
        splitByString(',', x)
    )
);
相关推荐
大千AI助手2 天前
硬核实战 | 3分钟Docker部署ClickHouse列存数据库
大数据·clickhouse·docker·database
Sayai3 天前
dbeaver 查询clickhouse,数据库时间差了8小时
数据库·clickhouse·oracle
weixin_307779134 天前
Clickhouse统计指定表中各字段的空值、空字符串或零值比例
运维·数据仓库·clickhouse
weixin_307779135 天前
Linux下GCC和C++实现统计Clickhouse数据仓库指定表中各字段的空值、空字符串或零值比例
linux·运维·c++·数据仓库·clickhouse
斯特凡今天也很帅6 天前
clickhouse常用语句汇总——持续更新中
数据库·sql·clickhouse
SelectDB技术团队7 天前
从 ClickHouse、Druid、Kylin 到 Doris:网易云音乐 PB 级实时分析平台降本增效
大数据·数据仓库·clickhouse·kylin·实时分析
risc12345612 天前
【ClickHouse】RollingBitmap
clickhouse
斯特凡今天也很帅12 天前
clickhouse如何查看操作记录,从日志来查看写入是否成功
数据库·clickhouse
袖清暮雨17 天前
ClickHouse讲解
大数据·数据库·数据仓库·clickhouse·oracle
江枫渔火L19 天前
使用clickhouse的ReplacingMergeTree引擎表做活跃玩家信息表
数据库·clickhouse