From 4fef7adbea0db8e930e90b2450e0d8f796b64701 Mon Sep 17 00:00:00 2001 From: Daniil Cherednik Date: Tue, 24 Sep 2024 11:35:37 +0000 Subject: [PATCH 1/4] Unique constraint docs (en, ru) --- ydb/docs/en/core/concepts/_includes/secondary_indexes.md | 8 ++++++++ .../reference/yql-core/syntax/_includes/create_table.md | 4 +++- .../yql-core/syntax/create_table/secondary_index.md | 6 ++++-- ydb/docs/ru/core/concepts/_includes/secondary_indexes.md | 8 ++++++++ .../reference/yql-core/syntax/_includes/create_table.md | 4 +++- .../yql-core/syntax/create_table/secondary_index.md | 4 +++- 6 files changed, 29 insertions(+), 5 deletions(-) diff --git a/ydb/docs/en/core/concepts/_includes/secondary_indexes.md b/ydb/docs/en/core/concepts/_includes/secondary_indexes.md index f63b6a7b0bb1..bba00c753709 100644 --- a/ydb/docs/en/core/concepts/_includes/secondary_indexes.md +++ b/ydb/docs/en/core/concepts/_includes/secondary_indexes.md @@ -21,6 +21,14 @@ 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 allows to get unique constraint behaviour. The query processor uses it to perform additional checks to guarantee indexed set of columns present just once in the table. If SQL modification of table brokes the constraint the coresponding query will be canceled with PRECONDITION_FAILED status. So user code must be ready to handle this status. Unique secondaty indes is a synchronous index so update process is same as in the [Synchronous secondary](#sync) described above from transaction perspective. + +As other this index allows to perform efficient point lookup query. + +Currently unique index can't be added in to existed 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. diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/create_table.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/create_table.md index df74ed46ffc7..2d0c4f1f4e32 100644 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/create_table.md +++ b/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/create_table.md @@ -102,7 +102,7 @@ The `INDEX` clause is used to define a {% if concept_secondary_index %}[secondar ```yql CREATE TABLE table_name ( ... - INDEX GLOBAL [SYNC|ASYNC] ON ( ) COVER ( ), + INDEX GLOBAL [UNIQUE] [SYNC|ASYNC] ON ( ) COVER ( ), ... ) ``` @@ -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 index should gurantee unique property for indexed column set thereby implements 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. @@ -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) ) ``` diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/create_table/secondary_index.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/create_table/secondary_index.md index 73c7d3500986..70c612c20ceb 100644 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/create_table/secondary_index.md +++ b/ydb/docs/en/core/yql/reference/yql-core/syntax/create_table/secondary_index.md @@ -7,7 +7,7 @@ The INDEX construct is used to define a {% if concept_secondary_index %}[seconda ```yql CREATE TABLE table_name ( ... - INDEX GLOBAL [SYNC|ASYNC] ON ( ) COVER ( ), + INDEX GLOBAL [UNIQUE] [SYNC|ASYNC] ON ( ) COVER ( ), ... ) ``` @@ -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 index should gurantee unique property for indexed column set thereby implements 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. @@ -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) ) -``` \ No newline at end of file +``` diff --git a/ydb/docs/ru/core/concepts/_includes/secondary_indexes.md b/ydb/docs/ru/core/concepts/_includes/secondary_indexes.md index aef1e5f683f3..3adcd398170d 100644 --- a/ydb/docs/ru/core/concepts/_includes/secondary_indexes.md +++ b/ydb/docs/ru/core/concepts/_includes/secondary_indexes.md @@ -21,6 +21,14 @@ Имеется возможность сделать копию содержимого колонок в индекс (covering index), таким образом это исключает необходимость чтения из основной таблицы в операциях чтения по индексу, что заметно снижает задержки. В то же время такая денормализация приводит к увеличенному потреблению дискового пространства и к возможному замедлению операции вставки и обновления из-за необходимости дополнительного копирования данных. +## Уникальный вторичный индекс {#unique} + +Этот тип индекса реализует семантику уникального значения в колонке или наборе колонок. Процессор запросов использует его для выполнения дополнительных проверок, чтобы гарантировать, что набор индексированных колонок присутствует в таблице только один раз. Если SQL-модификация таблицы нарушает это ограничение, соответствующий запрос будет отменен со статусом PRECONDITION_FAILED. Таким образом пользовательский код должен быть готов к обработке этого статуса. Уникальный вторичный индекс является синхронным индексом, поэтому процесс обновления происходит так же, как описано в разделе Синхронный вторичный с точки зрения транзакции. + +Как и другие индексы, этот индекс позволяет эффективно выполнять точечные чтения по набору индексируемых колонок. + +В настоящее время уникальный индекс не может быть добавлен в существующую таблицу. + ## Онлайн-создание вторичного индекса {#index-add} В {{ ydb-short-name }} доступно создание вторичного индекса, а также удаление существующего вторичного индекса без остановки обслуживания. Для одной таблицы можно создать только один индекс за раз. diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/create_table.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/create_table.md index 1532388ee3c5..11844d5de8e8 100644 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/create_table.md +++ b/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/create_table.md @@ -102,7 +102,7 @@ ```yql CREATE TABLE table_name ( ... - INDEX GLOBAL [SYNC|ASYNC] ON ( ) COVER ( ), + INDEX GLOBAL [UNIQUE] [SYNC|ASYNC] ON ( ) COVER ( ) ... ) ``` @@ -111,6 +111,7 @@ CREATE TABLE table_name ( * **index_name** — уникальное имя индекса, по которому будет возможно обращение к данным. * **SYNC/ASYNC** — синхронная или асинхронная запись в индекс, если не указано — синхронная. +* **UNIQUE** - создает индекс с гарантией уникальности для вставляемых значений. * **index_columns** — имена колонок создаваемой таблицы через запятую, по которым возможен поиск в индексе. * **cover_columns** — имена колонок создаваемой таблицы через запятую, которые будет сохранены в индексе дополнительно к колонкам поиска, давая возможность получить дополнительные данные без обращения за ними в таблицу. @@ -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) ) ``` diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/create_table/secondary_index.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/create_table/secondary_index.md index 4121dcca0725..3eae582cb1fa 100644 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/create_table/secondary_index.md +++ b/ydb/docs/ru/core/yql/reference/yql-core/syntax/create_table/secondary_index.md @@ -20,6 +20,7 @@ CREATE TABLE table_name ( * **index_name** — уникальное имя индекса, по которому будет возможно обращение к данным. * **SYNC/ASYNC** — синхронная или асинхронная запись в индекс, если не указано — синхронная. +* **UNIQUE** - создает индекс с гарантией уникальности для вставляемых значений. * **index_columns** — имена колонок создаваемой таблицы через запятую, по которым возможен поиск в индексе. * **cover_columns** — имена колонок создаваемой таблицы через запятую, которые будет сохранены в индексе дополнительно к колонкам поиска, давая возможность получить дополнительные данные без обращения за ними в таблицу. @@ -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) ) ``` @@ -78,4 +80,4 @@ CREATE TABLE my_table ( ) ``` -{% endif %} \ No newline at end of file +{% endif %} From fa08335218e7b3dca183b3b4ed3f321ef911f88c Mon Sep 17 00:00:00 2001 From: Ivan Blinkov Date: Tue, 24 Sep 2024 05:47:52 -0700 Subject: [PATCH 2/4] Apply suggestions from code review --- ydb/docs/en/core/concepts/_includes/secondary_indexes.md | 8 +++++--- .../reference/yql-core/syntax/_includes/create_table.md | 2 +- .../yql-core/syntax/create_table/secondary_index.md | 2 +- ydb/docs/ru/core/concepts/_includes/secondary_indexes.md | 6 ++++-- .../reference/yql-core/syntax/_includes/create_table.md | 2 +- .../yql-core/syntax/create_table/secondary_index.md | 2 +- 6 files changed, 13 insertions(+), 9 deletions(-) diff --git a/ydb/docs/en/core/concepts/_includes/secondary_indexes.md b/ydb/docs/en/core/concepts/_includes/secondary_indexes.md index bba00c753709..f3c604b89843 100644 --- a/ydb/docs/en/core/concepts/_includes/secondary_indexes.md +++ b/ydb/docs/en/core/concepts/_includes/secondary_indexes.md @@ -23,11 +23,13 @@ You can copy the contents of columns into a covering index. This eliminates the ## Unique secondary index {#unique} -This type of index allows to get unique constraint behaviour. The query processor uses it to perform additional checks to guarantee indexed set of columns present just once in the table. If SQL modification of table brokes the constraint the coresponding query will be canceled with PRECONDITION_FAILED status. So user code must be ready to handle this status. Unique secondaty indes is a synchronous index so update process is same as in the [Synchronous secondary](#sync) described above from transaction perspective. +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 canceled with a `PRECONDITION_FAILED` status. Therefore, client code must be prepared to handle this status. -As other this index allows to perform efficient point lookup query. +A unique secondary index is a synchronous index, so the update process is the same as in the [{#T}](#sync) section described above from a transaction perspective. -Currently unique index can't be added in to existed table. +### Limitations + +Currently, a unique index cannot be added to an existing table. ## Creating a secondary index online {#index-add} diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/create_table.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/create_table.md index 2d0c4f1f4e32..bd959b7c1f93 100644 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/create_table.md +++ b/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/create_table.md @@ -111,7 +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 index should gurantee unique property for indexed column set thereby implements unique constraint. +* **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. diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/create_table/secondary_index.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/create_table/secondary_index.md index 70c612c20ceb..9d99d900fb37 100644 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/create_table/secondary_index.md +++ b/ydb/docs/en/core/yql/reference/yql-core/syntax/create_table/secondary_index.md @@ -16,7 +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 index should gurantee unique property for indexed column set thereby implements unique constraint. +* **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. diff --git a/ydb/docs/ru/core/concepts/_includes/secondary_indexes.md b/ydb/docs/ru/core/concepts/_includes/secondary_indexes.md index 3adcd398170d..cf9238cdf726 100644 --- a/ydb/docs/ru/core/concepts/_includes/secondary_indexes.md +++ b/ydb/docs/ru/core/concepts/_includes/secondary_indexes.md @@ -23,9 +23,11 @@ ## Уникальный вторичный индекс {#unique} -Этот тип индекса реализует семантику уникального значения в колонке или наборе колонок. Процессор запросов использует его для выполнения дополнительных проверок, чтобы гарантировать, что набор индексированных колонок присутствует в таблице только один раз. Если SQL-модификация таблицы нарушает это ограничение, соответствующий запрос будет отменен со статусом PRECONDITION_FAILED. Таким образом пользовательский код должен быть готов к обработке этого статуса. Уникальный вторичный индекс является синхронным индексом, поэтому процесс обновления происходит так же, как описано в разделе Синхронный вторичный с точки зрения транзакции. +Этот тип индекса реализует семантику уникального значения в колонке или наборе колонок, а также, как и другие индексы, позволяет эффективно выполнять точечные чтения по набору индексируемых колонок. {{ ydb-short-name }} использует его для выполнения дополнительных проверок, чтобы гарантировать, что каждое уникальное значение индексируемых колонок присутствует в таблице не более одного раза. Если модифицирующий запрос нарушает это ограничение, он будет отменён со статусом `PRECONDITION_FAILED`. Таким образом, пользовательский код должен быть готов к обработке этого статуса. -Как и другие индексы, этот индекс позволяет эффективно выполнять точечные чтения по набору индексируемых колонок. +Уникальный вторичный индекс является синхронным индексом, поэтому процесс обновления происходит так же, как описано в разделе [Синхронный вторичный](#sync) с точки зрения транзакции. + +### Ограничения В настоящее время уникальный индекс не может быть добавлен в существующую таблицу. diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/create_table.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/create_table.md index 11844d5de8e8..8b4e00316ddd 100644 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/create_table.md +++ b/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/create_table.md @@ -111,7 +111,7 @@ CREATE TABLE table_name ( * **index_name** — уникальное имя индекса, по которому будет возможно обращение к данным. * **SYNC/ASYNC** — синхронная или асинхронная запись в индекс, если не указано — синхронная. -* **UNIQUE** - создает индекс с гарантией уникальности для вставляемых значений. +* **UNIQUE** — создаёт индекс с гарантией уникальности для вставляемых значений. * **index_columns** — имена колонок создаваемой таблицы через запятую, по которым возможен поиск в индексе. * **cover_columns** — имена колонок создаваемой таблицы через запятую, которые будет сохранены в индексе дополнительно к колонкам поиска, давая возможность получить дополнительные данные без обращения за ними в таблицу. diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/create_table/secondary_index.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/create_table/secondary_index.md index 3eae582cb1fa..649fb8a26203 100644 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/create_table/secondary_index.md +++ b/ydb/docs/ru/core/yql/reference/yql-core/syntax/create_table/secondary_index.md @@ -20,7 +20,7 @@ CREATE TABLE table_name ( * **index_name** — уникальное имя индекса, по которому будет возможно обращение к данным. * **SYNC/ASYNC** — синхронная или асинхронная запись в индекс, если не указано — синхронная. -* **UNIQUE** - создает индекс с гарантией уникальности для вставляемых значений. +* **UNIQUE** — создаёт индекс с гарантией уникальности для вставляемых значений. * **index_columns** — имена колонок создаваемой таблицы через запятую, по которым возможен поиск в индексе. * **cover_columns** — имена колонок создаваемой таблицы через запятую, которые будет сохранены в индексе дополнительно к колонкам поиска, давая возможность получить дополнительные данные без обращения за ними в таблицу. From 8460d969cd0295ff5a560417fe99d4c6bc5c94d0 Mon Sep 17 00:00:00 2001 From: Ivan Blinkov Date: Tue, 24 Sep 2024 05:55:05 -0700 Subject: [PATCH 3/4] fix warn --- ydb/docs/en/core/concepts/_includes/secondary_indexes.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ydb/docs/en/core/concepts/_includes/secondary_indexes.md b/ydb/docs/en/core/concepts/_includes/secondary_indexes.md index f3c604b89843..736f1de6a660 100644 --- a/ydb/docs/en/core/concepts/_includes/secondary_indexes.md +++ b/ydb/docs/en/core/concepts/_includes/secondary_indexes.md @@ -25,7 +25,7 @@ You can copy the contents of columns into a covering index. This eliminates the 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 canceled 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 [{#T}](#sync) section described above from a transaction perspective. +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 From e491d86f4c17d3b32040342e838e02dae740bfae Mon Sep 17 00:00:00 2001 From: Ivan Blinkov Date: Tue, 24 Sep 2024 05:56:52 -0700 Subject: [PATCH 4/4] Update secondary_indexes.md --- ydb/docs/en/core/concepts/_includes/secondary_indexes.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ydb/docs/en/core/concepts/_includes/secondary_indexes.md b/ydb/docs/en/core/concepts/_includes/secondary_indexes.md index 736f1de6a660..61570796ba78 100644 --- a/ydb/docs/en/core/concepts/_includes/secondary_indexes.md +++ b/ydb/docs/en/core/concepts/_includes/secondary_indexes.md @@ -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} @@ -23,7 +23,7 @@ You can copy the contents of columns into a covering index. This eliminates the ## 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 canceled with a `PRECONDITION_FAILED` status. Therefore, client code must be prepared to handle this status. +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.