提交 f1cfca40 编写于 作者: B BayoNet 提交者: alexey-milovidov

Fixed russian inclusions into english version of the document.

上级 3795adcd
......@@ -107,14 +107,11 @@
16. If the block for if, for, while... expressions consists of a single statement, you don't need to use curly brackets. Place the statement on a separate line, instead. The same is true for a nested if, for, while... statement. But if the inner statement contains curly brackets or else, the external block should be written in curly brackets.
```cpp
/// Если файлы не открыты, то открываем их.
if (streams.empty())
for (const auto & name : column_names)
streams.emplace(name, std::make_unique<Stream>(
storage.files[name].data_file.path(),
storage.files[name].marks[mark_number].offset));
```
```cpp
/// Finish write.
for (auto & stream : streams)
stream.second->finalize();
```
17. There should be any spaces at the ends of lines.
......@@ -286,7 +283,7 @@
14. Do not start discussions in comments.
```
/// Зачем ты сделал эту фигню?
/// Why did you do this stuff?
```
15. There's no need to write a comment at the end of a block describing what it was about.
......@@ -383,7 +380,7 @@
13. There is no difference in the names of local variables and class members (no prefixes required).
```
timer (не m_timer)
timer (not m_timer)
```
14. Constants in enums use CamelCase beginning with an uppercase letter. ALL_CAPS is also allowed. If the enum is not local, use enum class.
......
......@@ -132,8 +132,9 @@ Installing unixODBC and the ODBC driver for PostgreSQL:
sudo apt-get install -y unixodbc odbcinst odbc-postgresql
Configuring `/etc/odbc.ini` (или `~/.odbc.ini`): :
Configuring `/etc/odbc.ini` (or `~/.odbc.ini`):
```
[DEFAULT]
Driver = myconnection
......@@ -150,6 +151,7 @@ Configuring `/etc/odbc.ini` (или `~/.odbc.ini`): :
RowVersioning = No
ShowSystemTables = No
ConnSettings =
```
The dictionary configuration in ClickHouse:
......
......@@ -4,6 +4,5 @@ Prints every row in brackets. Rows are separated by commas. There is no comma af
The minimum set of characters that you need to escape when passing data in Values ​​format: single quotes and backslashes.
This is the format that is used in `INSERT INTO t VALUES ...`
Но вы также можете использовать его для форматирования результатов запросов.
This is the format that is used in `INSERT INTO t VALUES ...` but you can also use it for query result.
......@@ -39,7 +39,7 @@ Accepts an empty array and returns a one-element array that is equal to the defa
Returns an array of numbers from 0 to N-1.
Just in case, an exception is thrown if arrays with a total length of more than 100,000,000 elements are created in a data block.
## array(x1, ...), оператор \[x1, ...\]
## array(x1, ...), operator \[x1, ...\]
Creates an array from the function arguments.
The arguments must be constants and have types that have the smallest common type. At least one argument must be passed, because otherwise it isn't clear which type of array to create. That is, you can't use this function to create an empty array (to do that, use the 'emptyArray\*' function described above).
......
......@@ -24,7 +24,8 @@ If there is no `id` key in the dictionary, it returns the default value specifie
## dictGetTOrDefault
`dictGetT('dict_name', 'attr_name', id, default)`
Аналогично функциям dictGetT, но значение по умолчанию берётся из последнего аргумента функции.
Similar to the functions dictGetT, but the default value is taken from the last argument of the function.
## dictIsIn
......
......@@ -5,7 +5,7 @@ In Yandex.Metrica, JSON is transmitted by users as session parameters. There are
The following assumptions are made:
1. The field name (function argument) must be a constant.
2. The field name is somehow canonically encoded in JSON. For example: `visitParamHas('{"abc":"def"}', 'abc') = 1`, но `visitParamHas('{"\\u0061\\u0062\\u0063":"def"}', 'abc') = 0`
2. The field name is somehow canonically encoded in JSON. For example: `visitParamHas('{"abc":"def"}', 'abc') = 1`, but `visitParamHas('{"\\u0061\\u0062\\u0063":"def"}', 'abc') = 0`
3. Fields are searched for on any nesting level, indiscriminately. If there are multiple matching fields, the first occurrence is used.
4. The JSON doesn't have space characters outside of string literals.
......
......@@ -166,7 +166,7 @@ Example:
```sql
SELECT
transform(domain(Referer), ['yandex.ru', 'google.ru', 'vk.com'], ['www.yandex', 'ввв.яндекс.рф', 'example.com']) AS s,
transform(domain(Referer), ['yandex.ru', 'google.ru', 'vk.com'], ['www.yandex', 'example.com']) AS s,
count() AS c
FROM test.hits
GROUP BY domain(Referer)
......@@ -180,7 +180,6 @@ LIMIT 10
│ www.yandex │ 867767 │
│ ███████.ru │ 313599 │
│ mail.yandex.ru │ 107147 │
│ ввв.яндекс.рф │ 105668 │
│ ██████.ru │ 100355 │
│ █████████.ru │ 65040 │
│ news.yandex.ru │ 64515 │
......
......@@ -2,9 +2,7 @@
## How to import raw data
See <https://github.com/toddwschneider/nyc-taxi-data>
и <http://tech.marksblogg.com/billion-nyc-taxi-rides-redshift.html>
для описания набора данных и инструкций по загрузке.
See <https://github.com/toddwschneider/nyc-taxi-data> and <http://tech.marksblogg.com/billion-nyc-taxi-rides-redshift.html> for description of the dataset and loading instructions.
Downloading will result in about 227 GB of uncompressed data in CSV files. The download takes about an hour over a 1 Gbit connection (parallel downloading from s3.amazonaws.com recovers at least half of a 1 Gbit channel).
Some of the files might not download fully. Check the file sizes and re-download any that seem doubtful.
......
......@@ -49,8 +49,8 @@ You can compile packages and install them.
You can also use programs without installing packages.
```text
Клиент: dbms/src/Client/
Сервер: dbms/src/Server/
Client: dbms/src/Client/
Server: dbms/src/Server/
```
For the server, create a catalog with data, such as:
......
......@@ -5,8 +5,8 @@ ClickHouse is a columnar DBMS for OLAP.
In a "normal" row-oriented DBMS, data is stored in this order:
```text
5123456789123456789 1 Евробаскет - Греция - Босния и Герцеговина - example.com 1 2011-09-01 01:03:02 6274717 1294101174 11409 612345678912345678 0 33 6 http://www.example.com/basketball/team/123/match/456789.html http://www.example.com/basketball/team/123/match/987654.html 0 1366 768 32 10 3183 0 0 13 0\0 1 1 0 0 2011142 -1 0 0 01321 613 660 2011-09-01 08:01:17 0 0 0 0 utf-8 1466 0 0 0 5678901234567890123 277789954 0 0 0 0 0
5234985259563631958 0 Консалтинг, налогообложение, бухгалтерский учет, право 1 2011-09-01 01:03:02 6320881 2111222333 213 6458937489576391093 0 3 2 http://www.example.ru/ 0 800 600 16 10 2 153.1 0 0 10 63 1 1 0 0 2111678 000 0 588 368 240 2011-09-01 01:03:17 4 0 60310 0 windows-1251 1466 0 000 778899001 0 0 0 0 0
5123456789123456789 1 Eurobasket - Greece - Bosnia and Herzegovina - example.com 1 2011-09-01 01:03:02 6274717 1294101174 11409 612345678912345678 0 33 6 http://www.example.com/basketball/team/123/match/456789.html http://www.example.com/basketball/team/123/match/987654.html 0 1366 768 32 10 3183 0 0 13 0\0 1 1 0 0 2011142 -1 0 0 01321 613 660 2011-09-01 08:01:17 0 0 0 0 utf-8 1466 0 0 0 5678901234567890123 277789954 0 0 0 0 0
5234985259563631958 0 Consulting, Tax assessment, Accounting, Law 1 2011-09-01 01:03:02 6320881 2111222333 213 6458937489576391093 0 3 2 http://www.example.ru/ 0 800 600 16 10 2 153.1 0 0 10 63 1 1 0 0 2111678 000 0 588 368 240 2011-09-01 01:03:17 4 0 60310 0 windows-1251 1466 0 000 778899001 0 0 0 0 0
...
```
......
......@@ -449,7 +449,7 @@ Keys for server/client settings:
- verificationMode – The method for checking the node's certificates. Details are in the description of the [Context](https://github.com/yandex/ClickHouse/blob/master/contrib/libpoco/NetSSL_OpenSSL/include/Poco/Net/Context.h) class. Acceptable values: ``none``, ``relaxed``, ``strict``, ``once``.
- verificationDepth – The maximum length of the verification chain. Verification will fail if the certificate chain length exceeds the set value.
- loadDefaultCAFile – Indicates that built-in CA certificates for OpenSSL will be used. Acceptable values: `` true``, `` false``. |
- cipherList - Поддерживаемые OpenSSL-шифры. For example: `` ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH``.
- cipherList - Supported OpenSSL-ciphers. For example: `` ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH``.
- cacheSessions – Enables or disables caching sessions. Must be used in combination with ``sessionIdContext``. Acceptable values: `` true``, `` false``.
- sessionIdContext – A unique set of random characters that the server appends to each generated identifier. The length of the string must not exceed ``SSL_MAX_SSL_SESSION_ID_LENGTH``. This parameter is always recommended, since it helps avoid problems both if the server caches the session and if the client requested caching. Default value: ``${application.name}``.
- sessionCacheSize – The maximum number of sessions that the server caches. Default value: 1024\*20. 0 – Unlimited sessions.
......
......@@ -13,7 +13,7 @@ Settings profiles are declared in the user config file. This is usually `users.x
Example:
```xml
<!-- Профили настроек. -->
<!-- Settings profiles -->
<profiles>
<!-- Default settings -->
<default>
......@@ -21,7 +21,7 @@ Example:
<max_threads>8</max_threads>
</default>
<!-- Настройки для запросов из пользовательского интерфейса -->
<!-- Settings for quries from the user interface -->
<web>
<max_rows_to_read>1000000000</max_rows_to_read>
<max_bytes_to_read>100000000000</max_bytes_to_read>
......
......@@ -457,8 +457,9 @@ Displays a list of tables
- tables from the current database, or from the 'db' database if "FROM db" is specified.
- all tables, or tables whose name matches the pattern, if "LIKE 'pattern'" is specified.
This query is identical to: `SELECT name FROM system.tables WHERE database = 'db' [AND name LIKE 'pattern'] [INTO OUTFILE filename] [FORMAT format]`
Смотрите также раздел "Оператор LIKE".
This query is identical to: `SELECT name FROM system.tables WHERE database = 'db' [AND name LIKE 'pattern'] [INTO OUTFILE filename] [FORMAT format]`.
See the section "LIKE operator" also.
## SHOW PROCESSLIST
......@@ -1102,7 +1103,7 @@ Example:
SELECT
domainWithoutWWW(URL) AS domain,
count(),
any(Title) AS title -- для каждого домена достаём первый попавшийся заголовок страницы
any(Title) AS title -- getting the first occurred page header for each domain.
FROM hits
GROUP BY domain
```
......
......@@ -34,7 +34,8 @@ Keywords (such as `SELECT`) are not case-sensitive. Everything else (column name
Identifiers (column names, functions, and data types) can be quoted or non-quoted.
Non-quoted identifiers start with a Latin letter or underscore, and continue with a Latin letter, underscore, or number. In other words, they must match the regex `^[a-zA-Z_][0-9a-zA-Z_]*$`. Examples: `x, _1, X_y__Z123_.`
Квотированные идентификаторы расположены в обратных кавычках `` `id ``\` (the same as in MySQL), and can indicate any set of bytes (non-empty). In addition, symbols (for example, the reverse quotation mark) inside this type of identifier can be backslash-escaped. Escaping rules are the same as for string literals (see below).
Quoted identifiers are placed in reversed quotation marks `` `id` `` (the same as in MySQL), and can indicate any set of bytes (non-empty). In addition, symbols (for example, the reverse quotation mark) inside this type of identifier can be backslash-escaped. Escaping rules are the same as for string literals (see below).
We recommend using identifiers that do not need to be quoted.
## Literals
......
......@@ -43,7 +43,9 @@ With SELECT from an AggregatingMergeTree table, use GROUP BY and aggregate funct
You can use AggregatingMergeTree tables for incremental data aggregation, including for aggregated materialized views.
Пример:Creating a materialized AggregatingMergeTree view that tracks the 'test.visits' table:
Example:
Creating a materialized AggregatingMergeTree view that tracks the 'test.visits' table:
```sql
CREATE MATERIALIZED VIEW test.basic
......
......@@ -35,13 +35,13 @@ Deletes the partition for the current week with event type 1. The same is true f
Note: For old-style tables, the partition can be specified either as a number `201710` or a string `'201710'`. The syntax for the new style of tables is stricter with types (similar to the parser for the VALUES input format). In addition, ALTER TABLE FREEZE PARTITION uses exact match for new-style tables (not prefix match).
In the `system.parts` table, the `partition` column should specify the value of the partition expression to use in ALTER queries (if quotas are removed). The `name` column should specify the name of the data part that has a new format.<br>
Было: `20140317_20140323_2_2_0`<br>
(минимальная дата - максимальная дата - номер минимального блока - номер максимального блока - уровень).<br>
Стало: `201403_2_2_0`<br>
(ID партиции - номер минимального блока - номер максимального блока - уровень).
In the `system.parts` table, the `partition` column should specify the value of the partition expression to use in ALTER queries (if quotas are removed). The `name` column should specify the name of the data part that has a new format.
Before: `20140317_20140323_2_2_0` (minimal data - maximal data - number of minimal block - number of maximal block - level).
After: `201403_2_2_0` (partition ID - number of minimal block - number of maximal block - level).
The partition ID is its string identifier (human-readable, if possible) that is used for the names of data parts in the file system and in ZooKeeper. You can specify it in ALTER queries in place of the partition key. Example: Partition key `toYYYYMM(EventDate)`; ALTER can specify either `PARTITION 201710` or `PARTITION ID '201710'`.
There are more examples in the tests [`00502_custom_partitioning_local`](https://github.com/yandex/ClickHouse/blob/master/dbms/tests/queries/0_stateless/00502_custom_partitioning_local.sql)and[`00502_custom_partitioning_replicated_zookeeper`](https://github.com/yandex/ClickHouse/blob/master/dbms/tests/queries/0_stateless/00502_custom_partitioning_replicated_zookeeper.sql).
There are more examples in the tests [`00502_custom_partitioning_local`](https://github.com/yandex/ClickHouse/blob/master/dbms/tests/queries/0_stateless/00502_custom_partitioning_local.sql) and [`00502_custom_partitioning_replicated_zookeeper`](https://github.com/yandex/ClickHouse/blob/master/dbms/tests/queries/0_stateless/00502_custom_partitioning_replicated_zookeeper.sql).
......@@ -89,7 +89,7 @@
}
```
15. Если на весь файл один namespace и кроме него ничего существенного нет - то отступ внутри namespace не нужен.
16. Если блок для выражения if, for, while... состоит из одного statement-а, то фигурные скобки писать не обязательно. Вместо этого поместите statement на отдельную строку. Этим statement-ом также может быть вложенный if, for, while... Но если внутренний statement содержит фигурные скобки или else, то у внешнего блок следует писать в фигурных скобках.
16. Если блок для выражения if, for, while... состоит из одного statement-а, то фигурные скобки писать не обязательно. Вместо этого поместите statement на отдельную строку. Этим statement-ом также может быть вложенный if, for, while... Но если внутренний statement содержит фигурные скобки или else, то внешний блок следует писать в фигурных скобках.
```cpp
/// Finish write.
......@@ -240,7 +240,7 @@
14. Не нужно писать в комментарии диалог (лучше сказать устно).
```
/// Зачем ты сделал эту фигню?
/// Why did you do this stuff?
```
15. Не нужно писать комментарий в конце блока о том, что представлял собой этот блок.
......@@ -327,7 +327,7 @@
13. Именование локальных переменных и членов класса никак не отличается (никакие префиксы не нужны).
```
timer (не m_timer)
timer (not m_timer)
```
14. Константы в enum-е - CamelCase с большой буквы. Также допустимо ALL_CAPS. Если enum не локален, то используйте enum class.
......
......@@ -132,8 +132,9 @@
sudo apt-get install -y unixodbc odbcinst odbc-postgresql
Настройка `/etc/odbc.ini` (или `~/.odbc.ini`): :
Настройка `/etc/odbc.ini` (или `~/.odbc.ini`):
```
[DEFAULT]
Driver = myconnection
......@@ -150,6 +151,7 @@
RowVersioning = No
ShowSystemTables = No
ConnSettings =
```
Конфигурация словаря в ClickHouse:
......
......@@ -4,5 +4,4 @@
Минимальный набор символов, которых вам необходимо экранировать при передаче в Values формате: одинарная кавычка и обратный слеш.
Именно этот формат используется в запросе `INSERT INTO t VALUES ...`
Но вы также можете использовать его для форматирования результатов запросов.
Именно этот формат используется в запросе `INSERT INTO t VALUES ...`, но вы также можете использовать его для форматирования результатов запросов.
......@@ -22,8 +22,10 @@
Если ключа `id` нет в словаре - вернуть значение по умолчанию, заданное в описании словаря.
## dictGetTOrDefault
`dictGetT('dict_name', 'attr_name', id, default)`
Аналогично функциям dictGetT, но значение по умолчанию берётся из последнего аргумента функции.
Аналогично функциям `dictGetT`, но значение по умолчанию берётся из последнего аргумента функции.
## dictIsIn
`dictIsIn('dict_name', child_id, ancestor_id)`
......
......@@ -156,7 +156,7 @@ ORDER BY c DESC
```sql
SELECT
transform(domain(Referer), ['yandex.ru', 'google.ru', 'vk.com'], ['www.yandex', 'ввв.яндекс.рф', 'example.com']) AS s,
transform(domain(Referer), ['yandex.ru', 'google.ru', 'vk.com'], ['www.yandex', 'example.com']) AS s,
count() AS c
FROM test.hits
GROUP BY domain(Referer)
......@@ -170,7 +170,6 @@ LIMIT 10
│ www.yandex │ 867767 │
│ ███████.ru │ 313599 │
│ mail.yandex.ru │ 107147 │
│ ввв.яндекс.рф │ 105668 │
│ ██████.ru │ 100355 │
│ █████████.ru │ 65040 │
│ news.yandex.ru │ 64515 │
......
......@@ -2,9 +2,7 @@
## Как импортировать сырые данные
См. <https://github.com/toddwschneider/nyc-taxi-data>
и <http://tech.marksblogg.com/billion-nyc-taxi-rides-redshift.html>
для описания набора данных и инструкций по загрузке.
См. <https://github.com/toddwschneider/nyc-taxi-data> и <http://tech.marksblogg.com/billion-nyc-taxi-rides-redshift.html> для описания набора данных и инструкций по загрузке.
После скачивания получится порядка 227 Гб несжатых данных в CSV файлах. Скачивание занимает порядка часа на 1 Гбит соединении (параллельное скачивание с s3.amazonaws.com утилизирует как минимум половину гигабитного канала).
Некоторые файлы могут скачаться не полностью. Проверьте размеры файлов и скачайте повторно подозрительные.
......
......@@ -52,8 +52,8 @@ ClickHouse содержит настройки ограничения досту
Также вы можете использовать программы без установки пакетов.
```text
Клиент: dbms/src/Client/
Сервер: dbms/src/Server/
Client: dbms/src/Client/
Server: dbms/src/Server/
```
Для сервера создаёте директории с данными, например:
......
......@@ -5,8 +5,8 @@ ClickHouse - столбцовая СУБД для OLAP (Columnar DBMS).
В обычной, "строковой" СУБД, данные хранятся в таком порядке:
```text
5123456789123456789 1 Евробаскет - Греция - Босния и Герцеговина - example.com 1 2011-09-01 01:03:02 6274717 1294101174 11409 612345678912345678 0 33 6 http://www.example.com/basketball/team/123/match/456789.html http://www.example.com/basketball/team/123/match/987654.html 0 1366 768 32 10 3183 0 0 13 0\0 1 1 0 0 2011142 -1 0 0 01321 613 660 2011-09-01 08:01:17 0 0 0 0 utf-8 1466 0 0 0 5678901234567890123 277789954 0 0 0 0 0
5234985259563631958 0 Консалтинг, налогообложение, бухгалтерский учет, право 1 2011-09-01 01:03:02 6320881 2111222333 213 6458937489576391093 0 3 2 http://www.example.ru/ 0 800 600 16 10 2 153.1 0 0 10 63 1 1 0 0 2111678 000 0 588 368 240 2011-09-01 01:03:17 4 0 60310 0 windows-1251 1466 0 000 778899001 0 0 0 0 0
5123456789123456789 1 Eurobasket - Greece - Bosnia and Herzegovina - example.com 1 2011-09-01 01:03:02 6274717 1294101174 11409 612345678912345678 0 33 6 http://www.example.com/basketball/team/123/match/456789.html http://www.example.com/basketball/team/123/match/987654.html 0 1366 768 32 10 3183 0 0 13 0\0 1 1 0 0 2011142 -1 0 0 01321 613 660 2011-09-01 08:01:17 0 0 0 0 utf-8 1466 0 0 0 5678901234567890123 277789954 0 0 0 0 0
5234985259563631958 0 Consulting, Tax assessment, Accounting, Law 1 2011-09-01 01:03:02 6320881 2111222333 213 6458937489576391093 0 3 2 http://www.example.ru/ 0 800 600 16 10 2 153.1 0 0 10 63 1 1 0 0 2111678 000 0 588 368 240 2011-09-01 01:03:17 4 0 60310 0 windows-1251 1466 0 000 778899001 0 0 0 0 0
...
```
......
......@@ -13,15 +13,15 @@ SET profile = 'web'
Пример:
```xml
<!-- Профили настроек. -->
<!-- Settings profiles -->
<profiles>
<!-- Настройки по умолчанию -->
<!-- Default settings -->
<default>
<!-- Максимальное количество потоков при выполнении одного запроса. -->
<!-- The maximum number of threads when running a single query. -->
<max_threads>8</max_threads>
</default>
<!-- Настройки для запросов из пользовательского интерфейса -->
<!-- Settings for quries from the user interface -->
<web>
<max_rows_to_read>1000000000</max_rows_to_read>
<max_bytes_to_read>100000000000</max_bytes_to_read>
......
......@@ -449,7 +449,8 @@ SHOW TABLES [FROM db] [LIKE 'pattern'] [INTO OUTFILE filename] [FORMAT format]
- из текущей БД или из БД db, если указано FROM db;
- всех, или имя которых соответствует шаблону pattern, если указано LIKE 'pattern';
Запрос полностью аналогичен запросу: `SELECT name FROM system.tables WHERE database = 'db' [AND name LIKE 'pattern'] [INTO OUTFILE filename] [FORMAT format]`
Запрос полностью аналогичен запросу: `SELECT name FROM system.tables WHERE database = 'db' [AND name LIKE 'pattern'] [INTO OUTFILE filename] [FORMAT format]`.
Смотрите также раздел "Оператор LIKE".
## SHOW PROCESSLIST
......@@ -1095,7 +1096,7 @@ FROM hits
SELECT
domainWithoutWWW(URL) AS domain,
count(),
any(Title) AS title -- для каждого домена достаём первый попавшийся заголовок страницы
any(Title) AS title -- getting the first occurred page header for each domain.
FROM hits
GROUP BY domain
```
......
......@@ -34,7 +34,8 @@ INSERT INTO t VALUES (1, 'Hello, world'), (2, 'abc'), (3, 'def')
Идентификаторы (имена столбцов, функций, типов данных) могут быть квотированными или не квотированными.
Не квотированные идентификаторы начинаются на букву латинского алфавита или подчёркивание; продолжаются на букву латинского алфавита или подчёркивание или цифру. Короче говоря, должны соответствовать регулярному выражению `^[a-zA-Z_][0-9a-zA-Z_]*$`. Примеры: `x, _1, X_y__Z123_.`
Квотированные идентификаторы расположены в обратных кавычках `` `id ``\` (также, как в MySQL), и могут обозначать произвольный (непустой) набор байт. При этом, внутри записи такого идентификатора, символы (например, символ обратной кавычки) могут экранироваться с помощью обратного слеша. Правила экранирования такие же, как в строковых литералах (см. ниже).
Квотированные идентификаторы расположены в обратных кавычках `` `id` `` (также, как в MySQL), и могут обозначать произвольный (непустой) набор байт. При этом, внутри записи такого идентификатора, символы (например, символ обратной кавычки) могут экранироваться с помощью обратного слеша. Правила экранирования такие же, как в строковых литералах (см. ниже).
Рекомендуется использовать идентификаторы, которые не нужно квотировать.
## Литералы
......
# AggregatingMergeTree
Отличается от MergeTree тем, что при слиянии, выполняет объединение состояний агрегатных функций, хранимых в таблице, для строчек с одинаковым значением первичного ключа.
Отличается от `MergeTree` тем, что при слиянии, выполняет объединение состояний агрегатных функций, хранимых в таблице, для строчек с одинаковым значением первичного ключа.
Чтобы это работало, используются: тип данных AggregateFunction, а также модификаторы -State и -Merge для агрегатных функций. Рассмотрим подробнее.
Чтобы это работало, используются: тип данных `AggregateFunction`, а также модификаторы `-State` и `-Merge` для агрегатных функций. Рассмотрим подробнее.
Существует тип данных `AggregateFunction`. Это параметрический тип данных. В качестве параметров передаются: имя агрегатной функции, затем типы её аргументов.
Существует тип данных AggregateFunction. Это параметрический тип данных. В качестве параметров передаются: имя агрегатной функции, затем типы её аргументов.
Примеры:
```sql
......@@ -19,11 +20,15 @@ CREATE TABLE t
Столбец такого типа хранит состояние агрегатной функции.
Чтобы получить значение такого типа, следует использовать агрегатные функции с суффиксом `State`.
Пример: `uniqState(UserID), quantilesState(0.5, 0.9)(SendTiming)` - в отличие от соответствующих функций uniq, quantiles, такие функции возвращают не готовое значение, а состояние. То есть, значение типа AggregateFunction.
Значение типа AggregateFunction нельзя вывести в Pretty-форматах. В других форматах, значения такого типа выводятся в виде implementation-specific бинарных данных. То есть, значения типа AggregateFunction не предназначены для вывода, сохранения в дамп.
Пример:
`uniqState(UserID), quantilesState(0.5, 0.9)(SendTiming)`
В отличие от соответствующих функций `uniq`, `quantiles`, такие функции возвращают не готовое значение, а состояние. То есть, значение типа `AggregateFunction`.
Единственную полезную вещь, которую можно сделать со значениями типа AggregateFunction - это объединить состояния и получить результат, по сути - доагрегировать до конца. Для этого используются агрегатные функции с суффиксом Merge.
Значение типа `AggregateFunction` нельзя вывести в Pretty-форматах. В других форматах, значения такого типа выводятся в виде implementation-specific бинарных данных. То есть, значения типа `AggregateFunction` не предназначены для вывода, сохранения в дамп.
Единственную полезную вещь, которую можно сделать со значениями типа `AggregateFunction` - это объединить состояния и получить результат, по сути - доагрегировать до конца. Для этого используются агрегатные функции с суффиксом Merge.
Пример: `uniqMerge(UserIDState), где UserIDState имеет тип AggregateFunction`.
То есть, агрегатная функция с суффиксом Merge берёт множество состояний, объединяет их, и возвращает готовый результат.
......@@ -37,14 +42,15 @@ SELECT uniqMerge(state) FROM (SELECT uniqState(UserID) AS state FROM table GROUP
Существует движок `AggregatingMergeTree`. Он занимается тем, что при слияниях, выполняет объединение состояний агрегатных функций из разных строчек таблицы с одним значением первичного ключа.
В таблицу, содержащую столбцы типа AggregateFunction невозможно вставить строчку обычным запросом INSERT, так как невозможно явно указать значение типа AggregateFunction. Вместо этого, для вставки данных, следует использовать INSERT SELECT с агрегатными функциями -State.
В таблицу, содержащую столбцы типа `AggregateFunction` невозможно вставить строчку обычным запросом INSERT, так как невозможно явно указать значение типа `AggregateFunction`. Вместо этого, для вставки данных, следует использовать `INSERT SELECT` с агрегатными функциями `-State`.
При SELECT-е из таблицы AggregatingMergeTree, используйте GROUP BY и агрегатные функции с модификатором -Merge, чтобы доагрегировать данные.
При SELECT-е из таблицы `AggregatingMergeTree`, используйте GROUP BY и агрегатные функции с модификатором -Merge, чтобы доагрегировать данные.
Таблицы типа AggregatingMergeTree могут использоваться для инкрементальной агрегации данных, в том числе, для агрегирующих материализованных представлений.
Таблицы типа `AggregatingMergeTree` могут использоваться для инкрементальной агрегации данных, в том числе, для агрегирующих материализованных представлений.
Пример:
Создаём материализованное представление типа AggregatingMergeTree, следящее за таблицей test.visits:
Создаём материализованное представление типа `AggregatingMergeTree`, следящее за таблицей `test.visits`:
```sql
CREATE MATERIALIZED VIEW test.basic
......@@ -58,13 +64,13 @@ FROM test.visits
GROUP BY CounterID, StartDate;
```
Вставляем данные в таблицу test.visits. Данные будут также вставлены в представление, где они будут агрегированы:
Вставляем данные в таблицу `test.visits`. Данные будут также вставлены в представление, где они будут агрегированы:
```sql
INSERT INTO test.visits ...
```
Делаем SELECT из представления, используя GROUP BY, чтобы доагрегировать данные:
Делаем `SELECT` из представления, используя `GROUP BY`, чтобы доагрегировать данные:
```sql
SELECT
......
......@@ -32,11 +32,11 @@ ALTER TABLE table DROP PARTITION (toMonday(today()), 1)
Замечание: для таблиц старого стиля можно указывать партицию и как число `201710`, и как строку `'201710'`. Синтаксис для таблиц нового типа более строг к типам (аналогично парсеру входного формата VALUES). Также, ALTER TABLE FREEZE PARTITION для таблиц нового типа работает по полному совпадению (не по префиксу).
В таблице `system.parts` в столбце `partition` указывается значение выражения партиционирования, пригодное к использованию в запросах ALTER (если убрать квотирование). В столбце `name` указывается имя куска, формат которого изменился.<br>
Было: `20140317_20140323_2_2_0`<br>
(минимальная дата - максимальная дата - номер минимального блока - номер максимального блока - уровень).<br>
Стало: `201403_2_2_0`<br>
(ID партиции - номер минимального блока - номер максимального блока - уровень).
В таблице `system.parts` в столбце `partition` указывается значение выражения партиционирования, пригодное к использованию в запросах ALTER (если убрать квотирование). В столбце `name` указывается имя куска, формат которого изменился.
Было: `20140317_20140323_2_2_0` (минимальная дата - максимальная дата - номер минимального блока - номер максимального блока - уровень).
Стало: `201403_2_2_0` (ID партиции - номер минимального блока - номер максимального блока - уровень).
ID партиции - это её строковый идентификатор (по возможности человекочитаемый), используемый для имён кусков на файловой системе и в ZooKeeper. Его можно указывать в запросах ALTER вместо значения ключа партиционирования. Пример: ключ партиционирования `toYYYYMM(EventDate)`, в ALTER можно указывать либо `PARTITION 201710`, либо `PARTITION ID '201710'`.
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册