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

> 命名集合相关文档

# 命名集合

export const CloudNotSupportedBadge = () => {
  return <div className="cloudNotSupportedBadge">
            <div className="cloudNotSupportedIcon">
            <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path strokeWidth="1.5" d="M6.33366 12.6666L12.3739 12.6667C13.6593 12.6667 14.7073 11.6187 14.7073 10.3334C14.7073 9.04804 13.6593 8.00003 12.3739 8.00003C12.3739 8.00003 12.3337 7.66659 12.0003 7.33325M10.667 5.33322C8.00033 2.33325 4.45395 4.78537 4.14195 6.68203C2.55728 6.7627 1.29395 8.06203 1.29395 9.6667C1.29395 11.3234 2.66699 12.6666 4.00033 12.6666" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" />
                <path strokeWidth="1.5" d="M2.66699 14L12.0003 4.66663" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" />
            </svg>

        </div>
            ClickHouse Cloud 不支持此功能
        </div>;
};

<CloudNotSupportedBadge />

命名集合提供了一种存储键值对集合的方式，
可用于配置与外部源的集成。您可以将命名集合用于
字典、表、表函数和对象存储。

命名集合可以通过 DDL 或在配置文件中进行配置，并在
ClickHouse 启动时生效。它们可以简化对象的创建，并向
没有管理权限的用户隐藏凭据。

命名集合中的键必须与相应
函数、表引擎、database 等的参数名称匹配。下面的示例中，
每种类型都链接到了对应的参数列表。

在命名集合中设置的参数可以在 SQL 中被覆盖，下面的示例
展示了这一点。可以使用 `[NOT] OVERRIDABLE` 关键字、XML 属性
和/或配置选项 `allow_named_collection_override_by_default` 来限制这种能力。

<Warning>
  如果允许覆盖，可能会让没有管理权限的用户
  推断出您试图隐藏的凭据。
  如果您出于这个目的使用命名集合，应禁用
  `allow_named_collection_override_by_default` (默认启用) 。
</Warning>

<div id="storing-named-collections-in-the-system-database">
  ## 将命名集合存储在 system 数据库中
</div>

<div id="ddl-example">
  ### DDL 示例
</div>

```sql theme={null}
CREATE NAMED COLLECTION name AS
key_1 = 'value' OVERRIDABLE,
key_2 = 'value2' NOT OVERRIDABLE,
url = 'https://connection.url/'
```

在上述示例中：

* `key_1` 始终可以被覆盖。
* `key_2` 永远不能被覆盖。
* `url` 是否可以被覆盖，取决于 `allow_named_collection_override_by_default` 的值。

<div id="permissions-to-create-named-collections-with-ddl">
  ### 使用 DDL 创建 命名集合 的权限要求
</div>

要通过 DDL 管理 命名集合，用户必须具有 `named_collection_control` 特权。可通过在 `/etc/clickhouse-server/users.d/` 中添加文件来授予该权限。以下示例为用户 `default` 同时授予 `access_management` 和 `named_collection_control` 特权：

```xml title='/etc/clickhouse-server/users.d/user_default.xml' highlight={6} theme={null}
<clickhouse>
  <users>
    <default>
      <password_sha256_hex>65e84be33532fb784c48129675f9eff3a682b27168c0ea744b2cf58ee02337c5</password_sha256_hex replace=true>
      <access_management>1</access_management>
      <named_collection_control>1</named_collection_control>
    </default>
  </users>
</clickhouse>
```

<Tip>
  在上述示例中，`password_sha256_hex` 的值是密码的 SHA256 哈希的十六进制表示。用户 `default` 的这项配置带有 `replace=true` 属性，因为默认配置中已经设置了明文 `password`，而同一用户不能同时设置明文密码和 sha256 十六进制密码。
</Tip>

<div id="storage-for-named-collections">
  ### 命名集合的存储
</div>

