Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unique constraint docs (en, ru) #9702

Merged
merged 4 commits into from
Sep 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion ydb/docs/en/core/concepts/_includes/secondary_indexes.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ The current version of {{ ydb-short-name }} implements _synchronous_ and _asynch
* For synchronous indexes: Transactionally when the main table changes.
* For asynchronous indexes: In the background while getting the necessary changes from the main table.

When a user sends an SQL query to insert, modify, or delete data, the database transparently generates commands to modify the index table. A table may have multiple secondary indexes. An index may include multiple columns, and the sequence of columns in an index matters. A single column may be included in multiple indexes. In addition to the specified columns, every index implicitly stores the table primary key columns, to enable nvaigation from an index record to the table row.
When a user sends an SQL query to insert, modify, or delete data, the database transparently generates commands to modify the index table. A table may have multiple secondary indexes. An index may include multiple columns, and the sequence of columns in an index matters. A single column may be included in multiple indexes. In addition to the specified columns, every index implicitly stores the table primary key columns to enable navigation from an index record to the table row.

## Synchronous secondary index {#sync}

Expand All @@ -21,6 +21,16 @@ Unlike a synchronous index, an asynchronous index doesn't use distributed transa

You can copy the contents of columns into a covering index. This eliminates the need to read data from the main table when performing reads by index and significantly reduces delays. At the same time, such denormalization leads to increased usage of disk space and may slow down inserts and updates due to the need for additional data copying.

## Unique secondary index {#unique}

This type of index enforces unique constraint behavior and, like other indexes, allows efficient point lookup queries. {{ ydb-short-name }} uses it to perform additional checks, ensuring that each distinct value in the indexed column set appears in the table no more than once. If a modifying query violates the constraint, it will be aborted with a `PRECONDITION_FAILED` status. Therefore, client code must be prepared to handle this status.

