ClickHouse/docs/ru/query_language/dicts/external_dicts_dict_structure.md

121 lines
4.7 KiB
Markdown
Raw Normal View History

<a name="dicts-external_dicts_dict_structure"></a>
# Ключ и поля словаря
Секция `<structure>` описывает ключ словаря и поля, доступные для запросов.
Общий вид структуры:
```xml
<dictionary>
<structure>
<id>
<name>Id</name>
</id>
<attribute>
<!-- Attribute parameters -->
</attribute>
...
</structure>
</dictionary>
```
В структуре описываются столбцы:
- `<id>` - [ключевой столбец](external_dicts_dict_structure.md#dicts-external_dicts_dict_structure-key).
- `<attribute>` - [столбец данных](external_dicts_dict_structure.md#dicts-external_dicts_dict_structure-attributes). Столбцов может быть много.
<a name="dicts-external_dicts_dict_structure-key"></a>
## Ключ
ClickHouse поддерживает следующие виды ключей:
- Числовой ключ. Формат UInt64. Описывается в теге `<id>`.
- Составной ключ. Набор значений разного типа. Описывается в теге `<key>`.
Структура может содержать либо `<id>` либо `<key>`.
WIP on documentation (#2692) * Additional .gitignore entries * Merge a bunch of small articles about system tables into single one * Merge a bunch of small articles about formats into single one * Adapt table with formats to English docs too * Add SPb meetup link to main page * Move Utilities out of top level of docs (the location is probably not yet final) + translate couple articles * Merge MacOS.md into build_osx.md * Move Data types higher in ToC * Publish changelog on website alongside documentation * Few fixes for en/table_engines/file.md * Use smaller header sizes in changelogs * Group up table engines inside ToC * Move table engines out of top level too * Specificy in ToC that query language is SQL based. Thats a bit excessive, but catches eye. * Move stuff that is part of query language into respective folder * Move table functions lower in ToC * Lost redirects.txt update * Do not rely on comments in yaml + fix few ru titles * Extract major parts of queries.md into separate articles * queries.md has been supposed to be removed * Fix weird translation * Fix a bunch of links * There is only table of contents left * "Query language" is actually part of SQL abbreviation * Change filename in README.md too * fix mistype * s/formats\/interfaces/interfaces\/formats/g * Remove extra clarification from header as it was too verbose, probably making it a bit more confusing * Empty article was supposed to be hidden * At least change incorrect title * Move special links to the bottom of nav and slightly highlight them * Skip hidden pages in bottom navigation too * Make front page of documentation to be part of Introduction * Make tables in introduction somewhat readable + move abbreviation definitions earlier * Some introduction text refactoring * Some docs introduction refactoring * Use admonitions instead of divs * Additional .gitignore * Treat .gif as images too * Clarify ToC item
2018-07-20 17:35:34 +00:00
!!! attention "Обратите внимание"
Ключ не надо дополнительно описывать в атрибутах.
### Числовой ключ
Формат: `UInt64`.
Пример конфигурации:
```xml
<id>
<name>Id</name>
</id>
```
Поля конфигурации:
- name - имя столбца с ключами.
### Составной ключ
2018-10-31 12:56:30 +00:00
Ключом может быть кортеж (`tuple`) из полей произвольных типов. [layout](external_dicts_dict_layout.md#dicts-external_dicts_dict_layout) в этом случае должен быть `complex_key_hashed` или `complex_key_cache`.
WIP on documentation (#2692) * Additional .gitignore entries * Merge a bunch of small articles about system tables into single one * Merge a bunch of small articles about formats into single one * Adapt table with formats to English docs too * Add SPb meetup link to main page * Move Utilities out of top level of docs (the location is probably not yet final) + translate couple articles * Merge MacOS.md into build_osx.md * Move Data types higher in ToC * Publish changelog on website alongside documentation * Few fixes for en/table_engines/file.md * Use smaller header sizes in changelogs * Group up table engines inside ToC * Move table engines out of top level too * Specificy in ToC that query language is SQL based. Thats a bit excessive, but catches eye. * Move stuff that is part of query language into respective folder * Move table functions lower in ToC * Lost redirects.txt update * Do not rely on comments in yaml + fix few ru titles * Extract major parts of queries.md into separate articles * queries.md has been supposed to be removed * Fix weird translation * Fix a bunch of links * There is only table of contents left * "Query language" is actually part of SQL abbreviation * Change filename in README.md too * fix mistype * s/formats\/interfaces/interfaces\/formats/g * Remove extra clarification from header as it was too verbose, probably making it a bit more confusing * Empty article was supposed to be hidden * At least change incorrect title * Move special links to the bottom of nav and slightly highlight them * Skip hidden pages in bottom navigation too * Make front page of documentation to be part of Introduction * Make tables in introduction somewhat readable + move abbreviation definitions earlier * Some introduction text refactoring * Some docs introduction refactoring * Use admonitions instead of divs * Additional .gitignore * Treat .gif as images too * Clarify ToC item
2018-07-20 17:35:34 +00:00
!!! tip "Совет"
Cоставной ключ может состоять из одного элемента. Это даёт возможность использовать в качестве ключа, например, строку.
Структура ключа задаётся в элементе `<key>`. Поля ключа задаются в том же формате, что и [атрибуты](external_dicts_dict_structure.md#dicts-external_dicts_dict_structure-attributes) словаря. Пример:
```xml
<structure>
<key>
<attribute>
<name>field1</name>
<type>String</type>
</attribute>
<attribute>
<name>field2</name>
<type>UInt32</type>
</attribute>
...
</key>
...
```
При запросе в функции `dictGet*` в качестве ключа передаётся кортеж. Пример: `dictGetString('dict_name', 'attr_name', tuple('string for field1', num_for_field2))`.
<a name="dicts-external_dicts_dict_structure-attributes"></a>
## Атрибуты
Пример конфигурации:
```xml
<structure>
...
<attribute>
<name>Name</name>
<type>Type</type>
<null_value></null_value>
<expression>rand64()</expression>
<hierarchical>true</hierarchical>
<injective>true</injective>
<is_object_id>true</is_object_id>
</attribute>
</structure>
```
Поля конфигурации:
- `name` - Имя столбца.
- `type` - Тип столбца. Задает способ интерпретации данных в источнике. Например, в случае MySQL, в таблице-источнике поле может быть `TEXT`, `VARCHAR`, `BLOB`, но загружено может быть как `String`.
- `null_value` - Значение по умолчанию для несуществующего элемента. В примере - пустая строка.
- `expression` - Атрибут может быть выражением. Тег не обязательный.
- `hierarchical` - Поддержка иерархии. Отображение в идентификатор родителя. По умолчанию, `false`.
- `injective` - Признак инъективности отображения `id -> attribute`. Если `true`, то можно оптимизировать `GROUP BY`. По умолчанию, `false`.
- `is_object_id` - Признак того, что запрос выполняется к документу MongoDB по `ObjectID`.
[Оригинальная статья](https://clickhouse.yandex/docs/ru/query_language/dicts/external_dicts_dict_structure/) <!--hide-->