diff --git a/docs/en/interfaces/formats.md b/docs/en/interfaces/formats.md index 46a553089d9d82c6871bc46ffaa1d52c360e787d..c5dbbce674da1a0858492efa3d6453d75d0002e3 100644 --- a/docs/en/interfaces/formats.md +++ b/docs/en/interfaces/formats.md @@ -1,9 +1,6 @@ # Formats for input and output data {#formats} -ClickHouse can accept and return data in various formats. A format supported -for input can be used to parse the data provided to `INSERT`s, to perform -`SELECT`s from a file-backed table such as File, URL or HDFS, or to read an -external dictionary. A format supported for output can be used to arrange the +ClickHouse can accept and return data in various formats. A format supported for input can be used to parse the data provided to `INSERT`s, to perform `SELECT`s from a file-backed table such as File, URL or HDFS, or to read an external dictionary. A format supported for output can be used to arrange the results of a `SELECT`, and to perform `INSERT`s into a file-backed table. The supported formats are: @@ -388,7 +385,7 @@ Unlike the [JSON](#json) format, there is no substitution of invalid UTF-8 seque ### Usage of Nested Structures {#jsoneachrow-nested} -If you have a table with the [Nested](../data_types/nested_data_structures/nested.md) data type columns, you can insert JSON data having the same structure. Enable this functionality with the [input_format_import_nested_json](../operations/settings/settings.md#settings-input_format_import_nested_json) setting. +If you have a table with [Nested](../data_types/nested_data_structures/nested.md) data type columns, you can insert JSON data with the same structure. Enable this feature with the [input_format_import_nested_json](../operations/settings/settings.md#settings-input_format_import_nested_json) setting. For example, consider the following table: @@ -396,13 +393,13 @@ For example, consider the following table: CREATE TABLE json_each_row_nested (n Nested (s String, i Int32) ) ENGINE = Memory ``` -As you can find in the `Nested` data type description, ClickHouse treats each component of the nested structure as a separate column, `n.s` and `n.i` for our table. So you can insert the data the following way: +As you can see in the `Nested` data type description, ClickHouse treats each component of the nested structure as a separate column (`n.s` and `n.i` for our table). You can insert data in the following way: ```sql INSERT INTO json_each_row_nested FORMAT JSONEachRow {"n.s": ["abc", "def"], "n.i": [1, 23]} ``` -To insert data as hierarchical JSON object set [input_format_import_nested_json=1](../operations/settings/settings.md#settings-input_format_import_nested_json). +To insert data as a hierarchical JSON object, set [input_format_import_nested_json=1](../operations/settings/settings.md#settings-input_format_import_nested_json). ```json { @@ -413,7 +410,7 @@ To insert data as hierarchical JSON object set [input_format_import_nested_json= } ``` -Without this setting ClickHouse throws the exception. +Without this setting, ClickHouse throws an exception. ```sql SELECT name, value FROM system.settings WHERE name = 'input_format_import_nested_json' diff --git a/docs/en/operations/settings/settings.md b/docs/en/operations/settings/settings.md index 9ff1971ab88ceef7c0537c2fc145a95a06480f99..9e298583b380b9f245072252088a3c8dd1466cb8 100644 --- a/docs/en/operations/settings/settings.md +++ b/docs/en/operations/settings/settings.md @@ -238,7 +238,7 @@ Default value: 0. ## input_format_import_nested_json {#settings-input_format_import_nested_json} -Enables or disables inserting of JSON data with nested objects. +Enables or disables the insertion of JSON data with nested objects. Supported formats: @@ -275,7 +275,7 @@ Default value: 1. ## date_time_input_format {#settings-date_time_input_format} -Enables or disables extended parsing of date and time formatted strings. +Allows to choose a parser of text representation of date and time. The setting doesn't apply to [date and time functions](../../query_language/functions/date_time_functions.md). @@ -283,11 +283,13 @@ Possible values: - `'best_effort'` — Enables extended parsing. - ClickHouse can parse the basic format `YYYY-MM-DD HH:MM:SS` and all the [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time formats. For example, `'2018-06-08T01:02:03.000Z'`. + ClickHouse can parse the basic `YYYY-MM-DD HH:MM:SS` format and all [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time formats. For example, `'2018-06-08T01:02:03.000Z'`. - `'basic'` — Use basic parser. - ClickHouse can parse only the basic format. + ClickHouse can parse only the basic `YYYY-MM-DD HH:MM:SS` format. For example, `'2019-08-20 10:18:56'`. + +Default value: `'basic'`. **See Also** diff --git a/docs/ru/interfaces/formats.md b/docs/ru/interfaces/formats.md index 20aa78630b73d02624ca453043205cb6559acb06..20c919665d585a43218cfd8cf2183ec52c266b7d 100644 --- a/docs/ru/interfaces/formats.md +++ b/docs/ru/interfaces/formats.md @@ -377,9 +377,68 @@ CREATE TABLE IF NOT EXISTS example_table В отличие от формата [JSON](#json), для `JSONEachRow` ClickHouse не заменяет невалидные UTF-8 последовательности. Значения экранируются так же, как и для формата `JSON`. -!!! Примечание " Примечание" +!!! note "Примечание" В строках может выводиться произвольный набор байт. Используйте формат `JSONEachRow`, если вы уверены, что данные в таблице могут быть представлены в формате JSON без потери информации. +### Использование вложенных структур {#jsoneachrow-nested} + +Если у вас есть таблица со столбцами типа [Nested](../data_types/nested_data_structures/nested.md), то в неё можно вставить данные из JSON-документа с такой же структурой. Функциональность включается настройкой [input_format_import_nested_json](../operations/settings/settings.md#settings-input_format_import_nested_json). + +Например, рассмотрим следующую таблицу: + +```sql +CREATE TABLE json_each_row_nested (n Nested (s String, i Int32) ) ENGINE = Memory +``` + +Из описания типа данных `Nested` видно, что ClickHouse трактует каждый компонент вложенной структуры как отдельный столбец (для нашей таблицы `n.s` и `n.i`). Можно вставить данные следующим образом: + +```sql +INSERT INTO json_each_row_nested FORMAT JSONEachRow {"n.s": ["abc", "def"], "n.i": [1, 23]} +``` + +Чтобы вставить данные как иерархический объект JSON, установите [input_format_import_nested_json=1](../operations/settings/settings.md#settings-input_format_import_nested_json). + +```json +{ + "n": { + "s": ["abc", "def"], + "i": [1, 23] + } +} +``` + +Без этой настройки ClickHouse сгенерирует исключение. + +```sql +SELECT name, value FROM system.settings WHERE name = 'input_format_import_nested_json' +``` + +```text +┌─name────────────────────────────┬─value─┐ +│ input_format_import_nested_json │ 0 │ +└─────────────────────────────────┴───────┘ +``` + +```sql +INSERT INTO json_each_row_nested FORMAT JSONEachRow {"n": {"s": ["abc", "def"], "i": [1, 23]}} +``` + +```text +Code: 117. DB::Exception: Unknown field found while parsing JSONEachRow format: n: (at row 1) +``` + +```sql +SET input_format_import_nested_json=1 +INSERT INTO json_each_row_nested FORMAT JSONEachRow {"n": {"s": ["abc", "def"], "i": [1, 23]}} +SELECT * FROM json_each_row_nested +``` + +```text +┌─n.s───────────┬─n.i────┐ +│ ['abc','def'] │ [1,23] │ +└───────────────┴────────┘ +``` + ## Native {#native} Самый эффективный формат. Данные пишутся и читаются блоками в бинарном виде. Для каждого блока пишется количество строк, количество столбцов, имена и типы столбцов, а затем кусочки столбцов этого блока, один за другим. То есть, этот формат является "столбцовым" - не преобразует столбцы в строки. Именно этот формат используется в родном интерфейсе - при межсерверном взаимодействии, при использовании клиента командной строки, при работе клиентов, написанных на C++. @@ -399,7 +458,7 @@ CREATE TABLE IF NOT EXISTS example_table [NULL](../query_language/syntax.md) выводится как `ᴺᵁᴸᴸ`. -``` sql +```sql SELECT * FROM t_null ``` ``` @@ -410,7 +469,7 @@ SELECT * FROM t_null В форматах `Pretty*` строки выводятся без экранирования. Ниже приведен пример для формата [PrettyCompact](#prettycompact): -``` sql +```sql SELECT 'String with \'quotes\' and \t character' AS Escaping_test ``` @@ -425,7 +484,7 @@ SELECT 'String with \'quotes\' and \t character' AS Escaping_test Формат `Pretty` поддерживает вывод тотальных значений (при использовании WITH TOTALS) и экстремальных значений (при настройке extremes выставленной в 1). В этих случаях, после основных данных выводятся тотальные значения, и экстремальные значения, в отдельных табличках. Пример (показан для формата [PrettyCompact](#prettycompact)): -``` sql +```sql SELECT EventDate, count() AS c FROM test.hits GROUP BY EventDate WITH TOTALS ORDER BY EventDate FORMAT PrettyCompact ``` @@ -516,7 +575,7 @@ Array представлены как длина в формате varint (unsig Пример: -``` sql +```sql SELECT * FROM t_null FORMAT Vertical ``` ``` @@ -528,7 +587,7 @@ y: ᴺᵁᴸᴸ В формате `Vertical` строки выводятся без экранирования. Например: -``` sql +```sql SELECT 'string with \'quotes\' and \t with some special \n characters' AS test FORMAT Vertical ``` diff --git a/docs/ru/operations/settings/settings.md b/docs/ru/operations/settings/settings.md index c3d17ddfe354eee738073f60bb236980cda1f0bc..07c1e5ae977dbb5bfbb81f7d600fe455d9e28778 100644 --- a/docs/ru/operations/settings/settings.md +++ b/docs/ru/operations/settings/settings.md @@ -233,7 +233,26 @@ Ok. - 0 — выключена. - 1 — включена. -Значение по умолчанию: 0. +Значение по умолчанию — 0. + +## input_format_import_nested_json {#settings-input_format_import_nested_json} + +Включает или отключает вставку данных JSON с вложенными объектами. + +Поддерживаемые форматы: + +- [JSONEachRow](../../interfaces/formats.md#jsoneachrow) + +Возможные значения: + +- 0 — выключена. +- 1 — включена. + +Значение по умолчанию — 0. + +**Смотрите также** + +- [Использование вложенных структур](../../interfaces/formats.md#jsoneachrow-nested) with the `JSONEachRow` format. ## input_format_with_names_use_header {#settings-input_format_with_names_use_header} @@ -253,6 +272,29 @@ Ok. Значение по умолчанию: 1. +## date_time_input_format {#settings-date_time_input_format} + +Выбор парсера для текстового представления дат и времени при обработке входного формата. + +Настройка не применяется к [функциям для работы с датой и временем](../../query_language/functions/date_time_functions.md). + +Возможные значения: + +- `'best_effort'` — включает расширенный парсинг. + + ClickHouse может парсить базовый формат `YYYY-MM-DD HH:MM:SS` и все форматы [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601). Например, `'2018-06-08T01:02:03.000Z'`. + +- `'basic'` — используется базовый парсер. + + ClickHouse может парсить только базовый формат `YYYY-MM-DD HH:MM:SS`. Например, `'2019-08-20 10:18:56'`. + +Значение по умолчанию — `'basic'`. + +**Смотрите также** + +- [Тип данных DateTime.](../../data_types/datetime.md) +- [Функции для работы с датой и временем.](../../query_language/functions/date_time_functions.md) + ## join_default_strictness {#settings-join_default_strictness} Устанавливает строгость по умолчанию для [JOIN](../../query_language/select.md#select-join).