This commit is contained in:
Nikita Vasilev 2019-01-22 17:39:18 +03:00
parent 2d06486f01
commit 5ed3269324
4 changed files with 62 additions and 4 deletions

View File

@ -34,6 +34,8 @@ CREATE TABLE [IF NOT EXISTS] [db.]table_name [ON CLUSTER cluster]
name1 [type1] [DEFAULT|MATERIALIZED|ALIAS expr1],
name2 [type2] [DEFAULT|MATERIALIZED|ALIAS expr2],
...
INDEX index_name1 expr1 TYPE type1(...) GRANULARITY value1,
INDEX index_name2 expr2 TYPE type2(...) GRANULARITY value2
) ENGINE = MergeTree()
[PARTITION BY expr]
[ORDER BY expr]
@ -225,6 +227,49 @@ To check whether ClickHouse can use the index when running a query, use the sett
The key for partitioning by month allows reading only those data blocks which contain dates from the proper range. In this case, the data block may contain data for many dates (up to an entire month). Within a block, data is sorted by primary key, which might not contain the date as the first column. Because of this, using a query with only a date condition that does not specify the primary key prefix will cause more data to be read than for a single date.
### Data Skipping Indices
Index declaration in the columns section of create query.
```sql
INDEX index_name expr TYPE type(...) GRANULARITY granularity_value
```
For tables from the `*MergeTree` family data skipping indices can be specified.
These indices aggregate some information about specified expression on blocks, which consist of `granularity_value` granules,
then these aggregates is used in `SELECT` queries for reducing amount of data to read from disk by skipping big blocks of data where `where` query can not be satisfied.
Example
```sql
CREATE TABLE table_name
(
u64 UInt64,
i32 Int32,
s String,
...
INDEX a (u64 * i32, s) TYPE minmax GRANULARITY 3,
INDEX b (u64 * length(s)) TYPE minmax GRANULARITY 4
) ENGINE = MergeTree()
...
```
Indices from the example can be used by ClickHouse to reduce amount of data read from disk in following queries.
```sql
SELECT count() FROM table WHERE s < 'z'
SELECT count() FROM table WHERE u64 * i32 == 10 AND u64 * length(s) >= 1234
```
#### Available Types of Indices
* `minmax` Stores extremes of specified expression (if expression is `tuple`, then it stores extremes for each element of `tuple`), uses stored info for skipping blocks of data like primary key.
```sql
INDEX b (u64 * length(s)) TYPE minmax GRANULARITY 4
```
## Concurrent Data Access
For concurrent table access, we use multi-versioning. In other words, when a table is simultaneously read and updated, data is read from a set of parts that is current at the time of the query. There are no lengthy locks. Inserts do not get in the way of read operations.

View File

@ -83,6 +83,19 @@ rows are ordered by the sorting key expression you cannot add expressions contai
to the sorting key (only columns added by the `ADD COLUMN` command in the same `ALTER` query).
### Manipulations With Data Skipping Indices
It only works for tables in the [`MergeTree`](../operations/table_engines/mergetree.md) family (including
[replicated](../operations/table_engines/replication.md) tables). The following operations
are available:
* `ALTER ADD INDEX name expression TYPE type GRANULARITY value AFTER name [AFTER name2]` - Adds index description to tables metadata.
* `ALTER DROP INDEX name` - Removes index description from tables metadata and index files from disk.
These commands are lightweight in sense that they only change metadata or remove files.
Also these operations are replicated.
### Manipulations With Partitions and Parts
It only works for tables in the [`MergeTree`](../operations/table_engines/mergetree.md) family (including

View File

@ -226,11 +226,11 @@ SELECT count() FROM table WHERE CounterID = 34 OR URL LIKE '%upyachka%'
Ключ партиционирования по месяцам обеспечивает чтение только тех блоков данных, которые содержат даты из нужного диапазона. При этом блок данных может содержать данные за многие даты (до целого месяца). В пределах одного блока данные упорядочены по первичному ключу, который может не содержать дату в качестве первого столбца. В связи с этим, при использовании запроса с указанием условия только на дату, но не на префикс первичного ключа, будет читаться данных больше, чем за одну дату.
## Дополнительные индексы
### Дополнительные индексы
Для таблиц семейства `*MergeTree` можно задать дополнительные индексы в секции столбцов.
Индекс аггрегирует для заданного выражения некоторые данные, а потом при `SELECT` запросе использует их после первичного ключа для пропуска боков данных (пропускаемый блок состоих из гранул данных (в которых `index_granularity` строк) в количестве равном гранулярности данного индекса), на которых секция `WHERE` не может быть выполнена, тем самым уменьшая объем данных читаемых с диска.
Индекс аггрегирует для заданного выражения некоторые данные, а потом при `SELECT` запросе использует их после первичного ключа для пропуска боков данных (пропускаемый блок состоих из гранул данных в количестве равном гранулярности данного индекса), на которых секция `WHERE` не может быть выполнена, тем самым уменьшая объем данных читаемых с диска.
Пример
```sql
@ -252,7 +252,7 @@ SELECT count() FROM table WHERE s < 'z'
SELECT count() FROM table WHERE u64 * i32 == 10 AND u64 * length(s) >= 1234
```
### Доступные индексы
#### Доступные индексы
* `minmax` Хранит минимум и максимум выражения (если выражение - `tuple`, то для каждого элемента `tuple`), используя их пропуска кусков аналогично первичному ключу.

View File

@ -83,7 +83,7 @@ MODIFY ORDER BY new_expression
Добавить или удалить индекс можно с помощью операций
```
ALTER ADD INDEX name expression TYPE type GRANULARITY value AFTER name
ALTER ADD INDEX name expression TYPE type GRANULARITY value [AFTER name]
ALTER DROP INDEX name
```
Поддерживается только таблицами семейства `*MergeTree`.