A unique secondary index is a synchronous index, so the update process is the same as in the [Synchronous secondary index](#sync) section described above from a transaction perspective.

### Limitations

Currently, a unique index cannot be added to an existing table.

## Creating a secondary index online {#index-add}

{{ ydb-short-name }} lets you create new and delete existing secondary indexes without stopping the service. For a single table, you can only create one index at a time.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ The `INDEX` clause is used to define a {% if concept_secondary_index %}[secondar
```yql
CREATE TABLE table_name (
...
INDEX <index_name> GLOBAL [SYNC|ASYNC] ON ( <index_columns> ) COVER ( <cover_columns> ),
INDEX <index_name> GLOBAL [UNIQUE] [SYNC|ASYNC] ON ( <index_columns> ) COVER ( <cover_columns> ),
...
)
```
Expand All @@ -111,6 +111,7 @@ Where:

* **Index_name** is the unique name of the index to be used to access data.
* **SYNC/ASYNC** indicates synchronous/asynchronous data writes to the index. If not specified, synchronous.
* **UNIQUE** indicates that the index should guarantee the uniqueness of the indexed column set, thereby enforcing the unique constraint.
* **Index_columns** is a list of comma-separated names of columns in the created table to be used for a search in the index.
* **Cover_columns** is a list of comma-separated names of columns in the created table, which will be stored in the index in addition to the search columns, making it possible to fetch additional data without accessing the table for it.

Expand All @@ -124,6 +125,7 @@ CREATE TABLE my_table (
d Date,
INDEX idx_d GLOBAL ON (d),
INDEX idx_ba GLOBAL ASYNC ON (b, a) COVER (c),
INDEX idx_bc GLOBAL UNIQUE SYNC ON (b, c),
PRIMARY KEY (a)
)
```
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ The INDEX construct is used to define a {% if concept_secondary_index %}[seconda
```yql
CREATE TABLE table_name (
...
INDEX <index_name> GLOBAL [SYNC|ASYNC] ON ( <index_columns> ) COVER ( <cover_columns> ),
INDEX <index_name> GLOBAL [UNIQUE] [SYNC|ASYNC] ON ( <index_columns> ) COVER ( <cover_columns> ),
...
)
```
Expand All @@ -16,6 +16,7 @@ Where:

* **Index_name** is the unique name of the index to be used to access data.
* **SYNC/ASYNC** indicates synchronous/asynchronous data writes to the index. If not specified, synchronous.
* **UNIQUE** indicates that the index should guarantee the uniqueness of the indexed column set, thereby enforcing the unique constraint.
* **Index_columns** is a list of comma-separated names of columns in the created table to be used for a search in the index.
* **Cover_columns** is a list of comma-separated names of columns in the created table, which will be stored in the index in addition to the search columns, making it possible to fetch additional data without accessing the table for it.

Expand All @@ -29,6 +30,7 @@ CREATE TABLE my_table (
d Date,
INDEX idx_d GLOBAL ON (d),
INDEX idx_ba GLOBAL ASYNC ON (b, a) COVER (c),
INDEX idx_bc GLOBAL UNIQUE SYNC ON (b, c),
PRIMARY KEY (a)
)
```
```
10 changes: 10 additions & 0 deletions ydb/docs/ru/core/concepts/_includes/secondary_indexes.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,16 @@

Имеется возможность сделать копию содержимого колонок в индекс (covering index), таким образом это исключает необходимость чтения из основной таблицы в операциях чтения по индексу, что заметно снижает задержки. В то же время такая денормализация приводит к увеличенному потреблению дискового пространства и к возможному замедлению операции вставки и обновления из-за необходимости дополнительного копирования данных.

## Уникальный вторичный индекс {#unique}

Этот тип индекса реализует семантику уникального значения в колонке или наборе колонок, а также, как и другие индексы, позволяет эффективно выполнять точечные чтения по набору индексируемых колонок. {{ ydb-short-name }} использует его для выполнения дополнительных проверок, чтобы гарантировать, что каждое уникальное значение индексируемых колонок присутствует в таблице не более одного раза. Если модифицирующий запрос нарушает это ограничение, он будет отменён со статусом `PRECONDITION_FAILED`. Таким образом, пользовательский код должен быть готов к обработке этого статуса.

Уникальный вторичный индекс является синхронным индексом, поэтому процесс обновления происходит так же, как описано в разделе [Синхронный вторичный](#sync) с точки зрения транзакции.

### Ограничения

В настоящее время уникальный индекс не может быть добавлен в существующую таблицу.

## Онлайн-создание вторичного индекса {#index-add}

В {{ ydb-short-name }} доступно создание вторичного индекса, а также удаление существующего вторичного индекса без остановки обслуживания. Для одной таблицы можно создать только один индекс за раз.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@
```yql
CREATE TABLE table_name (
...
INDEX <index_name> GLOBAL [SYNC|ASYNC] ON ( <index_columns> ) COVER ( <cover_columns> ),
INDEX <index_name> GLOBAL [UNIQUE] [SYNC|ASYNC] ON ( <index_columns> ) COVER ( <cover_columns> )
...
)
```
Expand All @@ -111,6 +111,7 @@ CREATE TABLE table_name (

* **index_name** — уникальное имя индекса, по которому будет возможно обращение к данным.
* **SYNC/ASYNC** — синхронная или асинхронная запись в индекс, если не указано — синхронная.
* **UNIQUE** — создаёт индекс с гарантией уникальности для вставляемых значений.
* **index_columns** — имена колонок создаваемой таблицы через запятую, по которым возможен поиск в индексе.
* **cover_columns** — имена колонок создаваемой таблицы через запятую, которые будет сохранены в индексе дополнительно к колонкам поиска, давая возможность получить дополнительные данные без обращения за ними в таблицу.

Expand All @@ -124,6 +125,7 @@ CREATE TABLE my_table (
d Date,
INDEX idx_d GLOBAL ON (d),
INDEX idx_ba GLOBAL ASYNC ON (b, a) COVER (c),
INDEX idx_bc GLOBAL UNIQUE SYNC ON (b, c),
PRIMARY KEY (a)
)
```
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ CREATE TABLE table_name (

* **index_name** — уникальное имя индекса, по которому будет возможно обращение к данным.
* **SYNC/ASYNC** — синхронная или асинхронная запись в индекс, если не указано — синхронная.
* **UNIQUE** — создаёт индекс с гарантией уникальности для вставляемых значений.
* **index_columns** — имена колонок создаваемой таблицы через запятую, по которым возможен поиск в индексе.
* **cover_columns** — имена колонок создаваемой таблицы через запятую, которые будет сохранены в индексе дополнительно к колонкам поиска, давая возможность получить дополнительные данные без обращения за ними в таблицу.

Expand All @@ -39,6 +40,7 @@ CREATE TABLE table_name (
d Date,
INDEX idx_d GLOBAL ON (d),
INDEX idx_ba GLOBAL ASYNC ON (b, a) COVER (c),
INDEX idx_bc GLOBAL UNIQUE SYNC ON (b, c),
PRIMARY KEY (a)
)
```
Expand Down Expand Up @@ -78,4 +80,4 @@ CREATE TABLE my_table (
)
```

{% endif %}
{% endif %}
Loading