> ## Documentation Index
> Fetch the complete documentation index at: https://private-7c7dfe99-fix-nav-issues.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# 层级字典

> 配置带有父子键关系的层级字典。

<div id="hierarchical-dictionaries">
  ## 层级字典
</div>

ClickHouse 支持使用[数值键](/zh/reference/statements/create/dictionary/attributes#numeric-key)的层级字典。

请看下面的分层结构：

```text theme={null}
0 (Common parent)
│
├── 1 (Russia)
│   │
│   └── 2 (Moscow)
│       │
│       └── 3 (Center)
│
└── 4 (Great Britain)
    │
    └── 5 (London)
```

这种层级关系可以用下表所示的字典表来表示。

| region\_id | parent\_region | region\_name  |
| ---------- | -------------- | ------------- |
| 1          | 0              | Russia        |
| 2          | 1              | Moscow        |
| 3          | 2              | Center        |
| 4          | 0              | Great Britain |
| 5          | 4              | London        |

该表包含一个 `parent_region` 列，用于存储该元素最近父级的键。

ClickHouse 支持外部字典属性的层级特性。借助该特性，你可以按上述方式配置层级字典。

[dictGetHierarchy](/zh/reference/functions/regular-functions/ext-dict-functions#dictGetHierarchy) 函数可用于获取某个元素的父级链。

在本例中，字典结构可以如下所示：

<Tabs>
  <Tab title="DDL">
    ```sql theme={null}
    CREATE DICTIONARY regions_dict
    (
        region_id UInt64,
        parent_region UInt64 DEFAULT 0 HIERARCHICAL,
        region_name String DEFAULT ''
    )
    PRIMARY KEY region_id
    SOURCE(...)
    LAYOUT(HASHED())
    LIFETIME(3600);
    ```
  </Tab>

  <Tab title="配置文件">
    ```xml theme={null}
    <dictionary>
        <structure>
            <id>
                <name>region_id</name>
            </id>

            <attribute>
                <name>parent_region</name>
                <type>UInt64</type>
                <null_value>0</null_value>
                <hierarchical>true</hierarchical>
            </attribute>

            <attribute>
                <name>region_name</name>
                <type>String</type>
                <null_value></null_value>
            </attribute>

        </structure>
    </dictionary>
    ```
  </Tab>
</Tabs>

<br />
