Overview

A dictionary is an in-memory key-value structure loaded from a source (a ClickHouse table, file, MySQL/PostgreSQL, HTTP…) and refreshed periodically. dictGet looks up attributes without a join. Dictionaries are the idiomatic way to enrich large fact tables with small reference data, avoiding a join.

Core concepts

  • Layouts: flat (array by integer key), hashed, sparse_hashed, complex_key_hashed (composite keys), range_hashed (time-versioned), cache, direct (no memory; reads source on demand), ip_trie.
  • LIFETIME(MIN a MAX b): refresh interval randomised between a and b seconds; the source is re-read in the background.
  • Query with dictGet('name', 'attr', key), dictGetOrDefault, dictHas. Status and memory in system.dictionaries.
  • Joins are supported (INNER, LEFT, RIGHT, FULL, CROSS, ASOF) with algorithms chosen by join_algorithm (hash, parallel_hash, grace_hash, full_sorting_merge, direct…). The default in the test server was direct,parallel_hash,hash,ie_join.

Worked example

CREATE DICTIONARY country_names (code String, name String) PRIMARY KEY code
SOURCE(CLICKHOUSE(TABLE 'country_src' DB 'kb' USER 'default' PASSWORD '<secret>'))
LAYOUT(HASHED()) LIFETIME(MIN 300 MAX 600);
 
SELECT dictGet('country_names', 'name', country) AS country_name, count() c
FROM events_a GROUP BY country_name ORDER BY c DESC LIMIT 3;
-- India 625,727   Vietnam 625,537   United States 625,360

Status: country_names LOADED, 8 elements, 14.23 KiB. The enrichment query took 9 ms; the equivalent INNER JOIN country_src took 17 ms on 5,000,000 rows. For eight rows the gap is small, but the dictionary is built once and reused by every query, while the join builds its hash table every time.

Join side matters: joining events_a (5M rows) with a 1,000-row subquery on the right read 5 MiB and used 1.8 MiB of memory in 7 ms; putting the big table on the right with automatic table swapping disabled used 212 MiB and took 349 ms.

Pitfalls and production notes

  • The right table of a hash join is held in memory; keep it the smaller side or pick grace_hash / full_sorting_merge to bound memory.
  • Do not put credentials in dictionary DDL in version control; use named collections or secrets.
  • A dictionary load failure keeps the old data; monitor system.dictionaries.last_exception.
  • Prefer denormalising stable attributes into the fact table when they never change.
  • Compare with PostgreSQL/Oracle where joins are the default tool (sql-joins).

Practice questions

  1. When is dictGet better than a JOIN?
  2. Which layout would you use for a million integer keys? For IP ranges?
  3. Why does the order of tables in a ClickHouse join matter?

References

  • ClickHouse documentation, Dictionaries; JOIN clause

sql-joins · ch-query-optimization · ch-materialized-views