命名集合既可以存储在本地 disk 上，也可以存储在 ZooKeeper/Keeper 中。默认使用本地存储。
它们也可以采用加密存储，并使用与[磁盘加密](/docs/zh/concepts/features/configuration/server-config/storing-data#encrypted-virtual-file-system)相同的算法，
其中默认使用 `aes_128_ctr`。

要配置命名集合存储，需要指定一个 `type`。它可以是 `local` 或 `keeper`/`zookeeper`。对于加密存储，
可以使用 `local_encrypted` 或 `keeper_encrypted`/`zookeeper_encrypted`。

要使用 ZooKeeper/Keeper，还需要在配置文件的 `named_collections_storage` 部分中设置一个 `path` (即 ZooKeeper/Keeper 中存储命名集合的路径) 。
下面的示例使用了加密和 ZooKeeper/Keeper：

```xml theme={null}
<clickhouse>
  <named_collections_storage>
    <type>zookeeper_encrypted</type>
    <key_hex>bebec0cabebec0cabebec0cabebec0ca</key_hex>
    <algorithm>aes_128_ctr</algorithm>
    <path>/named_collections_path/</path>
    <update_timeout_ms>1000</update_timeout_ms>
  </named_collections_storage>
</clickhouse>
```

可选配置参数 `update_timeout_ms` 的默认值为 `5000`。

<div id="storing-named-collections-in-configuration-files">
  ## 在配置文件中存储命名集合
</div>

<div id="xml-example">
  ### XML 示例
</div>

```xml title='/etc/clickhouse-server/config.d/named_collections.xml' theme={null}
<clickhouse>
     <named_collections>
        <name>
            <key_1 overridable="true">value</key_1>
            <key_2 overridable="false">value_2</key_2>
            <url>https://connection.url/</url>
        </name>
     </named_collections>
</clickhouse>
```

在上述示例中：

* `key_1` 始终可以被覆盖。
* `key_2` 绝不会被覆盖。
* `url` 是否可以被覆盖，取决于 `allow_named_collection_override_by_default` 的值。

<div id="modifying-named-collections">
  ## 修改命名集合
</div>

通过 DDL 查询创建的命名集合，可以使用 DDL 进行修改或删除。通过 XML 文件创建的命名集合，则可以通过编辑或删除相应的 XML 文件来管理。

<div id="alter-a-ddl-named-collection">
  ### 修改 DDL 命名集合
</div>

修改或添加集合 `collection2` 中的键 `key1` 和 `key3`
(这不会更改这些键的 `overridable` 标志值) ：

```sql theme={null}
ALTER NAMED COLLECTION collection2 SET key1=4, key3='value3'
```

更改或添加键 `key1`，并允许始终覆盖它：

```sql theme={null}
ALTER NAMED COLLECTION collection2 SET key1=4 OVERRIDABLE
```

从 `collection2` 中删除键 `key2`：

```sql theme={null}
ALTER NAMED COLLECTION collection2 DELETE key2
```

修改或新增集合 `collection2` 的键 `key1`，并删除键 `key3`：

```sql theme={null}
ALTER NAMED COLLECTION collection2 SET key1=4, DELETE key3
```

要强制某个键在 `overridable` 标志上使用默认设置，你必须
先删除该键，然后重新添加。

```sql theme={null}
ALTER NAMED COLLECTION collection2 DELETE key1;
ALTER NAMED COLLECTION collection2 SET key1=4;
```

<div id="drop-the-ddl-named-collection-collection2">
  ### 删除名为 `collection2` 的 DDL 命名集合：
</div>

```sql theme={null}
DROP NAMED COLLECTION collection2
```

<div id="named-collections-for-accessing-s3">
  ## 用于访问 S3 的命名集合
</div>

参数说明请参见 [S3 表函数](/docs/zh/reference/functions/table-functions/s3)。

<div id="ddl-example">
  ### DDL 示例
</div>

```sql theme={null}
CREATE NAMED COLLECTION s3_mydata AS
access_key_id = 'AKIAIOSFODNN7EXAMPLE',
secret_access_key = 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY',
format = 'CSV',
url = 'https://s3.us-east-1.amazonaws.com/yourbucket/mydata/'
```

<div id="xml-example">
  ### XML 示例
</div>

```xml theme={null}
<clickhouse>
    <named_collections>
        <s3_mydata>
            <access_key_id>AKIAIOSFODNN7EXAMPLE</access_key_id>
            <secret_access_key>wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY</secret_access_key>
            <format>CSV</format>
            <url>https://s3.us-east-1.amazonaws.com/yourbucket/mydata/</url>
        </s3_mydata>
    </named_collections>
</clickhouse>
```

<div id="s3-function-and-s3-table-named-collection-examples">
  ### s3() 函数和 S3 表的命名集合示例
</div>

以下两个示例都使用相同的命名集合 `s3_mydata`：

<div id="s3-function">
  #### s3() 函数
</div>

```sql theme={null}
INSERT INTO FUNCTION s3(s3_mydata, filename = 'test_file.tsv.gz',
   format = 'TSV', structure = 'number UInt64', compression_method = 'gzip')
SELECT * FROM numbers(10000);
```

<Tip>
  上述 `s3()` 函数的第一个参数是集合名称，即 `s3_mydata`。如果不使用命名集合，那么每次调用 `s3()` 函数时，都需要传入访问密钥 ID、密钥、格式和 URL。
</Tip>

<div id="s3-table">
  #### S3 表
</div>

```sql theme={null}
CREATE TABLE s3_engine_table (number Int64)
ENGINE=S3(s3_mydata, url='https://s3.us-east-1.amazonaws.com/yourbucket/mydata/test_file.tsv.gz', format = 'TSV')
SETTINGS input_format_with_names_use_header = 0;

SELECT * FROM s3_engine_table LIMIT 3;
┌─number─┐
│      0 │
│      1 │
│      2 │
└────────┘
```

<div id="named-collections-for-accessing-mysql-database">
  ## 用于访问 MySQL 数据库的命名集合
</div>

参数说明请参见 [mysql](/docs/zh/reference/functions/table-functions/mysql)。

<div id="ddl-example">
  ### DDL 示例
</div>

```sql theme={null}
CREATE NAMED COLLECTION mymysql AS
user = 'myuser',
password = 'mypass',
host = '127.0.0.1',
port = 3306,
database = 'test',
connection_pool_size = 8,
replace_query = 1
```

<div id="xml-example">
  ### XML 示例
</div>

```xml theme={null}
<clickhouse>
    <named_collections>
        <mymysql>
            <user>myuser</user>
            <password>mypass</password>
            <host>127.0.0.1</host>
            <port>3306</port>
            <database>test</database>
            <connection_pool_size>8</connection_pool_size>
            <replace_query>1</replace_query>
        </mymysql>
    </named_collections>
</clickhouse>
```

<div id="mysql-function-mysql-table-mysql-database-and-dictionary-named-collection-examples">
  ### `mysql()` 函数、MySQL 表、MySQL 数据库和字典的命名集合示例
</div>

以下四个示例使用的是同一个命名集合 `mymysql`：

<div id="mysql-function">
  #### mysql() 函数
</div>

```sql theme={null}
SELECT count() FROM mysql(mymysql, table = 'test');

┌─count()─┐
│       3 │
└─────────┘
```

<Note>
  该 命名集合 未指定 `table` 参数，因此需在函数调用中指定 `table = 'test'`。
</Note>

<div id="mysql-table">
  #### MySQL 表
</div>

```sql theme={null}
CREATE TABLE mytable(A Int64) ENGINE = MySQL(mymysql, table = 'test', connection_pool_size=3, replace_query=0);
SELECT count() FROM mytable;

┌─count()─┐
│       3 │
└─────────┘
```

<Note>
  DDL 会覆盖命名集合中的 connection\_pool\_size 设置。
</Note>

<div id="mysql-database">
  #### MySQL 数据库
</div>

```sql theme={null}
CREATE DATABASE mydatabase ENGINE = MySQL(mymysql);

SHOW TABLES FROM mydatabase;

┌─name───┐
│ source │
│ test   │
└────────┘
```

<div id="mysql-dictionary">
  #### MySQL 字典
</div>

```sql theme={null}
CREATE DICTIONARY dict (A Int64, B String)
PRIMARY KEY A
SOURCE(MYSQL(NAME mymysql TABLE 'source'))
LIFETIME(MIN 1 MAX 2)
LAYOUT(HASHED());

SELECT dictGet('dict', 'B', 2);

┌─dictGet('dict', 'B', 2)─┐
│ two                     │
└─────────────────────────┘
```

<div id="named-collections-for-accessing-postgresql-database">
  ## 用于访问 PostgreSQL 数据库的命名集合
</div>

参数说明请参见 [postgresql](/docs/zh/reference/functions/table-functions/postgresql)。此外，还有以下别名：

* `username` 是 `user` 的别名
* `db` 是 `database` 的别名。

[PostgreSQL table engine](/docs/zh/reference/engines/table-engines/integrations/postgresql) 的连接池设置 (`postgresql_connection_pool_size` 以及其他 `postgresql_*` 设置) 也可以存储在集合中，或以 `key = value` overrides 的形式传递。它们适用于 `PostgreSQL` 表引擎、`postgresql` 表函数以及 `PostgreSQL` 数据库引擎；表上的显式 `SETTINGS` clause 的优先次序高于集合中的配置值。

在集合中，参数 `addresses_expr` 用于替代 `host:port`。该参数是可选的，因为还可以使用其他可选参数：`host`、`hostname`、`port`。以下伪代码说明了优先级：

```sql theme={null}
CASE
    WHEN collection['addresses_expr'] != '' THEN collection['addresses_expr']
    WHEN collection['host'] != ''           THEN collection['host'] || ':' || if(collection['port'] != '', collection['port'], '5432')
    WHEN collection['hostname'] != ''       THEN collection['hostname'] || ':' || if(collection['port'] != '', collection['port'], '5432')
END
```

创建示例：

```sql theme={null}
CREATE NAMED COLLECTION mypg AS
user = 'pguser',
password = 'jw8s0F4',
host = '127.0.0.1',
port = 5432,
database = 'test',
schema = 'test_schema'
```

配置示例：

```xml theme={null}
<clickhouse>
    <named_collections>
        <mypg>
            <user>pguser</user>
            <password>jw8s0F4</password>
            <host>127.0.0.1</host>
            <port>5432</port>
            <database>test</database>
            <schema>test_schema</schema>
        </mypg>
    </named_collections>
</clickhouse>
```

<div id="example-of-using-named-collections-with-the-postgresql-function">
  ### 使用命名集合的 postgresql 函数示例
</div>

```sql theme={null}
SELECT * FROM postgresql(mypg, table = 'test');

┌─a─┬─b───┐
│ 2 │ two │
│ 1 │ one │
└───┴─────┘
SELECT * FROM postgresql(mypg, table = 'test', schema = 'public');

┌─a─┐
│ 1 │
│ 2 │
│ 3 │
└───┘
```

<div id="example-of-using-named-collections-with-database-with-engine-postgresql">
  ### 在 PostgreSQL 引擎数据库中使用命名集合的示例
</div>

```sql theme={null}
CREATE TABLE mypgtable (a Int64) ENGINE = PostgreSQL(mypg, table = 'test', schema = 'public');

SELECT * FROM mypgtable;

┌─a─┐
│ 1 │
│ 2 │
│ 3 │
└───┘
```

<Note>
  PostgreSQL 会在创建表时从命名集合中复制数据。此后，即使命名集合发生变化，也不会影响现有表。
</Note>

<div id="example-of-using-named-collections-with-database-with-engine-postgresql-1">
  ### 将命名集合用于 PostgreSQL 引擎数据库的示例
</div>

```sql theme={null}
CREATE DATABASE mydatabase ENGINE = PostgreSQL(mypg);

SHOW TABLES FROM mydatabase

┌─name─┐
│ test │
└──────┘
```

<div id="example-of-using-named-collections-with-a-dictionary-with-source-postgresql">
  ### 在源为 POSTGRESQL 的字典中使用命名集合的示例
</div>

```sql theme={null}
CREATE DICTIONARY dict (a Int64, b String)
PRIMARY KEY a
SOURCE(POSTGRESQL(NAME mypg TABLE test))
LIFETIME(MIN 1 MAX 2)
LAYOUT(HASHED());

SELECT dictGet('dict', 'b', 2);

┌─dictGet('dict', 'b', 2)─┐
│ two                     │
└─────────────────────────┘
```

<div id="named-collections-for-accessing-a-remote-clickhouse-database">
  ## 用于访问远程 ClickHouse 数据库的命名集合
</div>

参数说明见 [remote](/docs/zh/reference/functions/table-functions/remote#parameters)。

配置示例：

```sql theme={null}
CREATE NAMED COLLECTION remote1 AS
host = 'remote_host',
port = 9000,
database = 'system',
user = 'foo',
password = 'secret',
secure = 1
```

```xml theme={null}
<clickhouse>
    <named_collections>
        <remote1>
            <host>remote_host</host>
            <port>9000</port>
            <database>system</database>
            <user>foo</user>
            <password>secret</password>
            <secure>1</secure>
        </remote1>
    </named_collections>
</clickhouse>
```

由于使用的是 `remoteSecure`，因此连接无需 `secure`，但它可用于字典。

<div id="example-of-using-named-collections-with-the-remoteremotesecure-functions">
  ### 结合命名集合使用 `remote`/`remoteSecure` 函数的示例
</div>

```sql theme={null}
SELECT * FROM remote(remote1, table = one);
┌─dummy─┐
│     0 │
└───────┘

SELECT * FROM remote(remote1, database = merge(system, '^one'));
┌─dummy─┐
│     0 │
└───────┘

INSERT INTO FUNCTION remote(remote1, database = default, table = test) VALUES (1,'a');

SELECT * FROM remote(remote1, database = default, table = test);
┌─a─┬─b─┐
│ 1 │ a │
└───┴───┘
```

<div id="example-of-using-named-collections-with-a-dictionary-with-source-clickhouse">
  ### 使用源为 ClickHouse 的字典和命名集合的示例
</div>

```sql theme={null}
CREATE DICTIONARY dict(a Int64, b String)
PRIMARY KEY a
SOURCE(CLICKHOUSE(NAME remote1 TABLE test DB default))
LIFETIME(MIN 1 MAX 2)
LAYOUT(HASHED());

SELECT dictGet('dict', 'b', 1);
┌─dictGet('dict', 'b', 1)─┐
│ a                       │
└─────────────────────────┘
```

<div id="named-collections-for-accessing-kafka">
  ## 用于访问 Kafka 的命名集合
</div>

有关参数的说明，请参见 [Kafka](/docs/zh/reference/engines/table-engines/integrations/kafka)。

<div id="ddl-example">
  ### DDL 示例
</div>

```sql theme={null}
CREATE NAMED COLLECTION my_kafka_cluster AS
kafka_broker_list = 'localhost:9092',
kafka_topic_list = 'kafka_topic',
kafka_group_name = 'consumer_group',
kafka_format = 'JSONEachRow',
kafka_max_block_size = '1048576';

```

<div id="xml-example">
  ### XML 示例
</div>

```xml theme={null}
<clickhouse>
    <named_collections>
        <my_kafka_cluster>
            <kafka_broker_list>localhost:9092</kafka_broker_list>
            <kafka_topic_list>kafka_topic</kafka_topic_list>
            <kafka_group_name>consumer_group</kafka_group_name>
            <kafka_format>JSONEachRow</kafka_format>
            <kafka_max_block_size>1048576</kafka_max_block_size>
        </my_kafka_cluster>
    </named_collections>
</clickhouse>
```

<div id="example-of-using-named-collections-with-a-kafka-table">
  ### 使用命名集合的 Kafka 表示例
</div>

以下两个示例都使用同一个命名集合 `my_kafka_cluster`：

```sql theme={null}
CREATE TABLE queue
(
    timestamp UInt64,
    level String,
    message String
)
ENGINE = Kafka(my_kafka_cluster)

CREATE TABLE queue
(
    timestamp UInt64,
    level String,
    message String
)
ENGINE = Kafka(my_kafka_cluster)
SETTINGS kafka_num_consumers = 4,
         kafka_thread_per_consumer = 1;
```

<div id="named-collections-for-backups">
  ## 用于备份的命名集合
</div>

有关参数的说明，请参见 [备份与恢复](/docs/zh/concepts/features/backup-restore/overview)。

<div id="ddl-example">
  ### DDL 示例
</div>

```sql theme={null}
BACKUP TABLE default.test to S3(named_collection_s3_backups, 'directory')
```

<div id="xml-example">
  ### XML 示例
</div>

```xml theme={null}
<clickhouse>
    <named_collections>
        <named_collection_s3_backups>
            <url>https://my-s3-bucket.s3.amazonaws.com/backup-S3/</url>
            <access_key_id>ABC123</access_key_id>
            <secret_access_key>Abc+123</secret_access_key>
        </named_collection_s3_backups>
    </named_collections>
</clickhouse>
```

<div id="named-collections-for-accessing-mongodb-table-and-dictionary">
  ## 用于访问 MongoDB 表和字典的命名集合
</div>

有关参数的说明，请参阅 [mongodb](/docs/zh/reference/functions/table-functions/mongodb)。

<div id="ddl-example">
  ### DDL 示例
</div>

```sql theme={null}
CREATE NAMED COLLECTION mymongo AS
user = '',
password = '',
host = '127.0.0.1',
port = 27017,
database = 'test',
collection = 'my_collection',
options = 'connectTimeoutMS=10000'
```

<div id="xml-example">
  ### XML 示例
</div>

```xml theme={null}
<clickhouse>
    <named_collections>
        <mymongo>
            <user></user>
            <password></password>
            <host>127.0.0.1</host>
            <port>27017</port>
            <database>test</database>
            <collection>my_collection</collection>
            <options>connectTimeoutMS=10000</options>
        </mymongo>
    </named_collections>
</clickhouse>
```

<div id="mongodb-table">
  #### MongoDB 表
</div>

```sql theme={null}
CREATE TABLE mytable(log_type VARCHAR, host VARCHAR, command VARCHAR) ENGINE = MongoDB(mymongo, options='connectTimeoutMS=10000&compressors=zstd')
SELECT count() FROM mytable;

┌─count()─┐
│       2 │
└─────────┘
```

<Note>
  DDL 会覆盖 命名集合 中这些选项的配置。
</Note>

<div id="mongodb-dictionary">
  #### MongoDB 字典
</div>

```sql theme={null}
CREATE DICTIONARY dict
(
    `a` Int64,
    `b` String
)
PRIMARY KEY a
SOURCE(MONGODB(NAME mymongo COLLECTION my_dict))
LIFETIME(MIN 1 MAX 2)
LAYOUT(HASHED())

SELECT dictGet('dict', 'b', 2);

┌─dictGet('dict', 'b', 2)─┐
│ two                     │
└─────────────────────────┘
```

<Note>
  该命名集合将 `my_collection` 指定为集合名称。在函数调用中，可通过 `collection = 'my_dict'` 将其覆盖，以选择另一个集合。
</Note>
