[hypequery](https://hypequery.com/) › ClickHouse Semantic Layer in TypeScript and Python | hypequery
Index for agents: https://hypequery.com/llms.txt
Canonical page: https://hypequery.com/clickhouse-semantic-layer

> Define a ClickHouse semantic layer in TypeScript or Python with typed datasets, tenant keys and time keys, then serve it to APIs, dashboards and AI agents.

[Open sourceApache 2.0](https://github.com/hypequery/hypequery)

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.

[Get started ](https://hypequery.com/docs)[Read the datasets docs](https://hypequery.com/docs/datasets/overview)

Working in Python? [See the Python semantic layer](https://hypequery.com/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, such as daily, weekly or monthly, driven by one agreed time column.

- 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.

datasets/orders.ts

```
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'),
  },
});
```

datasets/orders.py

```
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, which is modeled outside your application stack and runs 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 as typed code and ship with your deploys. Datasets put it there, with one definition in TypeScript or Python that is governed everywhere. Run it in your own backend; a hosted hypequery cloud is on a waitlist and not live yet.

Serving one set of definitions over APIs to front ends you build yourself is often called [headless BI](https://hypequery.com/semantic-layer/headless-bi). Datasets work that way, with the model kept in your app repo instead of a separate service.

### 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.

tenant-scope.ts

```
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 closed
```

## Every consumer reads the same definition.

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.

analytics/revenue-by-day.ts

```
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 },
});
```

consumers.ts

```
// 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 acme
```

## hypequery 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.

DecisionhypequeryCube / MetricFlow

Lives in

Where the semantic layer physically runs

hypequeryYour codebase, in TypeScript or Python

Cube / MetricFlowSeparate service / platform

Language

How you author metrics and dimensions

hypequeryTypeScript or Python

Cube / MetricFlowYAML / modeling DSLs

Types

Compile-time safety from schema to response

hypequeryTyped contracts from schema to response

Cube / MetricFlowLimited or external to app code

Tenancy

How rows are isolated per tenant

hypequeryRuntime-enforced from tenant context; typed fields

Cube / MetricFlowManual filters or platform policy

Operate

What you deploy and maintain in production

hypequeryA library in your stack (a hosted option is coming soon)

Cube / MetricFlowA platform to run

Best for

The workload each shape fits

hypequeryShipping ClickHouse-backed product features

Cube / MetricFlowCentralized BI metrics and non-engineer consumers

BI Support

Fit for dashboards and self-serve BI tools

hypequeryNot a full BI modeling platform

Cube / MetricFlowBetter fit for broad BI governance

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](https://hypequery.com/compare/hypequery-vs-cube), [dbt MetricFlow vs a code-defined layer](https://hypequery.com/semantic-layer/dbt-metricflow) and [semantic layers for AI agents](https://hypequery.com/semantic-layer/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, because 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](https://hypequery.com/examples).

[Recipe · TypeScript](https://hypequery.com/recipes/dictionary-lookups)

### [Tenant lookups with a ClickHouse dictionary and dictGet in a typed dataset](https://hypequery.com/recipes/dictionary-lookups)

[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.](https://hypequery.com/recipes/dictionary-lookups)

[Node.jsClickHouseSaaS analyticsMulti-tenant](https://hypequery.com/recipes/dictionary-lookups)

[Open recipe](https://hypequery.com/recipes/dictionary-lookups)

[Example · TypeScript](https://hypequery.com/examples/materialized-view-rollups)

### [ClickHouse materialized view rollups: incremental vs refreshable](https://hypequery.com/examples/materialized-view-rollups)

[Pre-aggregate a million events two ways, incremental and refreshable, and query both through one typed hypequery dataset.](https://hypequery.com/examples/materialized-view-rollups)

[Node.jsClickHousePre-aggregationDashboardsTime series](https://hypequery.com/examples/materialized-view-rollups)

[Open example](https://hypequery.com/examples/materialized-view-rollups)

[Example · TypeScript](https://hypequery.com/examples/mcp-agent-analytics)

### [A governed ClickHouse MCP server: agents query the semantic layer, not the database](https://hypequery.com/examples/mcp-agent-analytics)

[Give Claude Code, Cursor or any MCP client ClickHouse analytics through four governed tools: only published datasets, no SQL, one tenant per server.](https://hypequery.com/examples/mcp-agent-analytics)

[Node.jsMCPClickHouseAI agentsMulti-tenantSemantic layer](https://hypequery.com/examples/mcp-agent-analytics)

[Open example](https://hypequery.com/examples/mcp-agent-analytics)

[Recipe · TypeScript](https://hypequery.com/recipes/multiif-bucketing)

### [Latency and status buckets in ClickHouse with multiIf, as reusable dataset dimensions](https://hypequery.com/recipes/multiif-bucketing)

[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.](https://hypequery.com/recipes/multiif-bucketing)

[Node.jsClickHouseObservabilityProduct analytics](https://hypequery.com/recipes/multiif-bucketing)

[Open recipe](https://hypequery.com/recipes/multiif-bucketing)

[Guide · ClickHouse 25.8](https://hypequery.com/guides/refreshable-materialized-views)

### [Refreshable materialized views in ClickHouse: schedule, refresh, monitor and query them](https://hypequery.com/guides/refreshable-materialized-views)

[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.](https://hypequery.com/guides/refreshable-materialized-views)

[To start of dayQuantileCount](https://hypequery.com/guides/refreshable-materialized-views)

[Open guide](https://hypequery.com/guides/refreshable-materialized-views)

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](https://hypequery.com/semantic-layer)

[The vendor-neutral guide: dbt MetricFlow, Snowflake semantic views, Databricks metric views and OSI compared.](https://hypequery.com/semantic-layer)

[Read](https://hypequery.com/semantic-layer)

### [Datasets docs](https://hypequery.com/docs/datasets/overview)

[Define datasets, dimensions, measures and metrics in TypeScript, then execute and serve them.](https://hypequery.com/docs/datasets/overview)

[Read](https://hypequery.com/docs/datasets/overview)

### [Metrics docs](https://hypequery.com/docs/datasets/metrics)

[Attach named KPIs and derived calculations, such as average order value, to datasets.](https://hypequery.com/docs/datasets/metrics)

[Read](https://hypequery.com/docs/datasets/metrics)

### [Dataset multi-tenancy](https://hypequery.com/docs/datasets/multi-tenancy)

[How tenant keys are enforced at runtime and why missing tenant context fails closed.](https://hypequery.com/docs/datasets/multi-tenancy)

[Read](https://hypequery.com/docs/datasets/multi-tenancy)

### [Python semantic layer](https://hypequery.com/python-semantic-layer)

[The same datasets and Serve protocol for FastAPI, Django and Flask backends.](https://hypequery.com/python-semantic-layer)

[Read](https://hypequery.com/python-semantic-layer)

### [Introducing hypequery datasets](https://hypequery.com/blog/introducing-hypequery-datasets)

[Define dimensions, measures and metrics once, then reuse them across code, APIs, dashboards and agents.](https://hypequery.com/blog/introducing-hypequery-datasets)

[Read](https://hypequery.com/blog/introducing-hypequery-datasets)

### [Introducing hypequery for Python](https://hypequery.com/blog/introducing-hypequery-python)

[The Python SDK: datasets, serving and DataFrames over ClickHouse.](https://hypequery.com/blog/introducing-hypequery-python)

[Read](https://hypequery.com/blog/introducing-hypequery-python)

### [ClickHouse MCP server](https://hypequery.com/clickhouse-mcp)

[Expose datasets to Claude, Cursor and other MCP clients without raw SQL.](https://hypequery.com/clickhouse-mcp)

[Read](https://hypequery.com/clickhouse-mcp)

### [AI analytics chat for ClickHouse](https://hypequery.com/clickhouse-ai)

[Give the Vercel AI SDK, Anthropic SDK or OpenAI Agents SDK your datasets as tools, so in-product chat answers match your dashboards.](https://hypequery.com/clickhouse-ai)

[Read](https://hypequery.com/clickhouse-ai)

### [hypequery vs Cube](https://hypequery.com/compare/hypequery-vs-cube)

[A code-first library compared with a configuration-first semantic layer platform.](https://hypequery.com/compare/hypequery-vs-cube)

[Read](https://hypequery.com/compare/hypequery-vs-cube)

### [Cube.js alternative for ClickHouse](https://hypequery.com/cube-js-alternative)

[A semantic layer with no Cube server, Redis cache or YAML to run.](https://hypequery.com/cube-js-alternative)

[Read](https://hypequery.com/cube-js-alternative)

### [dbt MetricFlow vs a code-defined layer](https://hypequery.com/semantic-layer/dbt-metricflow)

[Semantic models and metric types in dbt, mapped onto datasets defined in code.](https://hypequery.com/semantic-layer/dbt-metricflow)

[Read](https://hypequery.com/semantic-layer/dbt-metricflow)

### [Cube vs Tinybird vs hypequery](https://hypequery.com/compare/cube-vs-tinybird-vs-hypequery)

[A semantic layer platform, a managed analytics service and a library in your codebase, side by side.](https://hypequery.com/compare/cube-vs-tinybird-vs-hypequery)

[Read](https://hypequery.com/compare/cube-vs-tinybird-vs-hypequery)

### [hypequery vs Propel](https://hypequery.com/compare/hypequery-vs-propel)

[Propel's domain now points to a parking page. Where its semantic layer and API users can move.](https://hypequery.com/compare/hypequery-vs-propel)

[Read](https://hypequery.com/compare/hypequery-vs-propel)

### [Embedded runtime](https://hypequery.com/docs/embedded-runtime)

[Run dataset and metric definitions inside your own backend process, with no separate server.](https://hypequery.com/docs/embedded-runtime)

[Read](https://hypequery.com/docs/embedded-runtime)

### [hypequery vs dbt](https://hypequery.com/compare/hypequery-vs-dbt)

[Scheduled transformations in dbt compared with request-time serving from your app.](https://hypequery.com/compare/hypequery-vs-dbt)

[Read](https://hypequery.com/compare/hypequery-vs-dbt)

### [TypeScript vs dbt for ClickHouse](https://hypequery.com/blog/typescript-vs-dbt-clickhouse)

[Which one belongs in your ClickHouse stack, and when you need both.](https://hypequery.com/blog/typescript-vs-dbt-clickhouse)

[Read](https://hypequery.com/blog/typescript-vs-dbt-clickhouse)

### [Embedded analytics](https://hypequery.com/embedded-analytics)

[Serving tenant-scoped metrics to customers, with build vs buy and vendors compared.](https://hypequery.com/embedded-analytics)

[Read](https://hypequery.com/embedded-analytics)

Next step

## Define your first dataset in 30 seconds.

Start open source in your own backend. A hosted option, hypequery cloud, is coming soon.

[Get started](https://hypequery.com/docs)
