Skip to content

Commit c59935e

Browse files
authored
YDBDOCS-768: introduce recipes folder for CLI + converting table types recipe (#7092)
1 parent 75ab2b2 commit c59935e

File tree

10 files changed

+249
-0
lines changed

10 files changed

+249
-0
lines changed

ydb/docs/en/core/recipes/index.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,5 @@
33
This section of {{ ydb-short-name }} documentation contains ready-to-use recipes for various aspects of interacting with {{ ydb-short-name }}. They are grouped into the following categories:
44

55
* [{#T}](ydb-sdk/index.md)
6+
* [{#T}](ydb-cli/index.md)
67
* [{#T}](yql/index.md)

ydb/docs/en/core/recipes/toc_p.yaml

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,11 @@ items:
33
include:
44
mode: link
55
path: ydb-sdk/toc_p.yaml
6+
- name: YDB CLI
7+
href: ydb-cli/index.md
8+
include:
9+
mode: link
10+
path: ydb-cli/toc_p.yaml
611
- name: YQL
712
include:
813
mode: link
Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
# Convert a table between row-oriented and column-oriented
2+
3+
{{ ydb-short-name }} supports two main types of tables: [row-oriented](../../concepts/datamodel/table.md#row-oriented-tables) and [column-oriented](../../concepts/datamodel/table.md#column-oriented-tables). The chosen table type determines the physical representation of data on disks, so changing the type in place is impossible. However, you can create a new table of a different type and copy the data. This recipe consists of the following steps:
4+
5+
1. [Prepare a new table](#prepare)
6+
2. [Copy data](#copy)
7+
3. [Switch the workload](#switch) *(optional)*
8+
9+
These instructions assume that the source table is row-oriented, and the goal is to obtain a similar column-oriented destination table; however, the table roles could be swapped.
10+
11+
{% include [ydb-cli-profile.md](../../_includes/ydb-cli-profile.md) %}
12+
13+
## Prepare a new table {#prepare}
14+
15+
Take a copy of the original `CREATE TABLE` statement used for the source table. Modify the following to create a file with the `CREATE TABLE` query for the destination table:
16+
17+
1. Change the table name to a desired new name.
18+
2. Set the `STORE` setting value to `COLUMN` to make it a column-oriented table.
19+
20+
Run this query (assuming it is saved in a file named `create_column_oriented_table.yql`):
21+
22+
```bash
23+
$ ydb -p quickstart yql -f create_column_oriented_table.yql
24+
```
25+
26+
{% cut "Example test data and table schemas" %}
27+
28+
Row-oriented source table:
29+
30+
```yql
31+
CREATE TABLE `row_oriented_table` (
32+
id Int64 NOT NULL,
33+
metric_a Double,
34+
metric_b Double,
35+
metric_c Double,
36+
PRIMARY KEY (id)
37+
)
38+
```
39+
40+
Column-oriented destination table:
41+
42+
```yql
43+
CREATE TABLE `column_oriented_table` (
44+
id Int64 NOT NULL,
45+
metric_a Double,
46+
metric_b Double,
47+
metric_c Double,
48+
PRIMARY KEY (id)
49+
)
50+
PARTITION BY HASH(id)
51+
WITH (STORE = COLUMN)
52+
```
53+
54+
{% note info %}
55+
56+
Refer to the documentation for application developers to learn more about [partitioning column-oriented tables and choosing a partitioning key](../../dev/primary-key/column-oriented.md) (`PARTITION BY` clause).
57+
58+
{% endnote %}
59+
60+
61+
Fill the source row-oriented table with random data:
62+
63+
```yql
64+
INSERT INTO `row_oriented_table` (id, metric_a, metric_b, metric_c)
65+
SELECT
66+
id,
67+
Random(id + 1),
68+
Random(id + 2),
69+
Random(id + 3)
70+
FROM (
71+
SELECT ListFromRange(1, 1000) AS id
72+
) FLATTEN LIST BY id
73+
```
74+
75+
{% endcut %}
76+
77+
## Copy data {#copy}
78+
79+
Currently, the recommended way to copy data between {{ ydb-short-name }} tables of different types is to export and import:
80+
81+
1. Export data to the local filesystem:
82+
83+
```bash
84+
$ ydb -p quickstart dump -p row_oriented_table -o tmp_backup/
85+
```
86+
87+
2. Import it back into another {{ ydb-short-name }} table:
88+
89+
```bash
90+
ydb -p quickstart import file csv -p column_oriented_table tmp_backup/row_oriented_table/*.csv
91+
```
92+
93+
Make sure you have enough free space in the file system to store all the data.
94+
95+
## Switch the workload {#switch}
96+
97+
It is currently impossible to seamlessly replace the original table with a newly created column-oriented one. However, if necessary, you can gradually switch your queries to work with the new table by replacing the original table path in the queries with the new one.
98+
99+
If the original table is no longer needed, it can be dropped with `ydb -p quickstart table drop row_oriented_table` or `yql -p quickstart yql -s "DROP TABLE row_oriented_table"`.
100+
101+
## See also
102+
103+
* [{#T}](../../reference/ydb-cli/index.md)
104+
* [{#T}](../../dev/index.md)
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
# {{ ydb-short-name }} CLI recipes
2+
3+
This section contains recipes for various tasks that can be solved with {{ ydb-short-name }} CLI.
4+
5+
Table of contents:
6+
7+
* [{#T}](convert-table-type.md)
8+
9+
See also:
10+
11+
- [{#T}](../../reference/ydb-cli/index.md)
12+
- [{#T}](../../dev/index.md)
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
items:
2+
- name: Convert table type
3+
href: convert-table-type.md

ydb/docs/ru/core/recipes/index.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,5 @@
33
Этот раздел документации {{ ydb-short-name }} содержит готовые рецепты для различных аспектов взаимодействия с {{ ydb-short-name }}. Они сгруппированы по следующим категориям:
44

55
* [{#T}](ydb-sdk/index.md)
6+
* [{#T}](ydb-cli/index.md)
67
* [{#T}](yql/index.md)

ydb/docs/ru/core/recipes/toc_p.yaml

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,11 @@ items:
33
include:
44
mode: link
55
path: ydb-sdk/toc_p.yaml
6+
- name: YDB CLI
7+
href: ydb-cli/index.md
8+
include:
9+
mode: link
10+
path: ydb-cli/toc_p.yaml
611
- name: YQL
712
include:
813
mode: link
Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
# Конвертация таблиц между строковой и колоночной ориентацией
2+
3+
{{ ydb-short-name }} поддерживает два основных типа таблиц: [строковые](../../concepts/datamodel/table.md#row-oriented-tables) и [колоночные](../../concepts/datamodel/table.md#column-oriented-tables). Выбранный тип таблицы определяет физическое представление данных на дисках, поэтому изменение типа существующей таблицы невозможно. Однако вы можете создать новую таблицу другого типа и скопировать в неё данные. Этот рецепт состоит из следующих шагов:
4+
5+
1. [Подготовка новой таблицы](#prepare)
6+
2. [Копирование данных](#copy)
7+
3. [Переключение нагрузки](#switch) *(опционально)*
8+
9+
Эти инструкции предполагают, что исходная таблица является строковой, и целью является получение аналогичной колоночной таблицы; однако роли таблиц могут быть изменены на противоположные.
10+
11+
{% include [ydb-cli-profile.md](../../_includes/ydb-cli-profile.md) %}
12+
13+
## Подготовка новой таблицы {#prepare}
14+
15+
Возьмите копию исходной команды `CREATE TABLE`, использованной для создания исходной таблицы. Проделайте в этом запросе следующие изменения, чтобы создать файл с запросом `CREATE TABLE` для таблицы назначения:
16+
17+
1. Измените имя таблицы на желаемое новое имя.
18+
2. Установите значение параметра `STORE` в `COLUMN`, чтобы сделать таблицу колоночной.
19+
20+
Запустите этот запрос (предполагается, что он сохранён в файле с именем `create_column_oriented_table.yql`):
21+
22+
```bash
23+
$ ydb -p quickstart yql -f create_column_oriented_table.yql
24+
```
25+
26+
{% cut "Примеры схем тестовых таблиц и заполнения их данными" %}
27+
28+
Исходная строковая таблица:
29+
30+
```yql
31+
CREATE TABLE `row_oriented_table` (
32+
id Int64 NOT NULL,
33+
metric_a Double,
34+
metric_b Double,
35+
metric_c Double,
36+
PRIMARY KEY (id)
37+
)
38+
```
39+
40+
Колоночная таблица назначения:
41+
42+
```yql
43+
CREATE TABLE `column_oriented_table` (
44+
id Int64 NOT NULL,
45+
metric_a Double,
46+
metric_b Double,
47+
metric_c Double,
48+
PRIMARY KEY (id)
49+
)
50+
PARTITION BY HASH(id)
51+
WITH (STORE = COLUMN)
52+
```
53+
54+
{% note info %}
55+
56+
Обратитесь к документации для разработчиков приложений, чтобы узнать больше о [партицировании колоночных таблиц и выборе ключа их партицирования](../../dev/primary-key/column-oriented.md) (параметр `PARTITION BY`).
57+
58+
{% endnote %}
59+
60+
Заполнение исходной строковой таблицы случайными данными:
61+
62+
```yql
63+
INSERT INTO `row_oriented_table` (id, metric_a, metric_b, metric_c)
64+
SELECT
65+
id,
66+
Random(id + 1),
67+
Random(id + 2),
68+
Random(id + 3)
69+
FROM (
70+
SELECT ListFromRange(1, 1000) AS id
71+
) FLATTEN LIST BY id
72+
```
73+
74+
{% endcut %}
75+
76+
## Копирование данных {#copy}
77+
78+
На данный момент рекомендуемый способ копирования данных между {{ ydb-short-name }} таблицами разных типов — это экспорт и импорт:
79+
80+
1. Экспорт данных в локальную файловую систему:
81+
82+
```bash
83+
$ ydb -p quickstart dump -p row_oriented_table -o tmp_backup/
84+
```
85+
86+
2. Импорт этих данных в другую таблицу {{ ydb-short-name }}:
87+
88+
```bash
89+
$ ydb -p quickstart import file csv -p column_oriented_table tmp_backup/row_oriented_table/*.csv
90+
```
91+
92+
Убедитесь, что у вас достаточно свободного места в файловой системе для хранения всех данных.
93+
94+
## Переключение нагрузки {#switch}
95+
96+
В настоящее время невозможно бесшовно заменить оригинальную таблицу на колоночную. Однако, при необходимости, вы можете постепенно переключить ваши запросы на работу с новой таблицей, заменив путь к оригинальной таблице в запросах на новый.
97+
98+
Если исходная таблица больше не нужна, её можно удалить с помощью `ydb -p quickstart table drop row_oriented_table` или `yql -p quickstart yql -s "DROP TABLE row_oriented_table"`.
99+
100+
## Смотрите также
101+
102+
* [{#T}](../../reference/ydb-cli/index.md)
103+
* [{#T}](../../dev/index.md)
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
# {{ ydb-short-name }} CLI рецепты
2+
3+
Этот раздел содержит рецепты для различных задач, которые можно решить с помощью {{ ydb-short-name }} CLI.
4+
5+
Содержание:
6+
7+
* [{#T}](convert-table-type.md)
8+
9+
Смотрите также:
10+
11+
- [{#T}](../../reference/ydb-cli/index.md)
12+
- [{#T}](../../dev/index.md)
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
items:
2+
- name: Конвертация типов таблиц
3+
href: convert-table-type.md

0 commit comments

Comments
 (0)