Clickhouse使用根本

种地  论坛元老 | 2024-12-29 09:44:13 | 显示全部楼层 | 阅读模式
打印 上一主题 下一主题

主题 1718|帖子 1718|积分 5154

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. # 查看操作系统版本
  2. cat /etc/os-release
  3. # clickhouse版本
  4. clickhouse -V
  5. # 登录clickhouse客户端
  6. clickhouse-client -u xxx --password xxx -m
  7. # -m 或 --multiline:进入客户端后,运行输入多行sql语句
复制代码
建表

  1. # 创建数据库
  2. CREATE DATABASE IF NOT EXISTS test;  --使用默认库引擎创建库
复制代码
  1. # 创建本地表
  2. create table IF NOT EXISTS test.user_table (
  3.         uid String comment '用户ID',
  4.         sex String comment '性别',
  5.         age UInt16 comment '年龄',
  6.         phone String comment '联系电话'
  7. )
  8. engine = MergeTree()
  9. order by uid;
复制代码


  • 数据类型必要大写开头:String、UInt16
  • 表引擎类型也必须大写MergeTree
  • 如果没有指定主键,默认使用 order by 指定的字段
  1. # 创建分布式表
  2. -- 在集群中创建实际存放数据的本地表
  3. create table test.user_event on cluster data_cluster(
  4.         uid String comment '用户id',
  5.         event String comment '事件名称',
  6.         c_time DateTime comment '点击时间',
  7.         dt Date comment '日期'
  8. )
  9. engine = MergeTree()
  10. partition by dt
  11. order by uid;
  12. --创建分布式表
  13. create table test.user_event_distributed (
  14.         uid String comment '用户id',
  15.         eventString comment '事件名称',
  16.         c_time DateTime comment '点击时间',
  17.         dt Date comment '日期'
  18. )
  19. engine = Distributed('data_cluster', 'test', 'user_event', rand());
复制代码


  • 分布式表必要选择Distributed 表引擎:

    • 第1个参数:集群名称
    • 第2个参数:数据库名
    • 第3个参数:数据表名
    • 第4个参数:分片key,数据被到不同服务器依据的字段,相同的值会被分配到同一台服务器

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

  1. # 删除特定分区
  2. alter table test.user_event
  3. on cluster data_cluster
  4. drop partition '2024-11-30';
  5. alter table test.user_event
  6. on cluster data_cluster
  7. delete where dt > '2024-11-15';
  8. alter table test.user_event
  9. on cluster data_cluster
  10. delete where dt='2024-11-30';
  11. # 删除满足特定条件数据
  12. alter table test.user_event
  13. on cluster data_cluster
  14. delete where user_id='u00001';
复制代码
自界说函数

  1. /**
  2. * 创建自定义函数 x_split
  3. * 分割字符串并把类型转换为整数
  4. */
  5. CREATE FUNCTION x_split (x String)
  6. RETURNS Array(UInt32)
  7. AS
  8. (
  9.     arrayMap(
  10.         (y) -> toUInt32(y),
  11.         splitByString(',', x)
  12.     )
  13. );
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

种地

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表