ClickHouse semantic layer
The ClickHouse semantic layer you define in TypeScript or Python
Model your table once — tenant key, time key, typed fields — and every query inherits it, across your APIs, dashboards, and AI agents. No YAML. Run it in your own backend.
Working in Python? See the Python semantic layer
Definition
What is a semantic layer?
A semantic layer is a single, shared definition of your business metrics that sits between your raw tables and everything that queries them. Dashboards, APIs, notebooks and AI agents ask it for “revenue” by name, and the layer decides which column, aggregate, filters and time column that means, so every consumer gets the same number and no caller can skip a filter that must always apply.
- Dimensions
- The attributes you slice by: region, plan, status, signup date. They end up in GROUP BY and WHERE.
- Measures
- Aggregations bound to a column, such as sum(total) or count(id), optionally with a filter built in.
- Metrics
- Named business quantities built from measures. Average order value is revenue divided by order count.
- Grain
- The time level a result is aggregated to, driven by one agreed time column: daily, weekly, monthly.
- Governed filters
- Conditions that always apply, whether or not the caller asks. Tenant isolation is the usual one.
Your semantic layer is a file in your repo.
A dataset declares your table, its tenant key, its time key, dimensions, and measures — once. Semantic queries built on it carry tenant and time context automatically when runtime tenancy is active. Change the definition; downstream usage follows the same typed contract.
import { dataset, dimension, measure } from '@hypequery/datasets';
export const Orders = dataset('orders', {
source: 'orders',
tenantKey: 'tenant_id', // every semantic query is tenant-scoped
timeKey: 'created_at', // every semantic query knows its time column
dimensions: {
id: dimension.string(),
amount: dimension.number(),
status: dimension.string(),
createdAt: dimension.timestamp({ column: 'created_at' }),
},
measures: {
revenue: measure.sum('amount'),
},
});from hypequery.datasets import dataset, dimension, measure
orders = dataset(
"orders",
source="orders",
tenant_key="tenant_id", # every semantic query is tenant-scoped
time_key="created_at", # every semantic query knows its time column
dimensions={
"id": dimension.string(),
"amount": dimension.number(),
"status": dimension.string(),
"createdAt": dimension.timestamp(column="created_at"),
},
measures={
"revenue": measure.sum("amount"),
},
)A semantic layer doesn't have to be a separate platform.
The usual answer to “ClickHouse semantic layer” is a separate platform such as Cube — a service modeled outside your application stack and run alongside your code. (dbt’s semantic layer doesn’t support ClickHouse today; see the options below.) That is the right tool when centralized BI metrics for non-engineers is the job.
For a team shipping product features, it is often the wrong shape. Your semantic layer should live in your codebase, your types, and your deploys. Datasets put it there: one definition, in TypeScript or Python, governed everywhere. Run it in your own backend; a hosted hypequery cloud is on a waitlist and not live yet.
Inside a BI tool
LookML or Power BI datasets. Consistent inside that tool, unavailable to your app code and APIs.
Standalone platform
Cube runs as a separate service with its own query API and pre-aggregation store.
Warehouse side
dbt MetricFlow keeps metrics in YAML next to your models. It still needs a runtime layer to serve app requests.
Code-first library
Definitions are typed code in your repo, imported by your backend and deployed with it. This is hypequery.
Multi-tenancy you can't forget.
The worst bug is the filter you forget to write. Declare tenantKey once on the dataset and semantic execution injects the tenant filter from runtime context. In Serve, require tenant context and requests without it fail before query execution.
TypeScript checks the fields, dimensions, measures, and filters you reference. Tenant identity itself is enforced at runtime because it comes from auth/request context.
import { createDatasetClient } from '@hypequery/datasets';
// the old way — a filter you must remember, in 40 places
`SELECT id, amount FROM orders WHERE tenant_id = '${tenantId}'`
// forget it once -> you leak a tenant's data
// with a dataset — declared once, applied from trusted runtime context
const analytics = createDatasetClient({ queryBuilder: db });
await analytics.execute(Orders, {
dimensions: ['id', 'amount'],
}, { runtime: { tenant: { id: tenantId } } });
// tenant filter is injected automatically; missing scope fails closedOne definition. Every consumer.
Register the dataset once. The same definition feeds server code, a validated HTTP route, a typed React hook, and governed MCP tools, without redefining what revenue means.
import { createDatasetClient } from '@hypequery/datasets';
import { initServe } from '@hypequery/serve';
import { db } from './client';
import { Orders } from './datasets';
import { verifyAuth } from './auth'; // your session or JWT check
const { serve } = initServe({
// the tenant comes from the verified session, never from the request
auth: verifyAuth,
tenant: {
extract: (auth) => auth.tenantId,
required: true,
},
context: () => ({ db }),
});
export const analytics = createDatasetClient({ queryBuilder: db });
export const api = serve({
queryBuilder: db,
datasets: { orders: Orders },
});// backend or worker
await analytics.execute(
Orders,
{ dimensions: ['status'], measures: ['revenue'] },
{ runtime: { tenant: { id: tenantId } } },
);
// HTTP
await fetch('/api/analytics/datasets/orders/query', {
method: 'POST',
body: JSON.stringify({ dimensions: ['status'], measures: ['revenue'] }),
});
// React
const { data } = useDataset('orders', {
dimensions: ['status'],
measures: ['revenue'],
});
// AI agents, over MCP
// npx hypequery mcp --tenant acmehypequery vs Cube / dbt MetricFlow
Both shapes can be correct. The question is whether you want a semantic layer inside your product codebase, or a separate metrics platform for centralized BI.
Where the semantic layer physically runs
How you author metrics and dimensions
Compile-time safety from schema to response
How rows are isolated per tenant
What you deploy and maintain in production
The workload each shape fits
Fit for dashboards and self-serve BI tools
Options
Semantic layer options for ClickHouse, compared
The named options, checked against each vendor’s own docs in November 2026. The deciding question is who consumes the metrics: your application and its agents, BI tools, or the ClickHouse console.
| Option | What it is | ClickHouse support | Your app and APIs | AI agents | Tenant rules |
|---|---|---|---|---|---|
| hypequery | Open-source TypeScript and Python libraries that run in your own backend | Built for ClickHouse (ClickHouse Cloud, self-hosted or chDB) | Yes: the same definitions serve typed HTTP endpoints, React hooks and server code | MCP tools, plus adapters for the Vercel AI SDK, Anthropic SDK and OpenAI Agents SDK | tenantKey on the dataset; a query without a trusted tenant is refused |
| Cube | A semantic layer platform: Cube Core (open source) or Cube Cloud | Yes, among many SQL sources | Through Cube's REST, GraphQL and SQL APIs, from a Cube deployment you run or Cube Cloud | An MCP server in Cube Cloud | Access policies and queryRewrite in the Cube data model |
| dbt Semantic Layer (MetricFlow) | Metrics defined in YAML next to dbt models | Not available: dbt lists Snowflake, BigQuery, Databricks, Redshift, Postgres and Trino as supported platforms | Not for ClickHouse | The dbt MCP server, on supported platforms | Relies on the data platform's own access policies |
| ClickHouse Cloud Assistant (AGENTS.md) | A saved query named AGENTS.md whose plain-language instructions are loaded into the Assistant's system prompt | ClickHouse Cloud, one service at a time | No: it guides the built-in Assistant, it is not a metric catalog your app can query | The Cloud console's Assistant only | Not a tenant mechanism |
| A BI tool's semantic model | LookML, Power BI datasets and similar, defined inside the BI tool | Where the BI tool connects to ClickHouse | No: consistent inside that tool, not available to your app code and APIs | Through that BI vendor's own agent, if it has one | The BI tool's own row-level rules |
Deeper comparisons: hypequery vs Cube, dbt MetricFlow vs a code-defined layer and semantic layers for AI agents.
Questions
ClickHouse semantic layer FAQ
Does ClickHouse have a built-in semantic layer?
Not as a set of metric definitions your application can query. ClickHouse Cloud's Assistant reads a saved query named AGENTS.md, plain-language instructions added to the agent's system prompt for one service. That helps the console Assistant, but your APIs, dashboards and own agents cannot ask it for "revenue". Views and materialized views precompute data; they do not define metrics or tenant rules.
Can I use the dbt Semantic Layer with ClickHouse?
Not today. dbt's documentation lists Snowflake, BigQuery, Databricks, Redshift, Postgres and Trino as the supported platforms and says support for other platforms is not available. You can still build your ClickHouse tables with dbt and define the metrics on top of them in a ClickHouse-native layer.
Should I use Cube or hypequery for a ClickHouse semantic layer?
Use Cube when BI tools need the same metrics through its SQL API, when metrics span several databases, or when you want managed pre-aggregations. Use hypequery when the semantic layer belongs to a TypeScript or Python product: the definitions live in your repo, deploy with your app and need no separate service.
How does a ClickHouse semantic layer keep tenants apart?
Declare the tenant column once. In hypequery, a dataset with a tenantKey adds the tenant filter to every query from trusted runtime context, sent as a bound parameter, and refuses any query that has no tenant or tries to filter on the tenant column itself.
Can AI agents query a ClickHouse semantic layer?
Yes. hypequery serves the same datasets as MCP tools (list_datasets, get_dataset_schema, query_dataset), and @hypequery/agent hands them to the Vercel AI SDK, the Anthropic SDK or the OpenAI Agents SDK. The agent asks for metrics by name and never writes SQL.
Does a semantic layer slow ClickHouse queries down?
A code-first layer compiles each request into one ClickHouse query inside your own process, so there is no extra service or network hop. ClickHouse still does the aggregation, and the definition can point at a materialized view or rollup table for expensive metrics.
Examples
Runnable examples
Every example runs against the same seeded ClickHouse dataset. Scaffold one with npx @hypequery/cli create <slug> -y, or browse the full list.
Recipe · TypeScript
Tenant lookups with a ClickHouse dictionary and dictGet in a typed dataset
Load tenant plan and region into a ClickHouse dictionary, expose them as dataset dimensions via dictGet, and check the result and timing against a JOIN.
Open recipe
Example · TypeScript
ClickHouse materialized view rollups: incremental vs refreshable
Pre-aggregate a million events two ways, incremental and refreshable, and query both through one typed hypequery dataset.
Open example
Example · TypeScript
A governed ClickHouse MCP server: agents query the semantic layer, not the database
Give Claude Code, Cursor or any MCP client ClickHouse analytics through four governed tools: only published datasets, no SQL, one tenant per server.
Open example
Recipe · TypeScript
Latency and status buckets in ClickHouse with multiIf, as reusable dataset dimensions
Define latency and status-class buckets once with multiIf, keep them in bucket order, and see how CASE, transform and roundDown compare on real requests.
Open recipe
Guide · ClickHouse 25.8
Refreshable materialized views in ClickHouse: schedule, refresh, monitor and query them
Create a refreshable materialized view on a schedule, refresh it on demand, watch it in system.view_refreshes, and query it through a typed hypequery dataset.
Open guide
Guides
Semantic layer guides and docs
Docs, design notes and comparisons for defining a ClickHouse semantic layer in code and serving it to APIs, dashboards and agents.
What is a semantic layer
The vendor-neutral guide: dbt MetricFlow, Snowflake semantic views, Databricks metric views and OSI compared.
Read
Datasets docs
Define datasets, dimensions, measures and metrics in TypeScript, then execute and serve them.
Read
Metrics docs
Attach named KPIs and derived calculations, such as average order value, to datasets.
Read
Dataset multi-tenancy
How tenant keys are enforced at runtime and why missing tenant context fails closed.
Read
Python semantic layer
The same datasets and Serve protocol for FastAPI, Django and Flask backends.
Read
Introducing hypequery datasets
Define dimensions, measures and metrics once, then reuse them across code, APIs, dashboards and agents.
Read
Introducing hypequery for Python
The Python SDK: datasets, serving and DataFrames over ClickHouse.
Read
ClickHouse MCP server
Expose datasets to Claude, Cursor and other MCP clients without raw SQL.
Read
AI analytics chat for ClickHouse
Give the Vercel AI SDK, Anthropic SDK or OpenAI Agents SDK your datasets as tools, so in-product chat answers match your dashboards.
Read
hypequery vs Cube
A code-first library compared with a configuration-first semantic layer platform.
Read
Cube.js alternative for ClickHouse
A semantic layer with no Cube server, Redis cache or YAML to run.
Read
dbt MetricFlow vs a code-defined layer
Semantic models and metric types in dbt, mapped onto datasets defined in code.
Read
Cube vs Tinybird vs hypequery
A semantic layer platform, a managed analytics service and a library in your codebase, side by side.
Read
hypequery vs Propel
Propel's domain now points to a parking page. Where its semantic layer and API users can move.
Read
Embedded runtime
Run dataset and metric definitions inside your own backend process, with no separate server.
Read
hypequery vs dbt
Scheduled transformations in dbt compared with request-time serving from your app.
Read
TypeScript vs dbt for ClickHouse
Which one belongs in your ClickHouse stack, and when you need both.
Read
Embedded analytics
Serving tenant-scoped metrics to customers: build vs buy and vendors compared.
Read
Next step
Define your first dataset in 30 seconds.
Start open source in your own backend. A hosted option, hypequery cloud, is coming soon.