问题
如何使用来自 MergeTree 表源的字符串键和字符串值创建 ClickHouse 字典
答案
- 创建字典的源表
CREATE TABLE db1.table1_dict_source
(
id UInt32,
email String,
name String
)
ENGINE = MergeTree()
ORDER BY id;
- 插入行
INSERT INTO db1.table1_dict_source
(id, email, name)
VALUES
(1, '[email protected]', 'me'),
(2, '[email protected]', 'you');
- 创建键/值均为字符串的字典
CREATE DICTIONARY db1.table1_dict
(
email String,
name String
)
PRIMARY KEY email
SOURCE(
CLICKHOUSE(
TABLE 'table1_dict_source'
USER 'default'
PASSWORD 'ClickHouse123!'))
LAYOUT(COMPLEX_KEY_HASHED())
LIFETIME(MIN 0 MAX 1000);
- 测试字典
clickhouse-cloud :) SELECT * from db1.table1_dict;
SELECT *
FROM db1.table1_dict
Query id: 098396ce-11dd-4c71-a0e1-40723dd67ddc
┌─email──────────┬─name─┐
│ [email protected] │ me │
│ [email protected] │ you │
└────────────────┴──────┘
2 rows in set. Elapsed: 0.001 sec.
您还可以使用 dictGet 函数从其中检索值,例如
SELECT dictGet('db1.table1_dict', 'name', '[email protected]');
响应
┌─dictGet('db1.table1_dict', 'name', '[email protected]')─┐
│ me │
└─────────────────────────────────────────────────────┘
更多详细信息 - https://clickhouse.ac.cn/docs/en/sql-reference/functions/ext-dict-functions