Merge pull request #4514 from vitlibar/document-protobuf-format

Add documentation of Protobuf input/output format.
This commit is contained in:
Vitaly Baranov 2019-02-27 19:33:26 +03:00 committed by GitHub
commit 4ad2f3d5f6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 162 additions and 16 deletions

View File

@ -23,11 +23,12 @@ The table below lists supported formats and how they can be used in `INSERT` and
| [PrettyCompactMonoBlock](#prettycompactmonoblock) | ✗ | ✔ |
| [PrettyNoEscapes](#prettynoescapes) | ✗ | ✔ |
| [PrettySpace](#prettyspace) | ✗ | ✔ |
| [Protobuf](#protobuf) | ✔ | ✔ |
| [RowBinary](#rowbinary) | ✔ | ✔ |
| [Native](#native) | ✔ | ✔ |
| [Null](#null) | ✗ | ✔ |
| [XML](#xml) | ✗ | ✔ |
| [CapnProto](#capnproto) | ✔ | |
| [CapnProto](#capnproto) | ✔ | |
## TabSeparated {#tabseparated}
@ -575,9 +576,8 @@ Cap'n Proto is a binary message format similar to Protocol Buffers and Thrift, b
Cap'n Proto messages are strictly typed and not self-describing, meaning they need an external schema description. The schema is applied on the fly and cached for each query.
``` sql
SELECT SearchPhrase, count() AS c FROM test.hits
GROUP BY SearchPhrase FORMAT CapnProto SETTINGS schema = 'schema:Message'
```bash
cat capnproto_messages.bin | clickhouse-client --query "INSERT INTO test.hits FORMAT CapnProto SETTINGS format_schema='schema:Message'"
```
Where `schema.capnp` looks like this:
@ -589,8 +589,82 @@ struct Message {
}
```
Schema files are in the file that is located in the directory specified in [ format_schema_path](../operations/server_settings/settings.md) in the server configuration.
Deserialization is effective and usually doesn't increase the system load.
See also [Format Schema](#formatschema).
## Protobuf {#protobuf}
Protobuf - is a [Protocol Buffers](https://developers.google.com/protocol-buffers/) format.
This format requires an external format schema. The schema is cached between queries.
Usage examples:
```sql
SELECT * FROM test.table FORMAT Protobuf SETTINGS format_schema = 'schemafile:MessageType'
```
```bash
cat protobuf_messages.bin | clickhouse-client --query "INSERT INTO test.table FORMAT Protobuf SETTINGS format_schema='schemafile:MessageType'"
```
Where the file `schemafile.proto` looks like this:
```
syntax = "proto3";
message MessageType {
string name = 1;
string surname = 2;
uint32 birthDate = 3;
repeated string phoneNumbers = 4;
};
```
To find the correspondence between table columns and fields of Protocol Buffers' message type ClickHouse compares their names.
This comparison is case-insensitive and the characters `_` (underscore) and `.` (dot) are considered as equal.
If types of a column and a field of Protocol Buffers' message are different the necessary conversion is applied.
Nested messages are supported. For example, for the field `z` in the following message type
```
message MessageType {
message XType {
message YType {
int32 z;
};
repeated YType y;
};
XType x;
};
```
ClickHouse tries to find a column named `x.y.z` (or `x_y_z` or `X.y_Z` and so on).
Nested messages are suitable to input or output a [nested data structures](../data_types/nested_data_structures/nested/).
Default values defined in the protobuf schema like this
```
message MessageType {
optional int32 result_per_page = 3 [default = 10];
}
```
are not applied; the [table defaults](../query_language/create.md#create-default-values) are used instead of them.
## Format Schema {#formatschema}
The file name containing the format schema is set by the setting `format_schema`.
It's required to set this setting when it is used one of the formats `Cap'n Proto` and `Protobuf`.
The format schema is a combination of a file name and the name of a message type in this file, delimited by colon,
e.g. `schemafile.proto:MessageType`.
If the file has the standard extension for the format (for example, `.proto` for `Protobuf`),
it can be omitted and in this case the format schema looks like `schemafile:MessageType`.
If you input or output data via the [client](../interfaces/cli/) the file name specified in the format schema
can contain an absolute path or a path relative to the current directory on the client.
If you input or output data via the [HTTP interface](../interfaces/http/) the file name specified in the format schema
should be located in the directory specified in [format_schema_path](../operations/server_settings/settings.md)
in the server configuration.
[Original article](https://clickhouse.yandex/docs/en/interfaces/formats/) <!--hide-->

View File

@ -45,7 +45,7 @@ In all cases, if `IF NOT EXISTS` is specified, the query won't return an error i
There can be other clauses after the `ENGINE` clause in the query. See detailed documentation on how to create tables in the descriptions of [table engines](../operations/table_engines/index.md#table_engines).
### Default Values
### Default Values {#create-default-values}
The column description can specify an expression for a default value, in one of the following ways:`DEFAULT expr`, `MATERIALIZED expr`, `ALIAS expr`.
Example: `URLDomain String DEFAULT domain(URL)`.

View File

@ -24,11 +24,12 @@ ClickHouse может принимать (`INSERT`) и отдавать (`SELECT
[PrettyCompactMonoBlock](#prettycompactmonoblock) | ✗ | ✔ |
[PrettyNoEscapes](#prettynoescapes) | ✗ | ✔ |
[PrettySpace](#prettyspace) | ✗ | ✔ |
[Protobuf](#protobuf) | ✔ | ✔ |
[RowBinary](#rowbinary) | ✔ | ✔ |
[Native](#native) | ✔ | ✔ |
[Null](#null) | ✗ | ✔ |
[XML](#xml) | ✗ | ✔ |
[CapnProto](#capnproto) | ✔ | |
[CapnProto](#capnproto) | ✔ | |
## TabSeparated {#tabseparated}
@ -565,11 +566,10 @@ test: string with \'quotes\' and \t with some special \n characters
Cap'n Proto - формат бинарных сообщений, похож на Protocol Buffers и Thrift, но не похож на JSON или MessagePack.
Сообщения Cap'n Proto строго типизированы и не самоописывающиеся, т.е. нуждаются во внешнем описании схемы. Схема применяется "на лету" и кешируется для каждого запроса.
Сообщения Cap'n Proto строго типизированы и не самоописывающиеся, т.е. нуждаются во внешнем описании схемы. Схема применяется "на лету" и кешируется между запросами.
``` sql
SELECT SearchPhrase, count() AS c FROM test.hits
GROUP BY SearchPhrase FORMAT CapnProto SETTINGS schema = 'schema:Message'
```bash
cat capnproto_messages.bin | clickhouse-client --query "INSERT INTO test.hits FORMAT CapnProto SETTINGS format_schema='schema:Message'"
```
Где `schema.capnp` выглядит следующим образом:
@ -581,9 +581,81 @@ struct Message {
}
```
Файлы со схемами находятся в файле, который находится в каталоге указанном в параметре [format_schema_path](../operations/server_settings/settings.md) конфигурации сервера.
Десериализация эффективна и обычно не повышает нагрузку на систему.
См. также [схема формата](#formatschema).
## Protobuf {#protobuf}
Protobuf - формат [Protocol Buffers](https://developers.google.com/protocol-buffers/).
Формат нуждается во внешнем описании схемы. Схема кэшируется между запросами.
Пример использования формата:
```sql
SELECT * FROM test.table FORMAT Protobuf SETTINGS format_schema = 'schemafile:MessageType'
```
или
```bash
cat protobuf_messages.bin | clickhouse-client --query "INSERT INTO test.table FORMAT Protobuf SETTINGS format_schema='schemafile:MessageType'"
```
Где файл `schemafile.proto` может выглядеть так:
```
syntax = "proto3";
message MessageType {
string name = 1;
string surname = 2;
uint32 birthDate = 3;
repeated string phoneNumbers = 4;
};
```
Соответствие между столбцами таблицы и полями сообщения Protocol Buffers устанавливается по имени,
при этом игнорируется регистр букв и символы `_` (подчеркивание) и `.` (точка) считаются одинаковыми.
Если типы столбцов не соответствуют точно типам полей сообщения Protocol Buffers, производится необходимая конвертация.
Вложенные сообщения поддерживаются, например, для поля `z` в таком сообщении
```
message MessageType {
message XType {
message YType {
int32 z;
};
repeated YType y;
};
XType x;
};
```
ClickHouse попытается найти столбец с именем `x.y.z` (или `x_y_z`, или `X.y_Z` и т.п.).
Вложенные сообщения удобно использовать в качестве соответствия для [вложенной структуры данных](../data_types/nested_data_structures/nested/).
Значения по умолчанию, определенные в схеме, например,
```
message MessageType {
optional int32 result_per_page = 3 [default = 10];
}
```
не применяются; вместо них используются определенные в таблице [значения по умолчанию](../query_language/create.md#create-default-values).
## Схема формата {#formatschema}
Имя файла со схемой записывается в настройке `format_schema`. При использовании форматов `Cap'n Proto` и `Protobuf` требуется указать схему.
Схема представляет собой имя файла и имя типа в этом файле, разделенные двоеточием, например `schemafile.proto:MessageType`.
Если файл имеет стандартное расширение для данного формата (например `.proto` для `Protobuf`),
то можно его не указывать и записывать схему так `schemafile:MessageType`.
Если для ввода/вывода данных используется [клиент](../interfaces/cli/), то при записи схемы можно использовать абсолютный путь или записывать путь
относительно текущей директории на клиенте.
Если для ввода/вывода данных используется [HTTP-интерфейс](../interfaces/http/), то файл со схемой должен располагаться на сервере в каталоге,
указанном в параметре [format_schema_path](../data_types/nested_data_structures/nested/) конфигурации сервера.
[Оригинальная статья](https://clickhouse.yandex/docs/ru/interfaces/formats/) <!--hide-->

View File

@ -46,7 +46,7 @@ CREATE TABLE [IF NOT EXISTS] [db.]table_name ENGINE = engine AS SELECT ...
После секции `ENGINE` в запросе могут использоваться и другие секции в зависимости от движка. Подробную документацию по созданию таблиц смотрите в описаниях [движков](../operations/table_engines/index.md#table_engines).
### Значения по умолчанию
### Значения по умолчанию {#create-default-values}
В описании столбца, может быть указано выражение для значения по умолчанию, одного из следующих видов:
`DEFAULT expr`, `MATERIALIZED expr`, `ALIAS expr`.