How to build a semantic layer in ClickHouse (with real YAML)
Step-by-step: model definitions, metric definitions, join graph, and a compiler that emits ClickHouse-dialect SQL. Working YAML at the end.
If you are on ClickHouse and want a semantic layer, the honest short story is that you do not need a new tool - you need four YAML files and a compiler. This post walks through the shape of those four files, why each one has to exist, and how the compiler that turns them into ClickHouse-dialect SQL actually works. The shape is the same whether you build it in-house or adopt a tool that ships one (dbt Semantic Layer, Cube, Goni, or a home-grown compiler on top of sqlglot).
We assume ClickHouse 24 or newer for the syntax below, but the concepts port to older versions.
Why a semantic layer, one paragraph
A semantic layer defines your business concepts (customers, orders, revenue) once, in code, and every BI tool, ad-hoc query, and AI Q&A surface compiles from that definition. The alternative is metric drift - the same KPI computed four different ways in four different places, none of which agree. We wrote a longer piece on the shape of that failure at metric drift audit, and on the underlying category at semantic vs metric vs headless BI.
The four files
A working semantic layer on ClickHouse is these four kinds of YAML:
sources.yml- the physical tables in your warehouse, one entry per raw source. This is where columns get typed and PII-tagged.models.yml- the transformations from raw sources into analytical tables. These are the entities your business talks about (customers, orders, sessions), not the raw tables.metrics.yml- the KPIs. Each metric has one canonical SQL definition.joins.yml- the join graph. Tells the compiler which models can be combined and on what keys.
That is it. Every serious semantic layer product boils down to these four concepts, plus a compiler.
sources.yml
sources:
- name: raw_orders
schema: raw
table: orders
freshness: {warn_after: 6h, error_after: 24h}
columns:
- {name: id, type: UUID}
- {name: customer_id, type: UUID}
- {name: amount, type: Decimal(12,2)}
- {name: plan_multiplier, type: Decimal(4,2), default: 1.0}
- {name: status, type: LowCardinality(String)}
- {name: created_at, type: DateTime}
- {name: email, type: String, tags: [pii]}
- name: raw_customers
schema: raw
table: customers
columns:
- {name: id, type: UUID}
- {name: name, type: String}
- {name: country, type: LowCardinality(String)}
- {name: signup_at, type: DateTime}
Two things worth noticing. LowCardinality(String) is a ClickHouse-native type that halves storage for string columns with a small distinct set - use it for country, status, plan. The pii tag on email is what a governance policy will hook into later; the tag lives in one place instead of duplicated across BI tools.
models.yml
models:
- name: dim_customers
kind: table
engine: ReplacingMergeTree
order_by: [id]
primary_key: [id]
sql: |
SELECT
id,
name,
country,
signup_at,
toDate(signup_at) AS signup_date
FROM {{ source('raw_customers') }}
- name: fact_orders
kind: incremental
engine: MergeTree
order_by: [created_at, customer_id]
partition_by: toYYYYMM(created_at)
incremental_by: created_at
sql: |
SELECT
id,
customer_id,
amount,
plan_multiplier,
amount * plan_multiplier AS effective_amount,
status,
created_at
FROM {{ source('raw_orders') }}
WHERE status = 'active'
{% if is_incremental %}
AND created_at > (SELECT max(created_at) FROM {{ this }})
{% endif %}
ReplacingMergeTree gives you late-arriving upserts on the customer table for free. MergeTree with a partition by month is the honest default for a fact table on ClickHouse. The {% if is_incremental %} block is a Jinja pattern borrowed from dbt - the compiler renders it differently on first build vs. incremental refresh.
metrics.yml
metrics:
- name: active_customers
label: "Active customers"
description: "Distinct customers with a paid, active order in the window"
model: fact_orders
type: count_distinct
sql: customer_id
filters: []
- name: monthly_recurring_revenue
label: "MRR"
description: "Sum of effective_amount for active recurring orders"
model: fact_orders
type: sum
sql: effective_amount
grain: month
time_column: created_at
- name: revenue_per_customer
label: "Revenue per customer"
type: ratio
numerator: monthly_recurring_revenue
denominator: active_customers
This is the file that stops metric drift. mrr has exactly one definition. Every dashboard, every AI Q&A query, every ad-hoc SQL query that asks for mrr compiles to sum(effective_amount) filtered on the fact_orders window. If the business changes what “active” means, you edit one file.
joins.yml
joins:
- from: fact_orders
to: dim_customers
kind: many_to_one
on: fact_orders.customer_id = dim_customers.id
- from: fact_orders
to: dim_plans
kind: many_to_one
on: fact_orders.plan_id = dim_plans.id
The join graph is what lets the compiler answer SELECT mrr BY country FROM metrics without the user knowing that country lives on dim_customers. It also lets the compiler catch fan-out bugs (a many-to-many join that duplicates the numerator of a ratio metric) at compile time rather than at query time.
The compiler, in shape
The compiler takes a query written in the semantic-layer DSL (SELECT mrr BY month FROM metrics) and emits ClickHouse SQL. Its job in one pass:
- Resolve
mrrto its metric definition. - Resolve the metric’s model to a physical table.
- Walk the join graph to bring in any requested dimensions.
- Push down the time filter to the partition key.
- Emit ClickHouse-dialect SQL.
The emitted SQL for SELECT mrr BY month, country FROM metrics WHERE month > '2025-01-01' looks like this:
SELECT
toStartOfMonth(fact_orders.created_at) AS month,
dim_customers.country AS country,
sum(fact_orders.effective_amount) AS mrr
FROM fact_orders
LEFT JOIN dim_customers
ON fact_orders.customer_id = dim_customers.id
WHERE fact_orders.created_at >= toDate('2025-01-01')
GROUP BY month, country
ORDER BY month, country;
That is the compiled artifact. Every rendering of mrr produces this SQL. No dashboard writes its own. No analyst copy-pastes it. No AI Q&A LLM invents it.
The compiler can be built on top of sqlglot in a couple of hundred lines of Python. dbt’s Semantic Layer, Cube, and Goni all sit on similar foundations.
The three ClickHouse-specific tricks
1. Push aggregation into materialised views. For high-frequency metrics like mrr on a large fact table, define a SummingMergeTree MV that pre-aggregates by month. The compiler picks the MV over the raw table when the query grain matches. Docs at ClickHouse materialized views.
2. Use projections for alternate sort orders. If your fact table is sorted by (created_at, customer_id) but a common metric filters by plan_id, define a projection that stores the same data sorted by (plan_id, created_at). See ClickHouse projections.
3. Materialise dictionaries for star-schema dimensions. Small dimension tables (fewer than 10M rows) can be materialised as ClickHouse dictionaries and joined at query time via dictGet, which is orders of magnitude faster than a LEFT JOIN.
Getting these three right is the difference between a semantic layer that renders a dashboard in 100 ms and one that renders it in 2 seconds. The compiler should choose the physical path; the user should not have to.
What to skip on the first pass
Do not build these on day one:
- Slow-changing dimensions. They matter, but they matter for maybe two of your ten dimensions. Ship the ten first, add SCD2 on the two later.
- Snapshot tables. Wait until you need historical rollups; if you don’t, you’re paying for storage of a shape nobody queries.
- Every dialect at once. Compile for ClickHouse first. Add BigQuery, Snowflake, or Postgres targets once one warehouse is working end-to-end.
Every homegrown semantic layer that failed I have seen tried to solve every dimension of the problem before shipping the first metric. The right shape is: ship five metrics, connect them to one BI tool, watch what people ask, then generalise.
When to build vs. buy
If you have a data engineer with a quarter to spare and a small set of metrics, build it. sqlglot plus 300 lines of Python plus a Jinja renderer is the honest shape. The four YAML files above will get you there.
If you have more than a handful of engineers on the data platform and want the layer to survive attrition, buy it. dbt Semantic Layer, Cube, and Goni all ship a compiler and a runtime for less than an engineer’s quarterly cost. The reason to buy is not the compiler; it is the ongoing maintenance of dialect drift, ClickHouse version upgrades, and the BI tool integrations.
Goni ships a compiled semantic layer natively on ClickHouse. Everything above is roughly what our compiler does, so if you want to see it working end-to-end on your own data, goni.paysera.com has a trial.
Why this matters for a data team
A semantic layer is four files and a compiler. The tool you pick to run them is less important than the discipline of routing every query surface through them. The teams that end up with metric drift are almost always the teams that shipped a semantic layer for their dashboards and let their AI Q&A tool, their notebooks, and their “temporary” CSV exports bypass it. The layer is worth exactly as much as the surfaces it owns.