大数据ClickHouse进阶(十九):ClickHouse字典的数据源

2022-10-17 08:09:35 浏览数 (2)

​ClickHouse字典的数据源

一、文件数据源

ClickHouse中的字典还可以映射本地文件数据。操作如下:

1、创建本地csv文件

在本地创建的csv文件需要放在“/var/lib/ClickHouse/user_files”路径下,在此目录下创建organization.csv文件,写入如下内容:

代码语言:javascript复制
1,"a0001","研发部"
2,"a0002","产品部"
3,"a0003","数据部"
4,"a0004","测试部"
5,"a0005","运维部"
6,"a0006","规划部"
7,"a0007","市场部"

2、创建字典表

代码语言:javascript复制
#在ClickHouse中创建字典表
create dictionary org_dic(
id UInt64,
code String,
name String
)
primary key id
SOURCE(FILE(path '/var/lib/ClickHouse/user_files/organization.csv' format 'CSV'))
LAYOUT(FLAT())
LIFETIME(30);

注意:SOURCE(FILE(path '文件名',' 文件格式')),文件格式支持CSV和TabSeparated。

#查询使用字典表
node1 :) select dictGet('dic_test_db.org_dic','name',toUInt64(2)) as name;
┌─name───┐
│ 产品部 │
└────────┘

二、MySQL数据源

ClickHouse中还支持从MySQL中提取数据到字典表。具体操作如下:

1、在MySQL中创建表organization并插入数据

代码语言:javascript复制
#在mysql中创建库、表及插入数据
mysql> create database mytest;
mysql> use mytest;
mysql> create table organization(id int,code varchar(255),name varchar(255));

#插入数据
insert into mytest.organization values(1,"a0001","org1");
insert into mytest.organization values(2,"a0002","org2");
insert into mytest.organization values(3,"a0003","org3");
insert into mytest.organization values(4,"a0004","org4");
insert into mytest.organization values(5,"a0005","org5");
insert into mytest.organization values(6,"a0006","org6");
insert into mytest.organization values(7,"a0007","org7");

#查询数据
mysql> select * from organization;

2、在ClickHouse中创建字典表

代码语言:javascript复制
#在ClickHouse中创建flat字典表
create dictionary org_dic2(
id UInt64,
code String,
name String
)
primary key id
SOURCE(MYSQL(
    port 3306
    user 'root'
    password '123456'
    host 'node2'
    db 'mytest'
    table 'organization'
))
LAYOUT(FLAT())
LIFETIME(MIN 3 MAX 5);


#使用字典表
node1 :)  select dictGet('dic_test_db.org_dic2','name',toUInt64(2)) as name;
┌─name─┐
│ org2 │
└──────┘

注意:ClickHouse字典表除了支持将MySQL、ClickHouse表作为数据来源,还可以从MongoDB中读取数据。

0 人点赞