Skip to content

Commit

Permalink
Merge d8320af into 8999d1e
Browse files Browse the repository at this point in the history
  • Loading branch information
swalrus1 authored Nov 26, 2024
2 parents 8999d1e + d8320af commit 034382c
Show file tree
Hide file tree
Showing 4 changed files with 116 additions and 10 deletions.
59 changes: 56 additions & 3 deletions ydb/docs/en/core/concepts/_includes/ttl.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,21 @@ This section describes how the TTL mechanism works and what its limits are. It a

## How it works {#how-it-works}

{{ ydb-short-name }} allows you to specify a TTL column in both [row-oriented](../datamodel/table.md#row-oriented-tables) and [column-oriented](../datamodel/table.md#column-oriented-tables) tables. Values in TTL columns determine the table rows lifetime.
The table's TTL is a sequence of storage tiers. Each tier contains an expression (TTL expression) and an action. When the expression triggers, that tier is assigned to the row. When a tier is assigned to a row, the specified action is automatically performed: moving the row to an external storage or deleting it. External storage is represented by the [external data source](https://ydb.tech/docs/en/concepts/datamodel/external_data_source) object. Deleting action can only be specified for the last tier.

{% note info %}

Currently, only an Object Storage is available as external storage.

{% endnote %}

{{ ydb-short-name }} allows you to specify a column (TTL column) whose values are used in TTL expressions. The expression triggers when the specified number of seconds have passed since the time recorded in the TTL column.

{% note info %}

Automatic data eviction to external storage is available only for column-oriented tables. For row-oriented tables, this functionality is under development.

{% endnote %}

{% note warning %}

Expand All @@ -15,12 +29,12 @@ An item with the `NULL` value in the TTL column is never deleted.
The timestamp for deleting a table item is determined by the formula:

```text
expiration_time = valueof(ttl_column) + expire_after_seconds
eviction_time = valueof(ttl_column) + evict_after_seconds
```

{% note info %}

TTL doesn't guarantee that the item will be deleted exactly at `expiration_time`, it might happen later. If it's important to exclude logically obsolete but not yet physically deleted items from the selection, use query-level filtering.
TTL doesn't guarantee that the item will be deleted exactly at `eviction_time`, it might happen later. If it's important to exclude logically obsolete but not yet physically deleted items from the selection, use query-level filtering.

{% endnote %}

Expand Down Expand Up @@ -176,6 +190,45 @@ The example below shows how to use the `modified_at` column with a numeric type

{% endlist %}

### Enabling eviction to Object Storage for an existing table {#enable-tiering-on-existing-tables}

{% note info %}

This functionality is only available for column-oriented tables. For row-oriented tables, this functionality is under development.

{% endnote %}

In the following example, rows of the table `mytable` will be moved to the bucket described in the external data source `/Root/s3_cold_data` one hour after the time recorded in the column `created_at`, and will be deleted after 24 hours:

{% list tabs group=tool %}

- YQL

```yql
ALTER TABLE `mytable` SET (TTL = Interval("PT1H") TO EXTERNAL DATA SOURCE `/Root/s3_cold_data`, Interval(PT24H) DELETE ON modified_at AS SECONDS);
```

{% if oss == true %}

- C++

```c++
session.AlterTable(
"mytable",
TAlterTableSettings()
.BeginAlterTtlSettings()
.Set("created_at", {
TTtlTierSettings(TDuration::Hours(1), TTtlEvictToExternalStorageAction("/Root/s3_cold_data")),
TTtlTierSettings(TDuration::Hours(24), TTtlDeleteAction("/Root/s3_cold_data"))
})
.EndAlterTtlSettings()
);
```
{% endif %}
{% endlist %}
### Enabling TTL for a newly created table {#enable-for-new-table}
For a newly created table, you can pass TTL settings along with the table description:
Expand Down
2 changes: 1 addition & 1 deletion ydb/docs/en/core/concepts/datamodel/_includes/table.md
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ If there are multiple followers, their delay from the leader may vary: although

| Parameter name | Type | Acceptable values | Update capability | Reset capability |
| ------------- | --- | ------------------- | --------------------- | ------------------ |
| `TTL` | Expression | `Interval("<literal>") ON <column> [AS <unit>]` | Yes | Yes |
| `TTL` | Expression | `<tier>, ..., <tier> ON <column> [AS <unit>]`, где `<tier>``Inteval("<literal>") TO EXTERNAL DATA SOURCE <path_to_source>` или `Inteval("<literal>") TO DELETE`. Краткая форма: `Interval("<literal>") ON <column> [AS <unit>]` — задаёт удаление данных | Да | Да |

Where `<unit>` is a unit of measurement, specified only for column with a [numeric type](../../../concepts/ttl.md#restrictions):

Expand Down
63 changes: 58 additions & 5 deletions ydb/docs/ru/core/concepts/_includes/ttl.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,23 +4,37 @@

## Принцип работы {#how-it-works}

{{ ydb-short-name }} позволяет указать для строковых и колоночных таблиц колонку (TTL-колонка), значения которой будут использоваться для определения времени жизни строк. TTL автоматически удаляет из таблицы строки, когда проходит указанное количество секунд от времени, записанного в TTL-колонку.
TTL таблицы задаётся последовательностью тиров хранения. Для каждого тира задаётся выражение, при срабатывании которого строке присваивается данный тир. Когда строке будет присвоен тир, TTL автоматически выполнит заданное действие: перенесёт строку во внешнее хранилище или удалит её. Внешние хранилища представляются объектом [external data source](https://ydb.tech/docs/ru/concepts/datamodel/external_data_source). Удаление может быть задано только для последнего тира.

{% note info %}

На данный момент, в качестве внешнего хранилища доступен только Object Storage.

{% endnote %}

{{ ydb-short-name }} позволяет указать для строковых и колоночных таблиц колонку (TTL-колонка), значения которой будут использоваться в TTL-выражениях. Выражение срабатывает, когда проходит указанное количество секунд от времени, записанного в TTL-колонку.

{% note info %}

Автоматическое перемещение данных во внешние хранилища доступно только для колоночных таблиц. Для строчных таблиц функциональность находится в разработке.

{% endnote %}

{% note warning %}

Строка с `NULL` в TTL-колонке никогда не будет удалена.
Строка с `NULL` в TTL-колонке никогда не сменит тир хранения.

{% endnote %}

Момент времени, когда строка таблицы может быть удалена, определяется по следующей формуле:
Момент времени, когда срабатывает TTL-выражение, определяется по следующей формуле:

```text
expiration_time = valueof(ttl_column) + expire_after_seconds
eviction_time = valueof(ttl_column) + evict_after_seconds
```

{% note info %}

Не гарантируется, что удаление произойдет именно в `expiration_time` — оно может случиться позже. Если важно исключить из выборки логически устаревшие, но пока еще физически не удаленные строки, нужно использовать фильтрацию уровня запроса.
Не гарантируется, что удаление произойдет именно в `eviction_time` — оно может случиться позже. Если важно исключить из выборки логически устаревшие, но пока еще физически не удаленные строки, нужно использовать фильтрацию уровня запроса.

{% endnote %}

Expand Down Expand Up @@ -176,6 +190,45 @@ expiration_time = valueof(ttl_column) + expire_after_seconds

{% endlist %}

### Включение вытеснения в Object Storage для существующих таблиц {#enable-tiering-on-existing-tables}

{% note info %}

Данная функциональность доступна только для колоночных таблиц. Для строчных таблиц функциональность находится в разработке.

{% endnote %}

В следующем примере строки таблицы `mytable` будут переноситься в бакет, описанный во внешнем источнике данных `/Root/s3_cold_data`, спустя час после наступления времени, записанного в колонке `created_at`, а спустя 24 часа будут удаляться:

{% list tabs group=tool %}

- YQL

```yql
ALTER TABLE `mytable` SET (TTL = Interval("PT1H") TO EXTERNAL DATA SOURCE `/Root/s3_cold_data`, Interval(PT24H) DELETE ON modified_at AS SECONDS);
```

{% if oss == true %}

- C++

```c++
session.AlterTable(
"mytable",
TAlterTableSettings()
.BeginAlterTtlSettings()
.Set("created_at", {
TTtlTierSettings(TDuration::Hours(1), TTtlEvictToExternalStorageAction("/Root/s3_cold_data")),
TTtlTierSettings(TDuration::Hours(24), TTtlDeleteAction("/Root/s3_cold_data"))
})
.EndAlterTtlSettings()
);
```
{% endif %}
{% endlist %}
### Включение TTL для вновь создаваемой таблицы {#enable-for-new-table}
Для вновь создаваемой таблицы можно передать настройки TTL вместе с ее описанием:
Expand Down
2 changes: 1 addition & 1 deletion ydb/docs/ru/core/concepts/datamodel/_includes/table.md
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ CREATE TABLE article (

| Имя параметра | Тип | Допустимые значения | Возможность<br/>изменения | Возможность<br/>сброса |
| ------------- | --- | ------------------- | --------------------- | ------------------ |
| `TTL` | Expression | `Interval("<literal>") ON <column> [AS <unit>]` | Да | Да |
| `TTL` | Expression | `<tier>, ..., <tier> ON <column> [AS <unit>]`, где `<tier>``Inteval("<literal>") TO EXTERNAL DATA SOURCE <path_to_source>` или `Inteval("<literal>") TO DELETE`. Краткая форма: `Interval("<literal>") ON <column> [AS <unit>]` — задаёт удаление данных | Да | Да |

Где `<unit>` — единица измерения, указывается только для колонок с [числовым типом](../../../concepts/ttl.md#restrictions):

Expand Down

0 comments on commit 034382c

Please sign in to comment.