[hypequery](https://hypequery.com/) › ClickHouse Analytics in Python: Define Metrics Once | hypequery
Index for agents: https://hypequery.com/llms.txt
Canonical page: https://hypequery.com/clickhouse-python-analytics

> Build ClickHouse analytics in Python with named measures, joins, and tenant rules. Query them from jobs and notebooks, and serve them to dashboards and agents.

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

ClickHouse Python analytics

# Build ClickHouse analytics in Python once, then use it everywhere

Revenue, paying customers, and average order value start in one script and end up in jobs, notebooks, customer dashboards, and AI agents. hypequery lets you define each metric once in Python, next to your application code, so every consumer gets the same number.

[Start with Python ](https://hypequery.com/docs/quick-start#python)[Serve it with FastAPI](https://hypequery.com/clickhouse-fastapi)

Defined in

Python 3.11+

Used from

Jobs, APIs, React, agents

Tenancy

Enforced on every query

## The same metric, five implementations

Revenue lives in a cron job, a notebook, an API handler, and a dashboard query. Each copy filters completed orders slightly differently, and the numbers stop matching.

## Joins and ratios get rebuilt by hand

Revenue by customer plan needs a join. Average order value needs a guarded division. Every new report rewrites both, and every rewrite is a chance to get them wrong.

## Customer-facing numbers need hard boundaries

Once analytics reach customers, a missing tenant filter is a data leak. A convention in SQL strings is not enough when several services query the same tables.

Define

## Write the metrics as Python, next to your app

A dataset maps a ClickHouse table to named dimensions and measures. Filtered measures, derived ratios, and to-one joins are part of the definition, so callers ask for `average_order_value` instead of rebuilding it.

- Sums, counts, exact distinct counts, percentiles, and filtered measures
- Derived measures with null-safe division, like average order value
- `belongs_to` relationships, so callers can group by `customer.plan`
- Tenant and time keys declared once and enforced on every query

Dataset

### Orders, with the metrics your product reports

analytics/datasets.py

```
# pip install "hypequery[clickhouse,jwt]==0.1.0b3"
from hypequery.datasets import Dataset, belongs_to, dimension, filter, formula, measure

customers = Dataset(
    name="customers",
    source="customers",
    tenant_key="tenant_id",
    dimensions={"id": dimension("string"), "plan": dimension("string")},
)

completed = (filter.eq("status", "completed"),)

orders = Dataset(
    name="orders",
    source="orders",
    tenant_key="tenant_id",
    time_key="created_at",
    dimensions={
        "status": dimension("string"),
        "created_at": dimension("timestamp"),
    },
    measures={
        "revenue": measure.sum("amount", filters=completed),
        "completed_orders": measure.count("id", filters=completed),
        "paying_customers": measure.count_distinct("customer_id", filters=completed),
        "average_order_value": measure.derived(
            formula.divide("revenue", formula.null_if_zero("completed_orders")),
        ),
    },
    relationships={
        "customer": belongs_to(customers, from_field="customer_id", to_field="id"),
    },
)
```

The `completed` filter is defined once and shared by every measure that needs it.

Use

## One client for jobs, notebooks, dashboards, and agents

Query measures by name with a time grain, and hypequery plans parameterized ClickHouse SQL with the join and the tenant predicate on both tables. Serve the same datasets over HTTP when a dashboard or agent needs them.

Results are cached under opaque, tenant-keyed entries, so a dashboard reloading the same chart does not rescan ClickHouse, and two customers never share an entry.

The HTTP endpoint authenticates every request and takes the tenant from the caller, not the request body. `include_related` lets callers group by `customer.plan` over HTTP, and `client_profile` plus the client-contract route are what generated React hooks and the MCP bridge read. See React and MCP clients for exporting the contract.

Consumers

### A monthly report and an authenticated API, from one definition

analytics/app.py

```
from hypequery.datasets import (
    ClientQueryProfile,
    MemoryCacheStore,
    ResultCache,
    create_dataset_client,
    create_dataset_registry,
    tenant,
)
from hypequery.execution import ClickHouseConnection, create_clickhouse_executor
from hypequery.serve import (
    EndpointPolicy,
    add_client_contract_endpoint,
    add_dataset_endpoint,
    create_api,
    jwt_strategy,
    to_asgi_app,
)

from analytics.datasets import customers, orders

analytics = create_dataset_client(
    executor=create_clickhouse_executor(ClickHouseConnection.from_env()),
    registry=create_dataset_registry(orders, customers),
    cache=ResultCache(
        store=MemoryCacheStore(max_entries=1_000),
        project="acme",
        environment="production",
        ttl_seconds=300,
    ),
)

# 1. A scheduled job, a notebook, or one of your own routes
report = analytics.for_tenant(tenant("org_123")).execute(
    "orders",
    {
        "dimensions": ["customer.plan"],
        "measures": ["revenue", "paying_customers", "average_order_value"],
        "by": "month",
    },
)

# 2. The same report over HTTP, for React hooks and MCP tools
api = create_api(
    auth=jwt_strategy(
        jwks_url="https://example.auth0.com/.well-known/jwks.json",
        issuer="https://example.auth0.com/",
        audience="https://api.example.com",
    )
)
policy = EndpointPolicy(tenant="required")
add_dataset_endpoint(
    api,
    "/v1/orders",
    dataset=orders,
    client=analytics,
    policy=policy,
    client_profile=ClientQueryProfile(default_limit=50, max_limit=500),
    include_related=("customer",),
)
add_client_contract_endpoint(api, "/v1/client-contract", policy=policy)
app = to_asgi_app(api)  # or app.mount("/analytics", ...) in FastAPI
```

`ClickHouseConnection.from_env()` reads `CLICKHOUSE_URL` or the `CLICKHOUSE_*` variables.

Where teams usually get stuck

## Questions teams ask

### ClickHouse analytics with Python

Use a driver like clickhouse-connect for ad hoc SQL. Use hypequery datasets for the metrics other code depends on, so there is one definition to review and change.

### Product analytics in a Python backend

Serve tenant-scoped metrics from FastAPI, Django, Flask, or any ASGI or WSGI app, and render them with typed React hooks.

### Not a BI tool

There is no separate server to run or YAML to maintain. Definitions are Python in your repository, reviewed and tested like the rest of your code.

### What is TypeScript-only for now

Window measures (trailing, to-date, cumulative) and period comparisons are TypeScript only. The Python SDK is in beta; see feature status for the full list.

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

[Example · Python](https://hypequery.com/examples/chdb-embedded-analytics)

### [Embedded ClickHouse analytics with chDB: typed datasets, a CLI and an API, no server](https://hypequery.com/examples/chdb-embedded-analytics)

[Run a ClickHouse semantic layer inside your Python process with chDB: no Docker, no server, then point the same datasets at ClickHouse Cloud.](https://hypequery.com/examples/chdb-embedded-analytics)

[PythonchDBClickHouseEmbedded analyticsSemantic layerLocal development](https://hypequery.com/examples/chdb-embedded-analytics)

[Open example](https://hypequery.com/examples/chdb-embedded-analytics)

[Example · Python](https://hypequery.com/examples/fastapi-analytics-api)

### [A FastAPI analytics API on ClickHouse with tenant-scoped datasets](https://hypequery.com/examples/fastapi-analytics-api)

[Serve governed ClickHouse analytics from FastAPI: datasets defined once in Python, query endpoints mounted beside your routes, tenant fixed by the token.](https://hypequery.com/examples/fastapi-analytics-api)

[PythonFastAPIClickHouseAnalytics APIMulti-tenantSaaS analytics](https://hypequery.com/examples/fastapi-analytics-api)

[Open example](https://hypequery.com/examples/fastapi-analytics-api)

[Example · Python](https://hypequery.com/examples/streamlit-dashboard)

### [A governed Streamlit dashboard on ClickHouse with pandas export](https://hypequery.com/examples/streamlit-dashboard)

[Build a Streamlit dashboard on ClickHouse that reads only typed hypequery datasets: filters, a time series, breakdowns and a pandas CSV export.](https://hypequery.com/examples/streamlit-dashboard)

[PythonStreamlitPandasClickHouseDashboardsProduct analyticsSemantic layerTime series](https://hypequery.com/examples/streamlit-dashboard)

[Open example](https://hypequery.com/examples/streamlit-dashboard)

Further reading

## Go deeper where it actually helps

### [Measures](https://hypequery.com/docs/python/datasets/measures)

[Aggregations, filtered measures, and derived formulas.](https://hypequery.com/docs/python/datasets/measures)

[Open guide](https://hypequery.com/docs/python/datasets/measures)

### [Relationships](https://hypequery.com/docs/python/datasets/relationships)

[Group and filter by fields on related datasets.](https://hypequery.com/docs/python/datasets/relationships)

[Open guide](https://hypequery.com/docs/python/datasets/relationships)

### [Caching](https://hypequery.com/docs/python/datasets/caching)

[Tenant-safe result caching with opaque keys.](https://hypequery.com/docs/python/datasets/caching)

[Open guide](https://hypequery.com/docs/python/datasets/caching)

### [Serving](https://hypequery.com/docs/python/serving)

[Authenticated HTTP endpoints from any ASGI or WSGI app.](https://hypequery.com/docs/python/serving)

[Open guide](https://hypequery.com/docs/python/serving)

### [React and MCP clients](https://hypequery.com/docs/python/client-endpoints)

[Export the client contract for typed React hooks and the MCP bridge.](https://hypequery.com/docs/python/client-endpoints)

[Open guide](https://hypequery.com/docs/python/client-endpoints)

### [FastAPI and React analytics](https://hypequery.com/fastapi-react-analytics)

[Typed React hooks on the endpoints your Python app serves.](https://hypequery.com/fastapi-react-analytics)

[Open guide](https://hypequery.com/fastapi-react-analytics)

### [Python feature status](https://hypequery.com/docs/python/feature-status)

[What ships in the beta, and what is TypeScript-only for now.](https://hypequery.com/docs/python/feature-status)

[Open guide](https://hypequery.com/docs/python/feature-status)

Related pillars

[ClickHouse with Python](https://hypequery.com/clickhouse-python)[ClickHouse with FastAPI](https://hypequery.com/clickhouse-fastapi)[Python semantic layer](https://hypequery.com/python-semantic-layer)[Multi-tenant Python analytics](https://hypequery.com/clickhouse-python-multi-tenant)[ClickHouse to pandas](https://hypequery.com/clickhouse-pandas)[ClickHouse MCP for Python](https://hypequery.com/clickhouse-python-mcp)[ClickHouse analytics](https://hypequery.com/clickhouse-analytics)

Next step

## Move one shared metric into a dataset

Pick the number your team argues about most, define it once, and point one job and one dashboard at it.

Open source, and it runs in your own backend. Want it hosted?

[Get started ](https://hypequery.com/docs/quick-start#python)[Datasets docs](https://hypequery.com/docs/python/datasets/overview)
