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

> 您可以使用 dbt 在 ClickHouse 中对数据进行转换和建模

# 集成 dbt 与 ClickHouse

export const ClickHouseSupportedBadge = () => {
  return <div className="ClickHouseSupportedBadge">
            <div className="ClickHouseSupportedIcon">
                <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M1.30762 1.39073C1.30762 1.3103 1.37465 1.22986 1.46849 1.22986H2.64824C2.72868 1.22986 2.80912 1.29689 2.80912 1.39073V14.4886C2.80912 14.5691 2.74209 14.6495 2.64824 14.6495H1.46849C1.38805 14.6495 1.30762 14.5825 1.30762 14.4886V1.39073Z" fill="currentColor" />
                    <path d="M4.2832 1.39073C4.2832 1.3103 4.35023 1.22986 4.44408 1.22986H5.62383C5.70427 1.22986 5.7847 1.29689 5.7847 1.39073V14.4886C5.7847 14.5691 5.71767 14.6495 5.62383 14.6495H4.44408C4.36364 14.6495 4.2832 14.5825 4.2832 14.4886V1.39073Z" fill="currentColor" />
                    <path d="M7.25977 1.39073C7.25977 1.3103 7.3268 1.22986 7.42064 1.22986H8.60039C8.68083 1.22986 8.76127 1.29689 8.76127 1.39073V14.4886C8.76127 14.5691 8.69423 14.6495 8.60039 14.6495H7.42064C7.3402 14.6495 7.25977 14.5825 7.25977 14.4886V1.39073Z" fill="currentColor" />
                    <path d="M10.2354 1.39073C10.2354 1.3103 10.3024 1.22986 10.3962 1.22986H11.576C11.6564 1.22986 11.7369 1.29689 11.7369 1.39073V14.4886C11.7369 14.5691 11.6698 14.6495 11.576 14.6495H10.3962C10.3158 14.6495 10.2354 14.5825 10.2354 14.4886V1.39073Z" fill="currentColor" />
                    <path d="M13.2256 6.6057C13.2256 6.52526 13.2926 6.44482 13.3865 6.44482H14.5662C14.6466 6.44482 14.7271 6.51186 14.7271 6.6057V9.27354C14.7271 9.35398 14.6601 9.43442 14.5662 9.43442H13.3865C13.306 9.43442 13.2256 9.36739 13.2256 9.27354V6.6057Z" fill="currentColor" />
                </svg>
            </div>
            支持 ClickHouse
        </div>;
};

<ClickHouseSupportedBadge />

<div id="dbt-clickhouse-adapter">
  ## dbt-clickhouse 适配器
</div>

