> ## Documentation Index
> Fetch the complete documentation index at: https://docs.cube.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# ClickHouse

> Connect Cube to ClickHouse for low-latency analytics, including host credentials and driver-specific connection options.

[ClickHouse](https://clickhouse.com) is a fast and resource efficient
[open-source database](https://github.com/ClickHouse/ClickHouse) for real-time
applications and analytics.

## Prerequisites

* The hostname for the [ClickHouse][clickhouse] database server
* The [username/password][clickhouse-docs-users] for the
  [ClickHouse][clickhouse] database server

## Setup

### Manual

Add the following to a `.env` file in your Cube project:

```dotenv theme={"dark"}
CUBEJS_DB_TYPE=clickhouse
CUBEJS_DB_HOST=my.clickhouse.host
CUBEJS_DB_NAME=my_clickhouse_database
CUBEJS_DB_USER=clickhouse_user
CUBEJS_DB_PASS=**********
```

## Environment Variables

| Environment Variable | Description | Possible Values | Required |
| - | - | - | :-: |
| [`CUBEJS_DB_HOST`](https://docs.cube.dev/reference/configuration/environment-variables#cubejs_db_host) | The host URL for a database | A valid database host URL | ✅ |
| [`CUBEJS_DB_PORT`](https://docs.cube.dev/reference/configuration/environment-variables#cubejs_db_port) | The port for the database connection | A valid port number | ❌ |
| [`CUBEJS_DB_NAME`](https://docs.cube.dev/reference/configuration/environment-variables#cubejs_db_name) | The name of the database to connect to | A valid database name | ✅ |
| [`CUBEJS_DB_USER`](https://docs.cube.dev/reference/configuration/environment-variables#cubejs_db_user) | The username used to connect to the database | A valid database username | ✅ |
| [`CUBEJS_DB_PASS`](https://docs.cube.dev/reference/configuration/environment-variables#cubejs_db_pass) | The password used to connect to the database | A valid database password | ✅ |
| [`CUBEJS_DB_CLICKHOUSE_READONLY`](https://docs.cube.dev/reference/configuration/environment-variables#cubejs_db_clickhouse_readonly) | Whether the ClickHouse user has read-only access or not | `true`, `false` | ❌ |
| [`CUBEJS_DB_CLICKHOUSE_COMPRESSION`](https://docs.cube.dev/reference/configuration/environment-variables#cubejs_db_clickhouse_compression) | Whether the ClickHouse client has compression enabled or not | `true`, `false` | ❌ |
| [`CUBEJS_DB_MAX_POOL`](https://docs.cube.dev/reference/configuration/environment-variables#cubejs_db_max_pool) | The maximum number of concurrent database connections to pool. Default is `20` | A valid number | ❌ |
| [`CUBEJS_CONCURRENCY`](https://docs.cube.dev/reference/configuration/environment-variables#cubejs_concurrency) | The number of [concurrent queries][ref-data-source-concurrency] to the data source | A valid number | ❌ |

[ref-data-source-concurrency]: https://docs.cube.dev/admin/connect-to-data/concurrency.md#data-source-concurrency

## Boolean Dimensions and Segments

ClickHouse evaluates comparisons to `UInt8`, not `Bool`. Cube casts [`boolean`
dimensions][ref-dimension-type] and segments to `Bool` when it selects them, so
boolean dimensions return `true` and `false`, and pre-aggregations store both
as `Bool` columns.

A `boolean` dimension over a `String` column has to hold values that ClickHouse
can read as booleans, such as `true`/`false`, `1`/`0`, or `yes`/`no`.
Otherwise, the query fails with `CANNOT_PARSE_BOOL`. For any other values,
compare the column in the dimension's `sql`, e.g., `{CUBE}.status = 'active'`.

## Pre-Aggregation Feature Support

When using [pre-aggregations][ref-preaggs] with ClickHouse, you have to define
[indexes][ref-preaggs-indexes] in pre-aggregations. Otherwise, you might get
the following error: `ClickHouse doesn't support pre-aggregations without indexes`.

### `count_distinct_approx`

Measures of type
[`count_distinct_approx`][ref-schema-ref-types-formats-countdistinctapprox] can
not be used in pre-aggregations when using ClickHouse as a source database.

### `rollup_join`

You can use [`rollup_join` pre-aggregations][ref-preaggs-rollup-join] to join
data from ClickHouse and other data sources inside Cube Store.

Alternatively, you can leverage ClickHouse support for [integration table
engines](https://clickhouse.com/docs/en/engines/table-engines#integration-engines)
to join data from ClickHouse and other data sources inside ClickHouse.
To do so, define table engines in ClickHouse and connect your ClickHouse as the
only data source to Cube.

## Pre-Aggregation Build Strategies

> [!NOTE]
>
> To learn more about pre-aggregation build strategies, \[head
> here]\[ref-caching-using-preaggs-build-strats].

| Feature | Works with read-only mode? | Is default? |
| - | :-: | :-: |
| Batching | ✅ | ✅ |
| Export Bucket | ✅ | - |

By default, ClickHouse uses [batching][self-preaggs-batching] to build
pre-aggregations.

### Batching

No extra configuration is required to configure batching for ClickHouse.

### Export Bucket

> [!WARNING]
>
> Clickhouse driver **only** supports using AWS S3 for export buckets.

#### AWS S3

For [improved pre-aggregation performance with large
datasets][ref-caching-large-preaggs], enable export bucket functionality by
configuring Cube with the following environment variables:

> [!NOTE]
>
> Ensure the AWS credentials are correctly configured in IAM to allow reads and
> writes to the export bucket in S3.

```dotenv theme={"dark"}
CUBEJS_DB_EXPORT_BUCKET_TYPE=s3
CUBEJS_DB_EXPORT_BUCKET=my.bucket.on.s3
CUBEJS_DB_EXPORT_BUCKET_AWS_KEY=<AWS_KEY>
CUBEJS_DB_EXPORT_BUCKET_AWS_SECRET=<AWS_SECRET>
CUBEJS_DB_EXPORT_BUCKET_AWS_REGION=<AWS_REGION>
```

## SSL

To enable SSL-encrypted connections between Cube and ClickHouse, set the
[`CUBEJS_DB_SSL`](https://docs.cube.dev/reference/configuration/environment-variables#cubejs_db_ssl) environment variable to `true`. For more information on how to
configure custom certificates, please check out [Enable SSL Connections to the
Database][ref-recipe-enable-ssl].

## Custom headers

The ClickHouse driver supports forwarding custom HTTP headers on every request to
the ClickHouse server. This is useful when requests pass through a proxy or gateway
that expects additional headers (e.g., for routing or tracing). See the [ClickHouse
JavaScript client configuration][clickhouse-docs-js-config] for more details.

Custom headers can't be configured via environment variables. Instead, use the
[`driver_factory`](https://docs.cube.dev/reference/configuration/config#driver_factory) configuration
option to pass a `headers` object to the driver:

```python title="Python" theme={"dark"}
from cube import config

@config('driver_factory')
def driver_factory(ctx: dict) -> dict:
  return {
    'type': 'clickhouse',
    'headers': {
      'X-Custom-Header': 'value',
      'X-Routing-Group': 'analytics'
    }
  }
```

```javascript title="JavaScript" theme={"dark"}
module.exports = {
  driverFactory: ({ dataSource }) => ({
    type: "clickhouse",
    headers: {
      "X-Custom-Header": "value",
      "X-Routing-Group": "analytics"
    }
  })
};
```

In multitenant deployments, you can use the [security
context](https://docs.cube.dev/embedding/authentication/security-context.md) to pass per-tenant headers, for example
to forward a user token from the API request down to ClickHouse:

```python title="Python" theme={"dark"}
from cube import config

@config('driver_factory')
def driver_factory(ctx: dict) -> dict:
  security_context = ctx['securityContext']
  return {
    'type': 'clickhouse',
    'headers': {
      'X-Custom-User-Token': security_context['token']
    }
  }
```

```javascript title="JavaScript" theme={"dark"}
module.exports = {
  driverFactory: ({ securityContext }) => ({
    type: "clickhouse",
    headers: {
      "X-Custom-User-Token": securityContext.token
    }
  })
};
```

## Query attribution

Cube identifies itself to ClickHouse as the client `application` (e.g. `CubeDev_Cube/1.7.37`),
visible alongside your other connections in ClickHouse's session and connection monitoring.

Cube sets the ClickHouse [`query_id`](https://clickhouse.com/docs/operations/system-tables/query_log)
of every statement it runs to `<cube-query-id>-<uuid>`, where `<cube-query-id>` is the
identifier shown for the query in Query History and `<uuid>` is generated per statement, so
one Cube query matches as many rows as it ran statements. Use it to trace a Cube query to the
statements it produced in ClickHouse:

```sql theme={"dark"}
SELECT query_id, query, event_time
FROM system.query_log
WHERE query_id LIKE '<cube-query-id>%'
```

## Additional Configuration

You can connect to a ClickHouse database when your user's permissions are
[restricted][clickhouse-readonly] to read-only, by setting
[`CUBEJS_DB_CLICKHOUSE_READONLY`](https://docs.cube.dev/reference/configuration/environment-variables#cubejs_db_clickhouse_readonly) to `true`.

You can connect to a ClickHouse database with compression enabled, by setting
[`CUBEJS_DB_CLICKHOUSE_COMPRESSION`](https://docs.cube.dev/reference/configuration/environment-variables#cubejs_db_clickhouse_compression) to `true`.

[clickhouse]: https://clickhouse.tech/

[clickhouse-docs-users]: https://clickhouse.tech/docs/en/operations/settings/settings-users/

[clickhouse-docs-js-config]: https://clickhouse.com/docs/integrations/javascript#configuration

[clickhouse-readonly]: https://clickhouse.com/docs/en/operations/settings/permissions-for-queries#readonly

[ref-caching-using-preaggs-build-strats]: https://docs.cube.dev/docs/pre-aggregations/using-pre-aggregations.md#pre-aggregation-build-strategies

[ref-recipe-enable-ssl]: https://docs.cube.dev/recipes/configuration/using-ssl-connections-to-data-source.md

[ref-caching-large-preaggs]: https://docs.cube.dev/docs/pre-aggregations/using-pre-aggregations.md#export-bucket

[ref-schema-ref-types-formats-countdistinctapprox]: https://docs.cube.dev/reference/data-modeling/measures.md#type

[ref-dimension-type]: https://docs.cube.dev/reference/data-modeling/dimensions.md#type

[self-preaggs-batching]: #batching

[ref-preaggs]: https://docs.cube.dev/docs/pre-aggregations/using-pre-aggregations.md

[ref-preaggs-indexes]: https://docs.cube.dev/reference/data-modeling/pre-aggregations.md#indexes

[ref-preaggs-rollup-join]: https://docs.cube.dev/reference/data-modeling/pre-aggregations.md#rollup_join


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.