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

> 您可以使用 Google Dataflow 模板将数据从 BigQuery 摄取到 ClickHouse

# Dataflow：BigQuery 到 ClickHouse 模板

export const Image = ({img, alt, size = "lg"}) => {
  const normalizedSize = ["sm", "md", "lg"].includes(size) ? size : "lg";
  return <div className={`ch-image-${normalizedSize}`}>
      <Frame>
        <img src={img} alt={alt} />
      </Frame>
    </div>;
};

BigQuery 到 ClickHouse 的模板是一个批次管道，用于将 BigQuery 表中的数据摄取到 ClickHouse 表中。
该模板可以读取整个表，也可以使用提供的 SQL 查询过滤特定记录。

<div id="pipeline-requirements">
  ## 管道要求
</div>

* 源 BigQuery 表必须存在。
* 目标 ClickHouse 表必须存在。
* 必须能够从 Dataflow 工作节点访问 ClickHouse 主机。

<div id="template-parameters">
  ## Template参数
</div>

<br />

<br />

| 参数名称                    | 参数说明                                                                                                                                                                                                                                   | 必填 | 说明                                                                                                                                                                                                              |
| ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `jdbcUrl`               | ClickHouse JDBC URL，格式为 `jdbc:clickhouse://<host>:<port>/<schema>`。                                                                                                                                                                    | ✅  | 不要将用户名和密码作为 JDBC 选项添加。其他 JDBC 选项可附加在 JDBC URL 末尾。对于 ClickHouse Cloud 用户，请在 `jdbcUrl` 中添加 `ssl=true&sslmode=NONE`。                                                                                               |
| `clickHouseUsername`    | 用于身份验证的 ClickHouse 用户名。                                                                                                                                                                                                                | ✅  |                                                                                                                                                                                                                 |
| `clickHousePassword`    | 用于身份验证的 ClickHouse 密码。                                                                                                                                                                                                                 | ✅  |                                                                                                                                                                                                                 |
| `clickHouseTable`       | 用于插入数据的目标 ClickHouse 表。                                                                                                                                                                                                                | ✅  |                                                                                                                                                                                                                 |
| `maxInsertBlockSize`    | 插入时的最大块大小；如果插入用的块由我们控制创建，则使用此参数 (ClickHouseIO 选项) 。                                                                                                                                                                                    |    | 一个 `ClickHouseIO` 选项。                                                                                                                                                                                           |
| `insertDistributedSync` | 如果启用此设置，写入 Distributed 表的插入查询会等待数据发送到 cluster 中的所有节点。 (ClickHouseIO 选项) 。                                                                                                                                                              |    | 一个 `ClickHouseIO` 选项。                                                                                                                                                                                           |
| `insertQuorum`          | 对于 Replicated 表中的 INSERT 查询，等待写入到指定数量的副本，并将数据追加线性化。0 - 禁用。                                                                                                                                                                             |    | 一个 `ClickHouseIO` 选项。此设置在默认服务器设置中处于禁用状态。                                                                                                                                                                        |
| `insertDeduplicate`     | 对于 Replicated 表中的 INSERT 查询，指定是否对插入块执行去重。                                                                                                                                                                                              |    | 一个 `ClickHouseIO` 选项。                                                                                                                                                                                           |
| `maxRetries`            | 每次插入的最大重试次数。                                                                                                                                                                                                                           |    | 一个 `ClickHouseIO` 选项。                                                                                                                                                                                           |
| `InputTableSpec`        | 要读取的 BigQuery 表。请指定 `inputTableSpec` 或 `query` 之一。如果两者都设置了，则优先使用 `query` 参数。示例：`<BIGQUERY_PROJECT>:<DATASET_NAME>.<INPUT_TABLE>`。                                                                                                      |    | 使用 [BigQuery Storage Read API](https://cloud.google.com/bigquery/docs/reference/storage) 直接从 BigQuery 存储中读取数据。请注意 [Storage Read API 的限制](https://cloud.google.com/bigquery/docs/reference/storage#limitations)。 |
| `outputDeadletterTable` | 用于存放未能写入输出表的消息的 BigQuery 表。如果该表不存在，则会在管道执行期间创建。如果未指定，则使用 `<outputTableSpec>_error_records`。例如：`<PROJECT_ID>:<DATASET_NAME>.<DEADLETTER_TABLE>`。                                                                                        |    |                                                                                                                                                                                                                 |
| `query`                 | 用于从 BigQuery 读取数据的 SQL 查询。如果 BigQuery 数据集与 Dataflow 作业不在同一项目中，请在 SQL 查询中指定完整的数据集名称，例如：`<PROJECT_ID>.<DATASET_NAME>.<TABLE_NAME>`。除非 `useLegacySql` 为 true，否则默认使用 [GoogleSQL](https://cloud.google.com/bigquery/docs/introduction-sql)。 |    | 必须指定 `inputTableSpec` 或 `query` 之一。如果同时设置这两个参数，Template将使用 `query` 参数。示例：`SELECT * FROM sampledb.sample_table`。                                                                                                 |
| `useLegacySql`          | 设为 `true` 以使用传统 SQL。此参数仅在使用 `query` 参数时适用。默认值为 `false`。                                                                                                                                                                                |    |                                                                                                                                                                                                                 |
| `queryLocation`         | 当从授权视图读取数据且没有底层表权限时需要设置。例如，`US`。                                                                                                                                                                                                       |    |                                                                                                                                                                                                                 |
| `queryTempDataset`      | 指定一个现有数据集，用于创建临时表以存储查询结果。例如，`temp_dataset`。                                                                                                                                                                                            |    |                                                                                                                                                                                                                 |
| `KMSEncryptionKey`      | 如果通过查询源从 BigQuery 读取数据，请使用此 Cloud KMS 密钥对创建的任何临时表进行加密。例如，`projects/your-project/locations/global/keyRings/your-keyring/cryptoKeys/your-key`。                                                                                           |    |                                                                                                                                                                                                                 |

<Note>
  所有 `ClickHouseIO` 参数的默认值均可在 [`ClickHouseIO` Apache Beam 连接器](/docs/zh/integrations/connectors/data-ingestion/etl-tools/apache-beam#clickhouseiowrite-parameters)中找到。
</Note>

<div id="source-and-target-tables-schema">
  ## 源表和目标表的 schema
</div>

为了高效地将 BigQuery 数据集加载到 ClickHouse 中，管道会执行列推断过程，分为以下几个阶段：

1. 模板基于目标 ClickHouse 表构建 schema 对象。
2. 模板遍历 BigQuery 数据集，并尝试根据列名进行匹配。

<br />

<Warning>
  不过，你的 BigQuery 数据集 (无论是表还是查询) 必须与 ClickHouse
  目标表具有完全相同的列名。
</Warning>

<div id="data-types-mapping">
  ## 数据类型映射
</div>

BigQuery 类型会根据你的 ClickHouse 表定义进行转换。因此，上表列出了你的目标 ClickHouse 表中建议采用的映射 (针对给定的 BigQuery 表/查询) ：

| BigQuery 类型                                                                                                        | ClickHouse 类型                                        | 备注                                                                                                                                                                                                                                                                 |
| ------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| [**Array 类型**](https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#array_type)                | [**Array 类型**](/docs/zh/reference/data-types/array)       | 内部类型必须是此表中列出的受支持基本类型之一。                                                                                                                                                                                                                                            |
| [**Boolean 类型**](https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#boolean_type)            | [**Bool 类型**](/docs/zh/reference/data-types/boolean)      |                                                                                                                                                                                                                                                                    |
| [**Date 类型**](https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#date_type)                  | [**Date 类型**](/docs/zh/reference/data-types/date)         |                                                                                                                                                                                                                                                                    |
| [**Datetime 类型**](https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#datetime_type)          | [**Datetime 类型**](/docs/zh/reference/data-types/datetime) | 同样也适用于 `Enum8`、`Enum16` 和 `FixedString`。                                                                                                                                                                                                                           |
| [**String 类型**](https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#string_type)              | [**String 类型**](/docs/zh/reference/data-types/string)     | 在 BigQuery 中，所有 Int 类型 (`INT`、`SMALLINT`、`INTEGER`、`BIGINT`、`TINYINT`、`BYTEINT`) 都是 `INT64` 的别名。我们建议你在 ClickHouse 中设置合适的整数位宽，因为模板会根据已定义的列类型 (`Int8`、`Int16`、`Int32`、`Int64`) 转换该列。                                                                                 |
| [**Numeric - Integer 类型**](https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#numeric_types) | [**Integer 类型**](/docs/zh/reference/data-types/int-uint)  | 在 BigQuery 中，所有 Int 类型 (`INT`、`SMALLINT`、`INTEGER`、`BIGINT`、`TINYINT`、`BYTEINT`) 都是 `INT64` 的别名。我们建议你在 ClickHouse 中设置合适的整数位宽，因为模板会根据已定义的列类型 (`Int8`、`Int16`、`Int32`、`Int64`) 转换该列。如果 ClickHouse 表中使用了未明确指定的 Int 类型 (`UInt8`、`UInt16`、`UInt32`、`UInt64`) ，模板也会进行转换。 |
| [**Numeric - Float 类型**](https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#numeric_types)   | [**Float 类型**](/docs/zh/reference/data-types/float)       | 支持的 ClickHouse 类型：`Float32` 和 `Float64`                                                                                                                                                                                                                            |

<div id="running-the-template">
  ## 运行Template
</div>

BigQuery 到 ClickHouse 的Template可通过 Google Cloud CLI 运行。

<Note>
  请务必阅读本文档，尤其是上面的各个章节，以充分了解此Template的配置要求和前置条件。
</Note>

<Tabs>
  <Tab title="Google Cloud Console">
    登录 Google Cloud Console 并搜索 DataFlow。

    1. 点击 `CREATE JOB FROM TEMPLATE` 按钮
           <Image img="https://mintcdn.com/private-7c7dfe99/pIetLsS_hOGHqoPJ/images/integrations/data-ingestion/google-dataflow/create_job_from_template_button.webp?fit=max&auto=format&n=pIetLsS_hOGHqoPJ&q=85&s=ca429a13d8a9e99c43ae477bf14ad1a9" border alt="DataFlow 控制台" width="1872" height="886" data-path="images/integrations/data-ingestion/google-dataflow/create_job_from_template_button.webp" />
    2. 打开Template表单后，输入作业名称并选择所需区域。
           <Image img="https://mintcdn.com/private-7c7dfe99/pIetLsS_hOGHqoPJ/images/integrations/data-ingestion/google-dataflow/template_initial_form.webp?fit=max&auto=format&n=pIetLsS_hOGHqoPJ&q=85&s=740afe5c75d840932c0a1071ec2e4e9c" border alt="DataFlow Template初始表单" width="1284" height="680" data-path="images/integrations/data-ingestion/google-dataflow/template_initial_form.webp" />
    3. 在 `DataFlow Template` 输入框中，输入 `ClickHouse` 或 `BigQuery`，然后选择 `BigQuery to ClickHouse` Template
           <Image img="https://mintcdn.com/private-7c7dfe99/pIetLsS_hOGHqoPJ/images/integrations/data-ingestion/google-dataflow/template_clickhouse_search.webp?fit=max&auto=format&n=pIetLsS_hOGHqoPJ&q=85&s=ce42d64ae501b16d2eda4435a6d6b755" border alt="选择 BigQuery 到 ClickHouse Template" width="1370" height="698" data-path="images/integrations/data-ingestion/google-dataflow/template_clickhouse_search.webp" />
    4. 选中后，表单会展开，以便你填写更多详细信息：
       * ClickHouse server JDBC URL，格式如下：`jdbc:clickhouse://host:port/schema`。
       * ClickHouse 用户名。
       * ClickHouse 目标表名称。

    <br />

    <Note>
      ClickHouse 密码选项被标记为可选，适用于未配置密码的场景。
      如需添加，请向下滚动到 `Password for ClickHouse Endpoint` 选项。
    </Note>

    <Image img="https://mintcdn.com/private-7c7dfe99/pIetLsS_hOGHqoPJ/images/integrations/data-ingestion/google-dataflow/extended_template_form.webp?fit=max&auto=format&n=pIetLsS_hOGHqoPJ&q=85&s=c070559675a9e221413cb0e69408dbde" border alt="BigQuery 到 ClickHouse 扩展Template表单" width="1903" height="864" data-path="images/integrations/data-ingestion/google-dataflow/extended_template_form.webp" />

    5. 根据[Template参数](#template-parameters)部分中的详细说明，自定义并添加任何与 BigQuery/ClickHouseIO 相关的配置
  </Tab>

  <Tab title="Google Cloud CLI">
    ### 安装并配置 `gcloud` CLI

    * 如果尚未安装，请安装 [`gcloud` CLI](https://cloud.google.com/sdk/docs/install)。
    * 按照[本指南](https://cloud.google.com/dataflow/docs/guides/templates/using-flex-templates#before-you-begin)中的 `Before you begin` 部分，设置运行 DataFlow Template所需的配置、设置和权限。

    ### 运行命令

    使用 [`gcloud dataflow flex-template run`](https://cloud.google.com/sdk/gcloud/reference/dataflow/flex-template/run)
    命令运行使用 Flex Template 的 Dataflow 作业。

    下面是一个命令示例：

    ```bash theme={null}
    gcloud dataflow flex-template run "bigquery-clickhouse-dataflow-$(date +%Y%m%d-%H%M%S)" \
     --template-file-gcs-location "gs://clickhouse-dataflow-templates/bigquery-clickhouse-metadata.json" \
     --parameters inputTableSpec="<bigquery table id>",jdbcUrl="jdbc:clickhouse://<clickhouse host>:<clickhouse port>/<schema>?ssl=true&sslmode=NONE",clickHouseUsername="<username>",clickHousePassword="<password>",clickHouseTable="<clickhouse target table>"
    ```

    ### 命令说明

    * **作业名称：** `run` 关键字后面的文本是唯一的作业名称。
    * **Template文件：** `--template-file-gcs-location` 指定的 JSON file 定义了Template结构以及接受的参数详情。该文件路径是公开的，可直接使用。
    * **参数：** 参数之间以逗号分隔。对于字符串参数，请用双引号将值括起来。

    ### 预期响应

    运行命令后，你应会看到类似下面的响应：

    ```bash theme={null}
    job:
      createTime: '2025-01-26T14:34:04.608442Z'
      currentStateTime: '1970-01-01T00:00:00Z'
      id: 2025-01-26_06_34_03-13881126003586053150
      location: us-central1
      name: bigquery-clickhouse-dataflow-20250126-153400
      projectId: ch-integrations
      startTime: '2025-01-26T14:34:04.608442Z'
    ```
  </Tab>
</Tabs>

<div id="monitor-the-job">
  ### 监控作业
</div>

前往 Google Cloud Console 中的 [Dataflow Jobs 选项卡](https://console.cloud.google.com/dataflow/jobs)，查看该作业的状态。你可以在这里找到作业的详细信息，包括进度以及任何错误：

<Image img="https://mintcdn.com/private-7c7dfe99/pIetLsS_hOGHqoPJ/images/integrations/data-ingestion/google-dataflow/dataflow-inqueue-job.webp?fit=max&auto=format&n=pIetLsS_hOGHqoPJ&q=85&s=adf4aca711a2783a0bb1062e9051ec41" size="lg" border alt="DataFlow 控制台显示一个正在运行的从 BigQuery 到 ClickHouse 的作业" width="1668" height="202" data-path="images/integrations/data-ingestion/google-dataflow/dataflow-inqueue-job.webp" />

<div id="troubleshooting">
  ## 故障排查
</div>

<div id="code-241-dbexception-memory-limit-total-exceeded">
  ### 超出内存限制 (总量) 错误 (代码 241)
</div>

当 ClickHouse 在处理大批次数据时内存耗尽，就会出现此错误。要解决此问题：

* 增加实例资源：将 ClickHouse server 升级到内存更大的更高规格实例，以承载数据处理负载。
* 减小批次大小：调整 Dataflow 作业配置中的批次大小，向 ClickHouse 发送更小的数据块，从而降低每个批次的内存消耗。这些更改有助于在数据摄取期间平衡资源使用。

<div id="template-source-code">
  ## Template 源代码
</div>

该 Template 的源代码可在以下位置查看：

* [`GoogleCloudPlatform/DataflowTemplates`](https://github.com/GoogleCloudPlatform/DataflowTemplates/tree/main/v2/googlecloud-to-clickhouse) — Google Cloud Platform 的上游代码仓库。
* [`ClickHouse/DataflowTemplates`](https://github.com/ClickHouse/DataflowTemplates) — ClickHouse 的 fork。