**dbt** (data build tool) 让分析工程师只需编写 SELECT 语句，即可在其数据仓库中转换数据。dbt 会将这些 SELECT 语句物化为数据库中的表和视图等对象，也就是完成 [Extract Load and Transform (ELT)](https://en.wikipedia.org/wiki/Extract,_load,_transform) 中的 T。你可以创建由 SELECT 语句定义的模型。

在 dbt 中，这些模型可以相互引用并分层组织，从而构建更高层级的概念。连接各模型所需的样板 SQL 会自动生成。此外，dbt 还能识别模型之间的依赖关系，并通过有向无环图 (DAG) 确保按正确的顺序创建它们。

dbt 可通过 [ClickHouse 支持的 适配器](https://github.com/ClickHouse/dbt-clickhouse) 与 ClickHouse 兼容。

<div id="related-pages">
  ## 相关页面
</div>

| 页面                                                                                                               | 描述                           |
| ---------------------------------------------------------------------------------------------------------------- | ---------------------------- |
| [功能与配置](/docs/zh/integrations/connectors/data-ingestion/etl-tools/dbt/features-and-configurations)                    | 可用功能和通用配置的说明                 |
| [物化类型](/docs/zh/integrations/connectors/data-ingestion/etl-tools/dbt/materializations)                                | 可用的物化类型及其配置                  |
| [Materialized views](/docs/zh/integrations/connectors/data-ingestion/etl-tools/dbt/materialization-materialized-view) | materialized\_view 物化类型的专门文档 |
| [指南](/docs/zh/integrations/connectors/data-ingestion/etl-tools/dbt/guides)                                            | 使用 dbt 和 ClickHouse 的指南      |

<div id="supported-features">
  ## 支持的功能
</div>

支持的功能列表：

* [x] 表物化类型
* [x] 视图物化类型
* [x] 增量物化类型
* [x] Microbatch 增量物化类型
* [x] materialized view 物化类型 (使用 MATERIALIZED VIEW 的 `TO` 形式，属 Experimental)
* [x] Seeds
* [x] Sources
* [x] 文档生成
* [x] 测试
* [x] Snapshots
* [x] 大多数 dbt-utils macro (现已并入 dbt-core)
* [x] Ephemeral 物化类型
* [x] 分布式表物化类型 (属 Experimental)
* [x] 分布式增量物化类型 (属 Experimental)
* [x] Contracts
* [x] ClickHouse 特有的列配置 (Codec、生存时间 (TTL)...)
* [x] ClickHouse 特有的表设置 (索引、projections...)

支持截至 dbt-core 1.10 的所有功能，包括 `--sample` 标志，并且已修复所有面向后续版本的弃用警告。dbt 1.10 中引入的**Catalog 集成** (例如 Iceberg) 目前尚未在该适配器中获得原生支持，但已有可用的变通方案。详情请参见 [Catalog Support 部分](/docs/zh/integrations/connectors/data-ingestion/etl-tools/dbt/features-and-configurations#catalog-support)。

该适配器暂时还无法在 [dbt Cloud](https://docs.getdbt.com/docs/dbt-cloud/cloud-overview) 中使用，但我们预计很快会提供支持。如需了解更多信息，请联系支持团队。

<div id="concepts-and-supported-materializations">
  ## dbt 概念和支持的物化类型
</div>

dbt 引入了“模型”这一概念。模型被定义为一条 SQL 语句，可能会连接多个表。一个模型可以通过多种方式进行“物化”。物化类型表示模型的 select 查询采用何种构建策略。物化类型背后的代码是样板 SQL，会将你的 SELECT 查询封装进一条语句中，以创建新的关系或更新现有关系。

dbt 提供 5 种物化类型，`dbt-clickhouse` 全部支持：

* **view** (默认) ：模型会在数据库中构建为视图。在 ClickHouse 中，这会构建为一个[视图](/docs/zh/reference/statements/create/view)。
* **table**：模型会在数据库中构建为表。在 ClickHouse 中，这会构建为一个[表](/docs/zh/reference/statements/create/table)。
* **ephemeral**：模型不会直接在数据库中构建，而是会作为 CTE (Common Table Expressions，公用表表达式) 被引入依赖它的模型中。
* **incremental**：模型最初会被物化为表，在后续运行中，dbt 会向表中插入新行并更新发生变化的行。
* **materialized view**：模型会在数据库中构建为 materialized view。在 ClickHouse 中，这会构建为一个[materialized view](/docs/zh/reference/statements/create/view#materialized-view)。

附加的语法和子句定义了当这些模型的底层数据发生变化时应如何更新。dbt 通常建议先从 view 物化类型开始，直到性能成为关注重点。table 物化类型通过将模型查询结果保存为表来提升查询时性能，但代价是会增加存储开销。incremental 方法则在此基础上进一步扩展，使后续对底层数据的更新能够反映到目标表中。

ClickHouse 的[当前 适配器](https://github.com/silentsokolov/dbt-clickhouse) 还支持 **dictionary**、**distributed table** 和 **distributed incremental** 物化类型。该 适配器 还支持 dbt 的 [snapshots](https://docs.getdbt.com/docs/building-a-dbt-project/snapshots#check-strategy) 和 [seeds](https://docs.getdbt.com/docs/building-a-dbt-project/seeds)。

以下是 `dbt-clickhouse` 中的[实验性功能](/docs/zh/reference/settings/beta-and-experimental-features)：

| 类型                           | 是否支持                 | 详情                                                                                                                                                                      |
| ---------------------------- | -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Materialized View 物化类型       | 是。使用显式目标创建处于 Beta 阶段 | 创建一个 [materialized view](/docs/zh/reference/statements/create/view#materialized-view)。                                                                                       |
| 分布式表物化类型                     | 是，Experimental       | 创建一个[分布式表](/docs/zh/reference/engines/table-engines/special/distributed)。                                                                                                    |
| Distributed incremental 物化类型 | 是，Experimental       | 这是一种基于与分布式表相同思路的增量模型。请注意，并非所有策略都受支持，更多信息请参阅[相关文档章节](/docs/zh/integrations/connectors/data-ingestion/etl-tools/dbt/materializations#materialization-distributed-incremental)。 |
| 字典物化类型                       | 是，Experimental       | 创建一个[字典](/docs/zh/reference/engines/table-engines/special/dictionary)。                                                                                                       |

<div id="setup-of-dbt-and-the-clickhouse-adapter">
  ## 设置 dbt 和 ClickHouse 适配器
</div>

<div id="install-dbt-core-and-dbt-clickhouse">
  ### 安装 dbt-core 和 dbt-clickhouse
</div>

dbt 提供了多种安装命令行界面 (CLI) 的方式，详细说明请参见[此处](https://docs.getdbt.com/dbt-cli/install/overview)。我们建议使用 `pip` 安装 dbt 和 dbt-clickhouse。

```sh theme={null}
pip install dbt-core dbt-clickhouse
```

<div id="provide-dbt-with-the-connection-details-for-our-clickhouse-instance">
  ### 为 dbt 提供 ClickHouse 实例的连接信息。
</div>

在 `~/.dbt/profiles.yml` 文件中配置 `clickhouse-service` profile，并提供 schema、主机、端口、用户名和密码等属性。完整的连接配置选项列表可参见 [功能与配置](/docs/zh/integrations/connectors/data-ingestion/etl-tools/dbt/features-and-configurations) 页面：

```yaml theme={null}
clickhouse-service:
  target: dev
  outputs:
    dev:
      type: clickhouse
      schema: [ default ] # 用于 dbt 模型的 ClickHouse 数据库

      # 可选
      host: [ localhost ]
      port: [ 8123 ]  # 默认值为 8123、8443、9000 或 9440，具体取决于 secure 和 driver 设置 
      user: [ default ] # 用于所有数据库操作的用户
      password: [ <empty string> ] # 该用户的密码
      secure: True  # 使用 TLS（native protocol）或 HTTPS（HTTP protocol）
```

<div id="create-a-dbt-project">
  ### 创建 dbt 项目
</div>

现在，您可以在现有项目中使用此 profile，或使用以下命令新建一个项目：

```sh theme={null}
dbt init project_name
```

在 `project_name` 目录中，更新 `dbt_project.yml` 文件，指定用于连接 ClickHouse server 的 profile 名称。

```yaml theme={null}
profile: 'clickhouse-service'
```

<div id="test-connection">
  ### 测试连接
</div>

使用 CLI 工具执行 `dbt debug`，确认 dbt 能否连接到 ClickHouse。确认返回结果中包含 `Connection test: [OK connection ok]`，表示连接成功。

前往[指南页面](/docs/zh/integrations/connectors/data-ingestion/etl-tools/dbt/guides)，了解如何将 dbt 与 ClickHouse 配合使用的更多信息。

<div id="testing-and-deploying-your-models-ci-cd">
  ### 测试和部署你的模型 (CI/CD)
</div>

测试和部署 dbt 项目的方法有很多。对于[最佳实践工作流](https://docs.getdbt.com/best-practices/best-practice-workflows#pro-tips-for-workflows)和 [CI 作业](https://docs.getdbt.com/docs/deploy/ci-jobs)，dbt 也提供了一些建议。下面我们会介绍几种策略，但请注意，这些策略可能需要根据你的具体使用场景进行较大调整。

<div id="ci-with-simple-data-tests-and-unit-tests">
  #### 使用简单数据测试和单元测试的 CI/CD
</div>

快速启动 CI 管道的一种简单方法，是在你的 job 中运行一个 ClickHouse 集群，然后针对该集群运行你的模型。你可以在运行模型之前，先向该集群插入演示数据。你只需使用一个 [seed](https://docs.getdbt.com/reference/commands/seed)，即可用生产数据的一个子集填充暂存环境。

数据插入完成后，你就可以运行 [数据测试](https://docs.getdbt.com/docs/build/data-tests) 和 [单元测试](https://docs.getdbt.com/docs/build/unit-tests)。

你的 CD 步骤也可以很简单：直接针对生产环境中的 ClickHouse 集群运行 `dbt build`。

<div id="more-complete-ci-stage">
  #### 更完整的 CI/CD 阶段：使用最新数据，只测试受影响的模型
</div>

一种常见策略是使用 [Slim CI](https://docs.getdbt.com/best-practices/best-practice-workflows#run-only-modified-models-to-test-changes-slim-ci) 作业，只重新部署被修改的模型 (以及它们的上下游依赖) 。这种方法利用生产运行生成的制品 (即 [dbt manifest](https://docs.getdbt.com/reference/artifacts/manifest-json)) ，以缩短项目运行时间，并确保各环境之间不会出现 schema 漂移。

为了让开发环境保持同步，并避免让模型针对过时的部署运行，你可以使用 [clone](https://docs.getdbt.com/reference/commands/clone)，甚至 [defer](https://docs.getdbt.com/reference/node-selection/defer)。

我们建议为测试环境 (即暂存环境) 使用专用的 ClickHouse 集群或服务，以避免影响生产环境的运行。为了确保测试环境具有代表性，务必要使用生产数据的一个子集，并以能够防止环境之间出现 schema 漂移的方式运行 dbt。

* 如果你不需要使用最新数据进行测试，可以将生产数据的备份恢复到暂存环境中。
* 如果你需要使用最新数据进行测试，可以结合使用 [`remoteSecure()` table function](/docs/zh/reference/functions/table-functions/remote) 和可刷新materialized view，按所需频率执行 insert。另一种做法是将对象存储作为中间层，定期从生产服务写入数据，再通过对象存储 table function 或 ClickPipes (用于持续摄取) 将其导入暂存环境。

使用专用环境进行 CI 测试，也便于你在不影响生产环境的情况下执行手动测试。例如，你可能希望将某个 BI 工具指向该环境进行测试。

对于部署 (即 CD 步骤) ，我们建议使用生产部署生成的制品，只更新发生变化的模型。这需要将对象存储 (例如 S3) 配置为 dbt 制品的中间存储。完成设置后，你可以运行类似 `dbt build --select state:modified+ --state path/to/last/deploy/state.json` 的命令，根据自上次生产运行以来的变更，有选择地仅重建所需的最少模型。

<div id="troubleshooting-common-issues">
  ## 常见问题排查
</div>

<div id="troubleshooting-connections">
  ### 连接
</div>

如果你在使用 dbt 连接 ClickHouse 时遇到问题，请确保满足以下条件：

* 所用引擎必须是[受支持的引擎](/docs/zh/integrations/connectors/data-ingestion/etl-tools/dbt/materializations#supported-table-engines)之一。
* 你必须具备访问数据库的足够权限。
* 如果你使用的不是数据库的默认表引擎，则必须在模型
  配置中指定表引擎。

<div id="understanding-long-running-operations">
  ### 了解长时间运行的操作
</div>

由于某些特定的 ClickHouse 查询，部分操作的耗时可能会超出预期。为了更清楚地了解哪些查询耗时较长，请将[日志级别](https://docs.getdbt.com/reference/global-configs/logs#log-level)提升到 `debug`——这样会输出每个查询的耗时。例如，可以通过在 dbt 命令中附加 `--log-level debug` 来实现。

<div id="limitations">
  ## 限制
</div>

当前用于 dbt 的 ClickHouse 适配器 有一些限制需要注意：

* 该插件使用的语法要求 ClickHouse 版本为 25.3 或更高。我们不测试较旧版本的 ClickHouse，目前也不测试 Replicated 表。
* 如果同时运行，不同的 `dbt-adapter` 运行之间可能会发生冲突，因为它们在内部可能会为相同操作使用相同的表名。更多信息，请参见问题 [#420](https://github.com/ClickHouse/dbt-clickhouse/issues/420)。
* 该 适配器 当前使用 [INSERT INTO SELECT](/docs/zh/reference/statements/insert-into#inserting-the-results-of-select) 将模型 materialize 为表。这实际上意味着如果再次执行运行，会产生重复数据。超大数据集 (PB 级) 可能会导致运行时间极长，从而使某些模型不具备可行性。要提升性能，请通过将视图实现为 `materialized: materialization_view` 来使用 ClickHouse Materialized Views。此外，应尽可能使用 `GROUP BY`，以减少任何查询返回的行数。相比只做转换但保持 source 行数不变的模型，应优先选择对数据进行汇总的模型。
* 要使用 分布式表 来表示模型，必须先在每个节点上手动创建底层 replicated 表，然后再在这些表之上创建 Distributed 表。该 适配器 不管理 cluster 的创建。
* 当 dbt 在 database 中创建 relation (表/视图) 时，通常会按以下形式创建：`{{ database }}.{{ schema }}.{{ table/view id }}`。ClickHouse 没有 schema 的概念，因此该 适配器 使用 `{{schema}}.{{ table/view id }}`，其中 `schema` 就是 ClickHouse database。
* 如果将 ephemeral 模型/CTE 放在 ClickHouse insert 语句的 `INSERT INTO` 之前，它们将无法工作，参见 [https://github.com/ClickHouse/ClickHouse/issues/30323。这一般不会影响大多数模型，但在模型定义和其他](https://github.com/ClickHouse/ClickHouse/issues/30323。这一般不会影响大多数模型，但在模型定义和其他) SQL 语句中放置 ephemeral 模型时仍需谨慎。 {/* TODO review this limitation, looks like the issue was already closed and the fix was introduced in 24.10 */}

<div id="fivetran">
  ## Fivetran
</div>

`dbt-clickhouse` 连接器也可用于 [Fivetran transformations](https://fivetran.com/docs/transformations/dbt)，从而能够在 Fivetran 平台内直接使用 `dbt` 实现无缝集成和转换。
