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

> Grafana 中 ClickHouse 数据源插件的配置选项

# 在 Grafana 中配置 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>;
};

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>;
};

<ClickHouseSupportedBadge />

修改配置最简单的方式，是在 Grafana UI 的插件配置页面中进行，但也可以[通过 YAML 文件预配数据源](https://grafana.com/docs/grafana/latest/administration/provisioning/#data-sources)。

本页列出了 ClickHouse 插件中可配置的各项选项，以及通过 YAML 预配数据源时可用的配置片段。

如需快速了解所有选项，请在[此处](#all-yaml-options)查看完整的配置选项列表。

<div id="common-settings">
  ## 通用设置
</div>

示例配置界面：

<Image size="sm" img="https://mintcdn.com/private-7c7dfe99/PWQnWTwcu17exYX2/images/integrations/data-visualization/grafana/config_common.webp?fit=max&auto=format&n=PWQnWTwcu17exYX2&q=85&s=ef8007c65279bb9df23fb52a0c6361d7" alt="安全原生配置示例" border width="601" height="813" data-path="images/integrations/data-visualization/grafana/config_common.webp" />

通用设置的 YAML 配置示例：

```yaml theme={null}
jsonData:
  host: 127.0.0.1 # (required) server address.
  port: 9000      # (required) server port. For native, defaults to 9440 secure and 9000 insecure. For HTTP, defaults to 8443 secure and 8123 insecure.

  protocol: native # (required) the protocol used for the connection. Can be set to "native" or "http".
  secure: false    # set to true if the connection is secure.

  username: default # the username used for authentication.

  tlsSkipVerify:     <boolean> # skips TLS verification when set to true.
  tlsAuth:           <boolean> # set to true to enable TLS client authentication.
  tlsAuthWithCACert: <boolean> # set to true if CA certificate is provided. Required for verifying self-signed TLS certificates.

secureJsonData:
  password: secureExamplePassword # the password used for authentication.

  tlsCACert:     <string> # TLS CA certificate
  tlsClientCert: <string> # TLS client certificate
  tlsClientKey:  <string> # TLS client key
```

请注意，从 UI 保存配置时，系统会自动添加一个 `version` 属性。该属性显示保存此配置时所使用的插件版本。

<div id="http-protocol">
  ### HTTP 协议
</div>

如果选择通过 HTTP 协议连接，则会显示更多设置选项。

<Image size="md" img="https://mintcdn.com/private-7c7dfe99/PWQnWTwcu17exYX2/images/integrations/data-visualization/grafana/config_http.webp?fit=max&auto=format&n=PWQnWTwcu17exYX2&q=85&s=173a06bd7c26a19b181299cbf4e60f59" alt="额外的 HTTP 配置选项" border width="975" height="442" data-path="images/integrations/data-visualization/grafana/config_http.webp" />

<div id="http-path">
  #### HTTP 路径
</div>

如果 HTTP 服务器通过其他 URL 路径对外提供服务，可以在此处添加。

```yaml theme={null}
jsonData:
  # 不包含开头的斜杠
  path: additional/path/example
```

<div id="custom-http-headers">
  #### 自定义 HTTP 请求头
</div>

你可以为发送到服务器的请求添加自定义请求头。

请求头可以是明文，也可以是安全值。
所有请求头键都会以明文形式存储，而安全请求头值会保存在安全配置中 (类似于 `password` 字段) 。

<Warning>
  **通过 HTTP 发送安全值**

  虽然安全请求头值会安全地存储在配置中，但如果未启用安全连接，该值仍会通过 HTTP 发送。
</Warning>

明文/安全请求头的 YAML 示例：

```yaml theme={null}
jsonData:
  httpHeaders:
  - name: X-Example-Plain-Header
    value: plain text value
    secure: false
  - name: X-Example-Secure-Header
    # 不包含 "value"
    secure: true
secureJsonData:
  secureHttpHeaders.X-Example-Secure-Header: secure header value
```

<div id="additional-settings">
  ## 其他设置
</div>

这些附加设置为可选项。

<Image size="sm" img="https://mintcdn.com/private-7c7dfe99/PWQnWTwcu17exYX2/images/integrations/data-visualization/grafana/config_additional.webp?fit=max&auto=format&n=PWQnWTwcu17exYX2&q=85&s=335542c340901788318c16cd8625b5c3" alt="附加设置示例" border width="406" height="452" data-path="images/integrations/data-visualization/grafana/config_additional.webp" />

示例 YAML：

```yaml theme={null}
jsonData:
  defaultDatabase: default # default database loaded by the query builder. Defaults to "default".
  defaultTable: <string>   # default table loaded by the query builder.

  dialTimeout: 10    # dial timeout when connecting to the server, in seconds. Defaults to "10".
  queryTimeout: 60   # query timeout when running a query, in seconds. Defaults to 60. This requires permissions on the user, if you get a permission error try setting it to "0" to disable it.
  validateSql: false # when set to true, will validate the SQL in the SQL editor.
```

<div id="opentelemetry">
  ### OpenTelemetry
</div>

OpenTelemetry (OTel) 已深度集成到此插件中。
OpenTelemetry 数据可通过我们的 [exporter 插件](https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/exporter/clickhouseexporter) 导出到 ClickHouse。
为获得最佳效果，建议同时为 [日志](#logs) 和 [链路追踪](#traces) 配置 OTel。

此外，还必须配置这些默认值，以启用 [数据链接](/docs/zh/integrations/connectors/data-visualization/grafana/query-builder#data-links)；这项功能可支持强大的可观测性工作流。

<div id="logs">
  ### 日志
</div>

为加快[日志查询构建](/docs/zh/integrations/connectors/data-visualization/grafana/query-builder#logs)速度，您可以为日志查询设置默认数据库/表以及列。这样会在 query builder 中预加载一个可直接运行的日志查询，从而加快在 Explore 页面中的可观测性浏览。

如果您使用 OpenTelemetry，应该启用“**Use OTel**”开关，并将 **default log table** 设置为 `otel_logs`。
这会自动覆盖默认列，以使用所选的 OTel schema 版本。

虽然日志并不要求必须使用 OpenTelemetry，但使用统一的日志/trace 数据集有助于借助[数据链接](/docs/zh/integrations/connectors/data-visualization/grafana/query-builder#data-links)实现更流畅的可观测性工作流。

日志配置界面示例：

<Image size="sm" img="https://mintcdn.com/private-7c7dfe99/PWQnWTwcu17exYX2/images/integrations/data-visualization/grafana/config_logs.webp?fit=max&auto=format&n=PWQnWTwcu17exYX2&q=85&s=657c4d40f4f9875dc6c33ff8a538ed51" alt="日志配置" border width="460" height="402" data-path="images/integrations/data-visualization/grafana/config_logs.webp" />

日志配置 YAML 示例：

```yaml theme={null}
jsonData:
  logs:
    defaultDatabase: default # default log database.
    defaultTable: otel_logs  # default log table. If you're using OTel, this should be set to "otel_logs".

    otelEnabled: false  # set to true if OTel is enabled.
    otelVersion: latest # the otel collector schema version to be used. Versions are displayed in the UI, but "latest" will use latest available version in the plugin.

    # Default columns to be selected when opening a new log query. Will be ignored if OTel is enabled.
    timeColumn:       <string> # the primary time column for the log.
    levelColumn:   <string> # the log level/severity of the log. Values typically look like "INFO", "error", or "Debug".
    messageColumn: <string> # the log's message/content.
```

<div id="traces">
  ### 链路追踪
</div>

为加快[链路追踪查询构建](/docs/zh/integrations/connectors/data-visualization/grafana/query-builder#traces)，你可以为 trace 查询设置默认的数据库/表以及列。这样会为 query builder 预加载一条可直接运行的 trace 搜索查询，从而加快在 Explore 页面中浏览可观测性数据的速度。

如果你使用 OpenTelemetry，建议启用“**Use OTel**”开关，并将**默认 trace 表**设置为 `otel_traces`。
这样会自动覆盖默认列，以使用所选的 OTel schema 版本。
虽然并非必须使用 OpenTelemetry，但如果链路追踪采用其 schema，此功能效果最佳。

链路追踪配置界面示例：

<Image size="sm" img="https://mintcdn.com/private-7c7dfe99/PWQnWTwcu17exYX2/images/integrations/data-visualization/grafana/config_traces.webp?fit=max&auto=format&n=PWQnWTwcu17exYX2&q=85&s=08216481b97764c5ffd49b94716ea0aa" alt="链路追踪配置" border width="476" height="625" data-path="images/integrations/data-visualization/grafana/config_traces.webp" />

链路追踪配置 YAML 示例：

```yaml theme={null}
jsonData:
  traces:
    defaultDatabase: default  # default trace database.
    defaultTable: otel_traces # default trace table. If you're using OTel, this should be set to "otel_traces".

    otelEnabled: false  # set to true if OTel is enabled.
    otelVersion: latest # the otel collector schema version to be used. Versions are displayed in the UI, but "latest" will use latest available version in the plugin.

    # Default columns to be selected when opening a new trace query. Will be ignored if OTel is enabled.
    traceIdColumn:       <string>    # trace ID column.
    spanIdColumn:        <string>    # span ID column.
    operationNameColumn: <string>    # operation name column.
    parentSpanIdColumn:  <string>    # parent span ID column.
    serviceNameColumn:   <string>    # service name column.
    durationTimeColumn:  <string>    # duration time column.
    durationUnitColumn:  <time unit> # duration time unit. Can be set to "seconds", "milliseconds", "microseconds", or "nanoseconds". For OTel the default is "nanoseconds".
    startTimeColumn:     <string>    # start time column. This is the primary time column for the trace span.
    tagsColumn:          <string>    # tags column. This is expected to be a map type.
    serviceTagsColumn:   <string>    # service tags column. This is expected to be a map type.
```

<div id="column-aliases">
  ### 列别名
</div>

列别名是一种便捷方式，让你能够使用不同的名称和类型来查询数据。
借助别名，你可以将嵌套的 schema 展平，从而在 Grafana 中更轻松地进行选择。

在以下情况下，别名功能可能对你特别有用：

* 你了解自己的 schema 及其大部分嵌套属性/类型
* 你将数据存储为 Map 类型
* 你将 JSON 以字符串形式存储
* 你经常使用函数来转换所选的列

<div id="table-defined-alias-columns">
  #### 在表中定义的 ALIAS 列
</div>

ClickHouse 内置了列别名功能，并且可开箱即用地与 Grafana 配合使用。
别名列可以直接在表中定义。

```sql theme={null}
CREATE TABLE alias_example (
  TimestampNanos DateTime(9),
  TimestampDate ALIAS toDate(TimestampNanos)
)
```

在上述示例中，我们创建了一个名为 `TimestampDate` 的别名，用于将纳秒级时间戳转换为 `Date` 类型。
这些数据不会像第一列那样存储在磁盘上，而是在查询时计算得出。
表中定义的别名不会随 `SELECT *` 一起返回，但可以在服务器设置中进行配置。

如需了解更多信息，请参阅 [ALIAS](/docs/zh/reference/statements/create/table#alias) 列类型的文档。

<div id="column-alias-tables">
  #### 列别名表
</div>

默认情况下，Grafana 会根据 `DESC table` 的返回结果提供列建议。
在某些情况下，你可能希望完全覆盖 Grafana 能看到的列。
这样可以在 Grafana 选择列时隐藏你的 schema；根据表的复杂程度，这可能有助于改善用户体验。

相比在表中直接定义别名，这种方式的好处是你可以轻松更新这些别名，而无需修改表。在某些 schema 中，这类定义可能长达数千项，从而让底层表定义显得杂乱。它还可以隐藏你希望用户忽略的列。

Grafana 要求别名表具有以下列结构：

```sql theme={null}
CREATE TABLE aliases (
  `alias` String,  -- The name of the alias, as seen in the Grafana column selector
  `select` String, -- The SELECT syntax to use in the SQL generator
  `type` String    -- The type of the resulting column, so the plugin can modify the UI options to match the data type.
)
```

下面介绍如何使用别名表来复现 `ALIAS` 列的行为：

```sql theme={null}
CREATE TABLE example_table (
  TimestampNanos DateTime(9)
);

CREATE TABLE example_table_aliases (`alias` String, `select` String, `type` String);

INSERT INTO example_table_aliases (`alias`, `select`, `type`) VALUES
('TimestampNanos', 'TimestampNanos', 'DateTime(9)'), -- Preserve original column from table (optional)
('TimestampDate', 'toDate(TimestampNanos)', 'Date'); -- Add new column that converts TimestampNanos to a Date
```

然后，我们就可以将此表配置为供 Grafana 使用。请注意，这个名称可以随意指定，甚至可以在单独的数据库中定义：

<Image size="md" img="https://mintcdn.com/private-7c7dfe99/PWQnWTwcu17exYX2/images/integrations/data-visualization/grafana/alias_table_config_example.webp?fit=max&auto=format&n=PWQnWTwcu17exYX2&q=85&s=0b8151e07c947f2afba1a4f91b86086b" alt="别名表配置示例" border width="974" height="199" data-path="images/integrations/data-visualization/grafana/alias_table_config_example.webp" />

现在，Grafana 看到的将是别名表的结果，而不是 `DESC example_table` 的结果：

<Image size="md" img="https://mintcdn.com/private-7c7dfe99/PWQnWTwcu17exYX2/images/integrations/data-visualization/grafana/alias_table_select_example.webp?fit=max&auto=format&n=PWQnWTwcu17exYX2&q=85&s=e04230ca34881112baab14f67b8ec663" alt="别名表查询示例" border width="508" height="188" data-path="images/integrations/data-visualization/grafana/alias_table_select_example.webp" />

这两种别名方式都可用于执行复杂的类型转换或提取 JSON 字段。

<div id="all-yaml-options">
  ## 所有 YAML 选项
</div>

以下是该插件提供的全部 YAML 配置选项。
部分字段给出了示例值，其他字段则仅显示字段类型。

有关使用 YAML 配置数据源的更多信息，请参阅 [Grafana 文档](https://grafana.com/docs/grafana/latest/administration/provisioning/#data-sources)。

```yaml theme={null}
datasources:
  - name: Example ClickHouse
    uid: clickhouse-example
    type: grafana-clickhouse-datasource
    jsonData:
      host: 127.0.0.1
      port: 9000
      protocol: native
      secure: false
      username: default
      tlsSkipVerify: <boolean>
      tlsAuth: <boolean>
      tlsAuthWithCACert: <boolean>
      defaultDatabase: default
      defaultTable: <string>
      dialTimeout: 10
      queryTimeout: 60
      validateSql: false
      httpHeaders:
      - name: X-Example-Plain-Header
        value: plain text value
        secure: false
      - name: X-Example-Secure-Header
        secure: true
      logs:
        defaultDatabase: default
        defaultTable: otel_logs
        otelEnabled: false
        otelVersion: latest
        timeColumn: <string>
        levelColumn: <string>
        messageColumn: <string>
      traces:
        defaultDatabase: default
        defaultTable: otel_traces
        otelEnabled: false
        otelVersion: latest
        traceIdColumn: <string>
        spanIdColumn: <string>
        operationNameColumn: <string>
        parentSpanIdColumn: <string>
        serviceNameColumn: <string>
        durationTimeColumn: <string>
        durationUnitColumn: <time unit>
        startTimeColumn: <string>
        tagsColumn: <string>
        serviceTagsColumn: <string>
    secureJsonData:
      tlsCACert:     <string>
      tlsClientCert: <string>
      tlsClientKey:  <string>
      secureHttpHeaders.X-Example-Secure-Header: secure header value
```
