diff options
author | Ivan Blinkov <ivan@ydb.tech> | 2023-06-21 15:26:16 +0000 |
---|---|---|
committer | blinkov <blinkov@yandex-team.com> | 2023-06-21 18:26:16 +0300 |
commit | 44fc7c21df7ac184d4ad09d3a6b9daa2eb5d7dae (patch) | |
tree | b157e5b03c56978dd3d86908cf32cbf96e27d6f5 | |
parent | dc2d2c099383b5e10d74ffdcb8e26d784ed8bcd2 (diff) | |
download | ydb-44fc7c21df7ac184d4ad09d3a6b9daa2eb5d7dae.tar.gz |
[docs] merge two "Quick start" article versions
[docs] merge two "Quick start" article versions
Pull Request resolved: #190
-rw-r--r-- | .gitignore | 3 | ||||
-rw-r--r-- | ydb/docs/en/core/administration/quickstart.md | 346 | ||||
-rw-r--r-- | ydb/docs/en/core/getting_started/_assets/select-hello-world.png | bin | 0 -> 36452 bytes | |||
-rw-r--r-- | ydb/docs/en/core/getting_started/_assets/web-ui-home.png | bin | 0 -> 28180 bytes | |||
-rw-r--r-- | ydb/docs/en/core/getting_started/quickstart.md | 230 | ||||
-rw-r--r-- | ydb/docs/en/core/getting_started/toc_i.yaml | 2 | ||||
-rw-r--r-- | ydb/docs/en/core/index.yaml | 2 | ||||
-rw-r--r-- | ydb/docs/en/core/toc_i.yaml | 4 | ||||
-rw-r--r-- | ydb/docs/presets.yaml | 2 | ||||
-rw-r--r-- | ydb/docs/redirects.yaml | 6 | ||||
-rw-r--r-- | ydb/docs/ru/core/administration/quickstart.md | 346 | ||||
-rw-r--r-- | ydb/docs/ru/core/getting_started/_assets/select-hello-world.png | bin | 0 -> 36452 bytes | |||
-rw-r--r-- | ydb/docs/ru/core/getting_started/_assets/web-ui-home.png | bin | 0 -> 28180 bytes | |||
-rw-r--r-- | ydb/docs/ru/core/getting_started/quickstart.md | 231 | ||||
-rw-r--r-- | ydb/docs/ru/core/toc_i.yaml | 2 |
15 files changed, 474 insertions, 700 deletions
diff --git a/.gitignore b/.gitignore index 6508f71cbf..fbc13ecdfe 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,6 @@ __pycache__/ *_pb2.py *_pb2_grpc.py *_pb2.pyi + +# MacOS specific +.DS_Store diff --git a/ydb/docs/en/core/administration/quickstart.md b/ydb/docs/en/core/administration/quickstart.md index d98f527308..e69de29bb2 100644 --- a/ydb/docs/en/core/administration/quickstart.md +++ b/ydb/docs/en/core/administration/quickstart.md @@ -1,346 +0,0 @@ -# Getting started - -In this guide, you will [deploy](#install) a single-node local [{{ ydb-short-name }} cluster](../concepts/databases.md#cluster) and [execute](#queries) simple queries against your [database](../concepts/databases.md#database). - -## Deploy a {{ ydb-short-name }} cluster {#install} - -To deploy your {{ ydb-short-name }} cluster, use an archive with an executable or a Docker image. - -{% list tabs %} - -- Bin - - {% note info %} - - Currently, only a Linux build is supported. We'll add builds for Windows and macOS later. - - {% endnote %} - - 1. Create a working directory and change to it: - - ```bash - mkdir ~/ydbd && cd ~/ydbd - ``` - - 1. Download and run the installation script: - - ```bash - curl https://binaries.ydb.tech/local_scripts/install.sh | bash - ``` - - This will download and unpack the archive including the `idbd` executable, libraries, configuration files, and scripts needed to start and stop the cluster. - - 1. Start the cluster in one of the following storage modes: - - * In-memory data: - - ```bash - ./start.sh ram - ``` - - When data is stored in-memory, it is lost when the cluster is stopped. - - * Data on disk: - - ```bash - ./start.sh disk - ``` - - The first time you run the script, an 80GB `ydb.data` file will be created in the working directory. Make sure there's enough disk space to create it. - - Result: - - ```text - Starting storage process... - Initializing storage ... - Registering database ... - Starting database process... - - Database started. Connection options for YDB CLI: - - -e grpc://localhost:2136 -d /Root/test - ``` - -- Docker - - 1. Pull the current version of the Docker image: - - ```bash - docker pull {{ ydb_local_docker_image }}:{{ ydb_local_docker_image_tag }} - ``` - - Make sure that the pull operation was successful: - - ```bash - docker image list | grep {{ ydb_local_docker_image }} - ``` - - Result: - - ```text - cr.yandex/yc/yandex-docker-local-ydb latest c37f967f80d8 6 weeks ago 978MB - ``` - - 1. Run the Docker container: - - ```bash - docker run -d --rm --name ydb-local -h localhost \ - -p 2135:2135 -p 2136:2136 -p 8765:8765 \ - -v $(pwd)/ydb_certs:/ydb_certs -v $(pwd)/ydb_data:/ydb_data \ - -e YDB_DEFAULT_LOG_LEVEL=NOTICE \ - -e GRPC_TLS_PORT=2135 -e GRPC_PORT=2136 -e MON_PORT=8765 \ - {{ ydb_local_docker_image}}:{{ ydb_local_docker_image_tag }} - ``` - - If the container starts successfully, you'll see the container's ID. The container might take a few minutes to initialize. The database will not be available until the initialization completes. - -{% endlist %} - -## Connect to the DB {#connect} - -To connect to the YDB database, use the cluster's Embedded UI or the [{{ ydb-short-name }} CLI command-line interface](../reference/ydb-cli/index.md). - -{% list tabs %} - -- YDB UI - - 1. In your browser, open the page: - - ```http - http://localhost:8765 - ``` - - 1. Under **Database list**, select the database: - - * `/Root/test`: If you used an executable to deploy your cluster. - * `/local`: If you deployed your cluster from a Docker image. - -- YDB CLI - - 1. Install the {{ ydb-short-name }} CLI: - - * For Linux or macOS: - - ```bash - curl -sSL https://storage.yandexcloud.net/yandexcloud-ydb/install.sh | bash - ``` - - {% note info %} - - The script will update the `PATH` variable only if you run it in the bash or zsh command shell. If you run the script in a different shell, add the CLI path to the `PATH` variable yourself. - - {% endnote %} - - * For Windows: - - ```cmd - @"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -Command "iex ((New-Object System.Net.WebClient).DownloadString('https://storage.yandexcloud.net/yandexcloud-ydb/install.ps1'))" - ``` - - Specify whether to add the executable file path to the `PATH` environment variable: - - ```text - Add ydb installation dir to your PATH? [Y/n] - ``` - - {% note info %} - - Some {{ ydb-short-name }} CLI commands may use Unicode characters in their results. If these characters aren't displayed correctly in the Windows console, switch the encoding to UTF-8: - - ```cmd - chcp 65001 - ``` - - {% endnote %} - - To update the environment variables, restart the command shell session. - - 1. Save the DB connection parameters in the [{{ ydb-short-name }} CLI profile](../reference/ydb-cli/profile/index.md): - - ```bash - ydb config profile create quickstart --endpoint grpc://localhost:2136 --database <path_database> - ``` - - * `path_database`: Database path. Specify one of these values: - - * `/Root/test`: If you used an executable to deploy your cluster. - * `/local`: If you deployed your cluster from a Docker image. - - 1. Check your database connection: - - ```bash - ydb --profile quickstart scheme ls - ``` - - Result: - - ```text - .sys_health .sys - ``` - -{% endlist %} - -## Run queries against the database {#queries} - -Use the cluster's YDB Embedded UI or the [{{ ydb-short-name }} CLI](../reference/ydb-cli/index.md) to execute queries against the database. - -{% list tabs %} - -- YDB UI - - 1. Create tables in the database: - - Enter the query text under **Query**: - - {% include [create-tables](../_includes/create-tables.md) %} - - Click **Run Script**. - - 1. Populate the resulting tables with data: - - Enter the query text under **Query**: - - {% include [upsert](../_includes/upsert.md) %} - - Click **Run Script**. - - 1. Select data from the `series` table: - - Enter the query text under **Query**: - - {% include [upsert](../_includes/select.md) %} - - Click **Run Script**. - - You'll see the query result below: - - ```text - series_id series_title release_date - 1 IT Crowd 13182 - 2 Silicon Valley 16166 - ``` - - 1. Delete data from the `episodes` table. - - Enter the query text under **Query**: - - {% include [upsert](../_includes/delete.md) %} - - Click **Run Script**. - -- YDB CLI - - 1. Create tables in the database: - - Write the query text to the `create-table.sql` file: - - {% include [create-tables](../_includes/create-tables.md) %} - - Run the following query: - - ```bash - ydb --profile quickstart yql --file create-table.sql - ``` - - 1. Populate the resulting tables with data: - - Write the query text to the `upsert.sql` file: - - {% include [upsert](../_includes/upsert.md) %} - - Run the following query: - - ```bash - ydb --profile quickstart yql --file upsert.sql - ``` - - 1. Select data from the `series` table: - - Write the query text to the `select.sql` file: - - {% include [select](../_includes/select.md) %} - - Run the following query: - - ```bash - ydb --profile quickstart yql --file select.sql - ``` - - Result: - - ```text - ┌───────────┬──────────────────┬──────────────┐ - | series_id | series_title | release_date | - ├───────────┼──────────────────┼──────────────┤ - | 1 | "IT Crowd" | "2006-02-03" | - ├───────────┼──────────────────┼──────────────┤ - | 2 | "Silicon Valley" | "2014-04-06" | - └───────────┴──────────────────┴──────────────┘ - ``` - - 1. Delete data from the `episodes` table. - - Write the query text to the `delete.sql` file: - - {% include [delete](../_includes/delete.md) %} - - Run the following query: - - ```bash - ydb --profile quickstart yql --file delete.sql - ``` - - View the `episodes` table: - - ```bash - ydb --profile quickstart yql --script "SELECT * FROM episodes;" - ``` - - Result: - - ```text - ┌──────────────┬────────────┬───────────┬───────────┬──────────────────────────┐ - | air_date | episode_id | season_id | series_id | title | - ├──────────────┼────────────┼───────────┼───────────┼──────────────────────────┤ - | "2006-02-03" | 1 | 1 | 1 | "Yesterday's Jam" | - ├──────────────┼────────────┼───────────┼───────────┼──────────────────────────┤ - | "2006-02-03" | 2 | 1 | 1 | "Calamity Jen" | - ├──────────────┼────────────┼───────────┼───────────┼──────────────────────────┤ - | "2014-04-06" | 1 | 1 | 2 | "Minimum Viable Product" | - └──────────────┴────────────┴───────────┴───────────┴──────────────────────────┘ - ``` - - You've deleted The Cap Table series row from the table. - -{% endlist %} - -## Stop the cluster {#stop} - -Stop the {{ ydb-short-name }} cluster when done: - -{% list tabs %} - -- Bin - - To stop your cluster, change to the `~/ydbd` directory, then run this command: - - ```bash - ./stop.sh - ``` - -- Docker - - To stop the Docker container with the cluster, run this command: - - ```bash - docker kill ydb-local - ``` - -{% endlist %} - -## What's next {#advanced} - -* Read about [{{ ydb-short-name }} concepts](../concepts/index.md). -* Learn more about these and other methods of [{{ ydb-short-name }} deployment](../deploy/index.md). -* Find out how to access your {{ ydb-short-name }} databases over the [SDK](../reference/ydb-sdk/index.md). -* Learn more about the [YQL](../yql/reference/index.md) query language. diff --git a/ydb/docs/en/core/getting_started/_assets/select-hello-world.png b/ydb/docs/en/core/getting_started/_assets/select-hello-world.png Binary files differnew file mode 100644 index 0000000000..d4d1a2e000 --- /dev/null +++ b/ydb/docs/en/core/getting_started/_assets/select-hello-world.png diff --git a/ydb/docs/en/core/getting_started/_assets/web-ui-home.png b/ydb/docs/en/core/getting_started/_assets/web-ui-home.png Binary files differnew file mode 100644 index 0000000000..af6cd1dafa --- /dev/null +++ b/ydb/docs/en/core/getting_started/_assets/web-ui-home.png diff --git a/ydb/docs/en/core/getting_started/quickstart.md b/ydb/docs/en/core/getting_started/quickstart.md new file mode 100644 index 0000000000..91e2782f26 --- /dev/null +++ b/ydb/docs/en/core/getting_started/quickstart.md @@ -0,0 +1,230 @@ +# {{ ydb-short-name }} Quick Start + +In this guide, you will install a single-node local [{{ ydb-short-name }} cluster](../concepts/databases.md#cluster) and execute simple queries against your [database](../concepts/databases.md#database). + +Normally, {{ ydb-short-name }} stores data on multiple SSD/NVMe or HDD raw disk devices without any filesystem. However, for simplicity, this guide emulates disks in RAM or using a file in a regular filesystem. Thus, this setup is unsuitable for any production usage or even benchmarks. See the [cluster management documentation](../cluster/index.md) to learn how to run {{ ydb-short-name }} in a production environment. + +## Install and start {{ ydb-short-name }} {#install} + +{% list tabs %} + +- Linux x86_64 + + {% note info %} + + The recommended environment to run {{ ydb-short-name }} is x86_64 Linux. If you don't have access to one, feel free to switch to the instructions on the "Docker" tab. + + {% endnote %} + + 1. Create a directory for {{ ydb-short-name }} and use it as the current working directory: + + ```bash + mkdir ~/ydbd && cd ~/ydbd + ``` + + 2. Download and run the installation script: + + ```bash + curl https://binaries.ydb.tech/local_scripts/install.sh | bash + ``` + + This will download and unpack the archive containing the `ydbd` executable, libraries, configuration files, and scripts needed to start and stop the local cluster. + + The script is executed entirely with the current user privileges (notice the lack of `sudo`). Therefore, it can't do much on the system. You can check which exactly commands it runs by opening the same URL in your browser. + + 3. Start the cluster in one of the following storage modes: + + * In-memory data: + + ```bash + ./start.sh ram + ``` + + In this case, all data is stored only in RAM, it will be lost when the cluster is stopped. + + * Data on disk: + + ```bash + ./start.sh disk + ``` + + The first time you run the script, an 80GB `ydb.data` file will be created in the working directory. Make sure there's enough disk space to create it. This file will be used to emulate a raw disk device, which would have been used in production environments. + + Result: + + ```text + Starting storage process... + Initializing storage ... + Registering database ... + Starting database process... + + Database started. Connection options for YDB CLI: + + -e grpc://localhost:2136 -d /Root/test + ``` + +- Docker + + 1. Create a directory for {{ ydb-short-name }} and use it as the current working directory: + + ```bash + mkdir ~/ydbd && cd ~/ydbd + ``` + 2. Pull the current version of the Docker image: + + ```bash + docker pull {{ ydb_local_docker_image }}:{{ ydb_local_docker_image_tag }} + ``` + + 3. Run the Docker container: + + ```bash + docker run -d --rm --name ydb-local -h localhost \ + -p 2135:2135 -p 2136:2136 -p 8765:8765 \ + -v $(pwd)/ydb_certs:/ydb_certs -v $(pwd)/ydb_data:/ydb_data \ + -e GRPC_TLS_PORT=2135 -e GRPC_PORT=2136 -e MON_PORT=8765 \ + {{ ydb_local_docker_image}}:{{ ydb_local_docker_image_tag }} + ``` + + If the container starts successfully, you'll see the container's ID. The container might take a few minutes to initialize. The database will not be available until container initialization is complete. + +{% endlist %} + + +## Run your first "Hello, world!" query + +The simplest way to launch your first {{ ydb-short-name }} query is via the built-in web interface. It is launched by default on port 8765 of the {{ ydb-short-name }} server. If you have launched it locally, open [localhost:8765](http://localhost:8765) in your web browser. If not, replace `localhost` with your server's hostname in this URL or use `ssh -L 8765:localhost:8765 my-server-hostname-or-ip.example.com` to set up port forwarding and still open [localhost:8765](http://localhost:8765). You'll see a page like this: + +![Web UI home page](_assets/web-ui-home.png) + +{{ ydb-short-name }} is designed to be a multi-tenant system, with potentially thousands of users working with the same cluster simultaneously. Hence, most logical entities inside a {{ ydb-short-name }} cluster reside in a flexible hierarchical structure more akin to Unix's virtual filesystem rather than a fixed-depth schema you might be familiar with from other database management systems. As you can see, the first level of hierarchy consists of databases running inside a single {{ ydb-short-name }} process that might belong to different tenants. `/Root` is for system purposes, while `/Root/test` or `/local` (depending on the chosen installation method) is a playground created during installation in the previous step. Click on either `/Root/test` or `/local`, enter your first query, and hit the "Run" button: + +```sql +SELECT "Hello, world!"u; +``` + +The query returns the greeting, as it is supposed to: + +![SELECT "Hello, world!"u;](_assets/select-hello-world.png) + +{% note info %} + +Did you notice the odd `u` suffix? {{ ydb-short-name }} and its query language, YQL, are strongly typed. Regular strings in {{ ydb-short-name }} can contain any binary data, while this suffix indicates that this string literal is of the `Utf8` data type, which can only contain valid [UTF-8](https://en.wikipedia.org/wiki/UTF-8) sequences. [Learn more](../yql/reference/types/index.md) about {{ ydb-short-name }}'s type system. + +{% endnote %} + +The second simplest way to run a SQL query with {{ ydb-short-name }} is the [command line interface (CLI)](../reference/ydb-cli/index.md), while most real-world applications will likely communicate with {{ ydb-short-name }} via one of the available [software development kits (SDK)](../reference/ydb-sdk/index.md). Feel free to follow the rest of the guide using either the CLI or one of the SDKs instead of the web UI if you feel comfortable doing so. + +## Create your first table + +The main purpose of database management systems is to store data for later retrieval. As an SQL-based system, {{ ydb-short-name }}'s primary abstraction for data storage is a table. To create our first one, run the following query: + +```sql +CREATE TABLE example +( + key UInt64, + value String, + PRIMARY KEY (key) +); +``` + +As you can see, it is a simple key-value table. Let's walk through the query step-by-step: + +* Each SQL statement kind like `CREATE TABLE` has more detailed explanation in [YQL reference](../yql/reference/index.md). +* `example` is the table name identifier, while `key` and `value` are column name identifiers. It is recommended to use simple names for identifiers like these, but if you need one that contains non-trivial symbols, wrap the name in backticks. +* `UInt64` and `String` are data type names. `String` represents a binary string, and `UInt64` is a 64-bit unsigned integer. Thus, our example table stores string values identified by unsigned integer keys. More details [about data types](../yql/reference/types/index.md). +* `PRIMARY KEY` is one of the fundamental concepts of SQL that has a significant impact on both application logic and performance. Following the SQL standard, the primary key also implies an unique constraint, meaning the table cannot have multiple rows with equal primary keys. In this example table, it's quite straightforward which column should be chosen as the primary key, which we specify as `(key)` in round brackets after the respective keyword. In real-world scenarios, tables often have dozens of columns, and primary keys can be compound (consisting of multiple columns in a specified order), making choosing the right primary key more of an art. If you are interested in this topic, there's a [guide on choosing the primary key for maximizing performance](../best_practices/pk_scalability.md). YDB tables are required to have a primary key. + +## Add sample data + +Now let's fill our table with some data. The simplest way is to just use literals: + +```sql +INSERT INTO example (key, value) +VALUES (123, "hello"), + (321, "world"); +``` + +Step-by-step walkthrough: + +* `INSERT INTO` is the classic SQL statement for adding new rows to a table. However, it is not the most performant, as according to the SQL standard, it has to check whether the table already has rows with the given primary key values, and raise an error if they exist. Thus, if you run this query multiple times, all attempts except the first will return an error. If your application logic doesn't require this behavior, it is better to use `UPSERT INTO` instead of `INSERT INTO`. Upsert (which stands for "update or insert") will blindly write the provided values, overwriting existing rows if there were any. The rest of the syntax will be the same. +* `(key, value)` specifies the names of the columns we're inserting and their order. The values provided next need to match this specification, both in the number of columns and their data types. +* After the `VALUES` keyword, there's a list of tuples, each representing a table row. In this example, we have two rows identified by 123 and 321 in the `key` column, and "hello" and "world" values in the `value` column, respectively. + +To double-check that the rows were indeed added to the table, there's a common query that should return `2` in this case: + +```sql +SELECT COUNT(*) FROM example; +``` + +A few notable details in this one: + +* The `FROM` clause specifies a table to retrieve data from. +* `COUNT` is an aggregate function that counts the number of values. By default, when there are no other special clauses around, the presence of any aggregate function collapses the result to one row containing aggregates over the whole input data (the `example` table in this case). +* Asterisk `*` is a placeholder that normally means "all columns"; thus, `COUNT` will return the overall row count. + +Another common way to fill a table with data is by combining `INSERT INTO` (or `UPSERT INTO`) and `SELECT`. In this case, values to be stored are calculated inside the database instead of being provided by the client as literals. We'll use a slightly more realistic query to demonstrate this: + +```sql +$subquery = SELECT ListFromRange(1000, 10000) AS keys; + +UPSERT INTO example +SELECT + key, + CAST(RandomUuid(key) AS String) AS value +FROM $subquery +FLATTEN LIST BY keys AS key +``` + +There's quite a lot going on in this query; let's dig into it: + +* `$subquery` is a named expression. This syntax is YQL's extension to the SQL standard that allows making complex queries more readable. It behaves the same as if you wrote that first `SELECT` inline where `$subquery` is later used on the last row, but it allows comprehending what's going on piece by piece, like variables in regular programming languages. +* `ListFromRange` is a function that produces a list of consecutive integers, starting from the value provided in the first argument and ending with the value provided in the second argument. There's also a third optional argument that can allow skipping integers with a specified step, but we omit it in our example, which defaults to returning all integers in the given range. `List` is one of the most common [container data types](../yql/reference/types/containers.md). +* `AS` is a keyword used to give a name to the value we're returning from `SELECT`; in this example, `keys`. +* `FROM ... FLATTEN LIST BY ... AS ...` has a few notable things happening: + * Another `SELECT` used in the `FROM` clause is called a subquery. That's why we chose this name for our `$subquery` named expression, but we could have chosen something more meaningful to explain what it is. Subqueries normally aren't materialized; they just pass the output of one `SELECT` to the input of another on the fly. They can be used as a means to produce arbitrarily complex execution graphs, especially if used in conjunction with other YQL features. + * `FLATTEN LIST BY` clause modifies input passed via `FROM` in the following way: for each row in the input data, it takes a column of list data type and produces multiple rows according to the number of elements in that list. Normally, that list column is replaced by the column with the current single element, but the `AS` keyword in this context allows access to both the whole list (under the original name) and the current element (under the name specified after `AS`), or just to make it more clear what is what, like in this example. +* `RandomUuid` is a function that returns a pseudorandom [UUID version 4](https://datatracker.ietf.org/doc/html/rfc4122#section-4.4). Unlike most other functions, it doesn't actually use what is passed as an argument (the `key` column); instead, it indicates that we need to call the function on each row. See the [reference](../yql/reference/builtins/basic.md#random) for more examples of how this works. +* `CAST(... AS ...)` is a common function for converting values to a specified data type. In this context, the type specification is expected after `AS` (in this case, `String`), not an arbitrary name. +* `UPSERT INTO` will blindly write the values to the specified tables, as we discussed previously. Note that it didn't require `(key, value)` column names specification when used in conjunction with `SELECT`, as now columns can just be matched by names returned from `SELECT`. + +{% note info "Quick question!" %} + +What will the `SELECT COUNT(*) FROM example;` query return now? + +{% endnote %} + +## Stop the cluster {#stop} + +Stop the local {{ ydb-short-name }} cluster after you have finished experimenting: + +{% list tabs %} + +- Linux x86_64 + + To stop the local cluster, run the following command: + + ```bash + ~/ydbd/stop.sh + ``` + +- Docker + + To stop the Docker container with the local cluster, run the following command: + + ```bash + docker kill ydb-local + ``` + +{% endlist %} + +Optionally, you can then clean up your filesystem by removing your working directory with the `rm -rf ~/ydbd` command. All data inside the local {{ ydb-short-name }} cluster will be lost. + +## Done! What's next? + +After getting a hold of some basics demonstrated in this guide, you should be ready to jump into more advanced topics. Choose what looks the most relevant depending on your use case and role: + +* Walk through a more detailed [YQL tutorial](../yql/reference/) that focuses on writing queries. +* Try to build your first app storing data in {{ ydb-short-name }} using [one of the SDKs](../reference/ydb-sdk/index.md). +* Learn how to set up a [production-ready deployment of {{ ydb-short-name }}](../cluster/index.md). +* Read about [{{ ydb-short-name }} concepts](../concepts/index.md). diff --git a/ydb/docs/en/core/getting_started/toc_i.yaml b/ydb/docs/en/core/getting_started/toc_i.yaml index 982538b31f..3fd8345c18 100644 --- a/ydb/docs/en/core/getting_started/toc_i.yaml +++ b/ydb/docs/en/core/getting_started/toc_i.yaml @@ -1,4 +1,6 @@ items: +- name: Quick start + href: quickstart.md - name: Creating a database href: create_db.md - include: { mode: link, path: _includes/index/toc_network.yaml } diff --git a/ydb/docs/en/core/index.yaml b/ydb/docs/en/core/index.yaml index 4360315ba2..8eedeccc05 100644 --- a/ydb/docs/en/core/index.yaml +++ b/ydb/docs/en/core/index.yaml @@ -9,7 +9,7 @@ meta: links: - title: Getting started description: Deploy your cluster and perform basic operations with data - href: administration/quickstart + href: getting_started/quickstart - title: Concepts description: How YDB works, its features and available usage modes href: concepts/ diff --git a/ydb/docs/en/core/toc_i.yaml b/ydb/docs/en/core/toc_i.yaml index 80c66a5eb7..a04b1a7a90 100644 --- a/ydb/docs/en/core/toc_i.yaml +++ b/ydb/docs/en/core/toc_i.yaml @@ -2,8 +2,8 @@ items: # Header - name: Contents href: index.yaml -- name: Getting started - href: administration/quickstart.md +- name: Quick start + href: getting_started/quickstart.md # - name: Getting started # hidden: true # include: { mode: link, path: getting_started/toc_p.yaml } diff --git a/ydb/docs/presets.yaml b/ydb/docs/presets.yaml index 3f314c1de2..0139a588ea 100644 --- a/ydb/docs/presets.yaml +++ b/ydb/docs/presets.yaml @@ -31,7 +31,7 @@ default: objstorage-name: Object Storage ydb-cli: ydb k8s: Kubernetes - quickstart-path: ../../../../administration/quickstart.md#queries + quickstart-path: ../../../../getting_started/quickstart.md oss: true feature_not_null_for_pk: true ydb_non_deterministic_functions: true diff --git a/ydb/docs/redirects.yaml b/ydb/docs/redirects.yaml index 926114ccfb..b4b444a3cb 100644 --- a/ydb/docs/redirects.yaml +++ b/ydb/docs/redirects.yaml @@ -3,10 +3,10 @@ common: to: /reference/ydb-cli/table-ttl-reset.md - from: changelog.md to: changelog-server.md - - from: /getting_started/index.md - to: /administration/quickstart.md + - from: /administration/quickstart.md + to: /getting_started/quickstart.md - from: /getting_started/create_db.md - to: /administration/quickstart.md + to: /getting_started/quickstart.md - from: /getting_started/auth.md to: /concepts/auth.md - from: /getting_started/cli.md diff --git a/ydb/docs/ru/core/administration/quickstart.md b/ydb/docs/ru/core/administration/quickstart.md index 72f6d6e105..e69de29bb2 100644 --- a/ydb/docs/ru/core/administration/quickstart.md +++ b/ydb/docs/ru/core/administration/quickstart.md @@ -1,346 +0,0 @@ -# Начало работы - -В этой инструкции вы [развернете](#install) одноузловой локальный [кластер {{ ydb-short-name }}](../concepts/databases.md#cluster) и [выполните](#queries) простые запросы к [базе данных](../concepts/databases.md#database). - -## Разверните кластер {{ ydb-short-name }} {#install} - -Разверните кластер {{ ydb-short-name }} из архива с исполняемым файлом или используйте Docker-образ. - -{% list tabs %} - -- Bin - - {% note info %} - - В настоящее время поддерживается сборка только для Linux. Сборки для Windows и macOS будут добавлены позже. - - {% endnote %} - - 1. Создайте рабочую директорию и перейдите в нее: - - ```bash - mkdir ~/ydbd && cd ~/ydbd - ``` - - 1. Скачайте и запустите скрипт установки: - - ```bash - curl https://binaries.ydb.tech/local_scripts/install.sh | bash - ``` - - Будет загружен и распакован архив с исполняемым файлом `ydbd`, библиотеками, конфигурационными файлами, а также скриптами для запуска и остановки кластера. - - 1. Запустите кластер в одном из режимов хранения данных: - - * Данные в памяти: - - ```bash - ./start.sh ram - ``` - - При хранении данных в памяти остановка кластера приведет к их потере. - - * Данные на диске: - - ```bash - ./start.sh disk - ``` - - При первом запуске скрипта в рабочей директории будет создан файл `ydb.data` размером 80 ГБ. Убедитесь, что у вас есть достаточно свободного места для его создания. - - Результат: - - ```text - Starting storage process... - Initializing storage ... - Registering database ... - Starting database process... - - Database started. Connection options for YDB CLI: - - -e grpc://localhost:2136 -d /Root/test - ``` - -- Docker - - 1. Загрузите актуальную версию Docker-образа: - - ```bash - docker pull {{ ydb_local_docker_image }}:{{ ydb_local_docker_image_tag }} - ``` - - Убедитесь, что загрузка прошла успешно: - - ```bash - docker image list | grep {{ ydb_local_docker_image }} - ``` - - Результат: - - ```text - cr.yandex/yc/yandex-docker-local-ydb latest c37f967f80d8 6 weeks ago 978MB - ``` - - 1. Запустите Docker-контейнер: - - ```bash - docker run -d --rm --name ydb-local -h localhost \ - -p 2135:2135 -p 2136:2136 -p 8765:8765 \ - -v $(pwd)/ydb_certs:/ydb_certs -v $(pwd)/ydb_data:/ydb_data \ - -e YDB_DEFAULT_LOG_LEVEL=NOTICE \ - -e GRPC_TLS_PORT=2135 -e GRPC_PORT=2136 -e MON_PORT=8765 \ - {{ ydb_local_docker_image}}:{{ ydb_local_docker_image_tag }} - ``` - - При успешном запуске будет выведен идентификатор запущенного контейнера. Инициализация контейнера может занять несколько минут, до окончания инициализации база данных будет недоступна. - -{% endlist %} - -## Подключитесь к БД {#connect} - -Вы можете использовать для подключения к базе данных YDB Embedded UI кластера или [интерфейс командной строки {{ ydb-short-name }} CLI](../reference/ydb-cli/index.md). - -{% list tabs %} - -- YDB UI - - 1. Откройте в браузере страницу: - - ```http - http://localhost:8765 - ``` - - 1. В блоке **Database list** выберите базу данных: - - * `/Root/test` — если вы развернули кластер с помощью исполняемого файла; - * `/local` — если вы использовали Docker-образ. - -- YDB CLI - - 1. Установите {{ ydb-short-name }} CLI: - - * Для Linux или macOS: - - ```bash - curl -sSL https://storage.yandexcloud.net/yandexcloud-ydb/install.sh | bash - ``` - - {% note info %} - - Скрипт дополнит переменную `PATH`, только если его запустить в командной оболочке bash или zsh. Если вы запустили скрипт в другой оболочке, добавьте путь до CLI в переменную `PATH` самостоятельно. - - {% endnote %} - - * Для Windows: - - ```cmd - @"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -Command "iex ((New-Object System.Net.WebClient).DownloadString('https://storage.yandexcloud.net/yandexcloud-ydb/install.ps1'))" - ``` - - Укажите, нужно ли добавить путь к исполняемому в переменную окружения `PATH`: - - ```text - Add ydb installation dir to your PATH? [Y/n] - ``` - - {% note info %} - - {{ ydb-short-name }} CLI использует символы Юникода в выводе некоторых команд. При некорректном отображении таких символов в консоли Windows, переключите кодировку на UTF-8: - - ```cmd - chcp 65001 - ``` - - {% endnote %} - - Чтобы обновить переменные окружения, перезапустите сеанс командной оболочки. - - 1. Сохраните параметры соединения с БД в [профиле {{ ydb-short-name }} CLI](../reference/ydb-cli/profile/index.md): - - ```bash - ydb config profile create quickstart --endpoint grpc://localhost:2136 --database <path_database> - ``` - - * `path_database` — путь базы данных. Укажите одно из значений: - - * `/Root/test` — если вы развернули кластер с помощью исполняемого файла; - * `/local` — если вы использовали Docker-образ. - - 1. Проверьте подключение к БД: - - ```bash - ydb --profile quickstart scheme ls - ``` - - Результат: - - ```text - .sys_health .sys - ``` - -{% endlist %} - -## Выполните запросы к БД {#queries} - -Выполните запросы к базе данных используя YDB Embedded UI кластера или [интерфейс командной строки {{ ydb-short-name }} CLI](../reference/ydb-cli/index.md). - -{% list tabs %} - -- YDB UI - - 1. Создайте таблицы в базе данных: - - В блоке **Query** введите текст запроса: - - {% include [create-tables](../_includes/create-tables.md) %} - - Нажмите кнопку **Run Script**. - - 1. Добавьте данные в созданные таблицы: - - В блоке **Query** введите текст запроса: - - {% include [upsert](../_includes/upsert.md) %} - - Нажмите кнопку **Run Script**. - - 1. Выберите данных из таблицы `series`: - - В блоке **Query** введите текст запроса: - - {% include [upsert](../_includes/select.md) %} - - Нажмите кнопку **Run Script**. - - Ниже отобразится результат выполнения запроса: - - ```text - series_id series_title release_date - 1 IT Crowd 13182 - 2 Silicon Valley 16166 - ``` - - 1. Удалите данные из таблицы `episodes`: - - В блоке **Query** введите текст запроса: - - {% include [upsert](../_includes/delete.md) %} - - Нажмите кнопку **Run Script**. - -- YDB CLI - - 1. Создайте таблицы в базе данных: - - Сохраните текст запроса в файл `create-table.sql`: - - {% include [create-tables](../_includes/create-tables.md) %} - - Выполните запрос: - - ```bash - ydb --profile quickstart yql --file create-table.sql - ``` - - 1. Добавьте данные в созданные таблицы: - - Сохраните текст запроса в файл `upsert.sql`: - - {% include [upsert](../_includes/upsert.md) %} - - Выполните запрос: - - ```bash - ydb --profile quickstart yql --file upsert.sql - ``` - - 1. Выберите данных из таблицы `series`: - - Сохраните текст запроса в файл `select.sql`: - - {% include [select](../_includes/select.md) %} - - Выполните запрос: - - ```bash - ydb --profile quickstart yql --file select.sql - ``` - - Результат: - - ```text - ┌───────────┬──────────────────┬──────────────┐ - | series_id | series_title | release_date | - ├───────────┼──────────────────┼──────────────┤ - | 1 | "IT Crowd" | "2006-02-03" | - ├───────────┼──────────────────┼──────────────┤ - | 2 | "Silicon Valley" | "2014-04-06" | - └───────────┴──────────────────┴──────────────┘ - ``` - - 1. Удалите данные из таблицы `episodes`: - - Сохраните текст запроса в файл `delete.sql`: - - {% include [delete](../_includes/delete.md) %} - - Выполните запрос: - - ```bash - ydb --profile quickstart yql --file delete.sql - ``` - - Просмотрите таблицу `episodes`: - - ```bash - ydb --profile quickstart yql --script "SELECT * FROM episodes;" - ``` - - Результат: - - ```text - ┌──────────────┬────────────┬───────────┬───────────┬──────────────────────────┐ - | air_date | episode_id | season_id | series_id | title | - ├──────────────┼────────────┼───────────┼───────────┼──────────────────────────┤ - | "2006-02-03" | 1 | 1 | 1 | "Yesterday's Jam" | - ├──────────────┼────────────┼───────────┼───────────┼──────────────────────────┤ - | "2006-02-03" | 2 | 1 | 1 | "Calamity Jen" | - ├──────────────┼────────────┼───────────┼───────────┼──────────────────────────┤ - | "2014-04-06" | 1 | 1 | 2 | "Minimum Viable Product" | - └──────────────┴────────────┴───────────┴───────────┴──────────────────────────┘ - ``` - - Из таблицы удалена строка о сериале The Cap Table. - -{% endlist %} - -## Остановите кластер {#stop} - -По окончании работы остановите кластер {{ ydb-short-name }}. - -{% list tabs %} - -- Bin - - Чтобы остановить кластер, выполните команду в директории `~/ydbd`: - - ``` bash - ./stop.sh - ``` - -- Docker - - Чтобы остановить Docker-контейнер с кластером, выполните команду: - - ```bash - docker kill ydb-local - ``` - -{% endlist %} - -## Что дальше {#advanced} - -* Изучите [концепции {{ ydb-short-name }}](../concepts/index.md). -* Узнайте подробнее об этих и других способах [развертывания {{ ydb-short-name }}](../deploy/index.md). -* Посмотрите, как работать с БД {{ ydb-short-name }} при помощи [SDK](../reference/ydb-sdk/index.md). -* Ознакомьтесь с языком запросов [YQL](../yql/reference/index.md). diff --git a/ydb/docs/ru/core/getting_started/_assets/select-hello-world.png b/ydb/docs/ru/core/getting_started/_assets/select-hello-world.png Binary files differnew file mode 100644 index 0000000000..d4d1a2e000 --- /dev/null +++ b/ydb/docs/ru/core/getting_started/_assets/select-hello-world.png diff --git a/ydb/docs/ru/core/getting_started/_assets/web-ui-home.png b/ydb/docs/ru/core/getting_started/_assets/web-ui-home.png Binary files differnew file mode 100644 index 0000000000..af6cd1dafa --- /dev/null +++ b/ydb/docs/ru/core/getting_started/_assets/web-ui-home.png diff --git a/ydb/docs/ru/core/getting_started/quickstart.md b/ydb/docs/ru/core/getting_started/quickstart.md new file mode 100644 index 0000000000..55ac182b30 --- /dev/null +++ b/ydb/docs/ru/core/getting_started/quickstart.md @@ -0,0 +1,231 @@ +# {{ ydb-short-name }} Быстрый старт + +В этом руководстве вы установите одноузловой локальный [кластер {{ ydb-short-name }}](../concepts/databases.md#cluster) и выполните простые запросы к вашей [базе данных](../concepts/databases.md#database). + +Обычно {{ ydb-short-name }} хранит данные напрямую на нескольких дисковых устройствах SSD/NVMe или HDD без использования файловой системы. Однако для простоты данное руководство эмулирует диски в оперативной памяти или с использованием файла в обычной файловой системе. Таким образом, эта конфигурация не подходит для использования в промышленном окружении и даже для проведения тестов производительности. Ознакомьтесь с [документацией по управлению кластерами](../cluster/index.md) для запуска {{ ydb-short-name }} в промышленном окружении. + +## Установите и запустите {{ ydb-short-name }} {#install} + +{% list tabs %} + +- Linux x86_64 + + {% note info %} + + Рекомендуемая среда для запуска {{ ydb-short-name }} - это x86_64 Linux. Если у вас нет доступа к такой системе, можете переключиться на инструкции во вкладке "Docker". + + {% endnote %} + + 1. Создайте каталог для тестирования {{ ydb-short-name }} и используйте его в качестве текущего рабочего каталога: + + ```bash + mkdir ~/ydbd && cd ~/ydbd + ``` + + 2. Загрузите и запустите скрипт установки: + + ```bash + curl https://binaries.ydb.tech/local_scripts/install.sh | bash + ``` + + Это действие загрузит и распакует архив с исполняемым файлом `ydbd`, библиотеками, файлами конфигурации и скриптами, необходимыми для запуска и остановки локального кластера. + + Скрипт выполняется с текущими привилегиями пользователя (обратите внимание на отсутствие `sudo`). Таким образом, он не может сделать многого в системе. Чтобы проверить какие именно команды он выполняет — откройте этот же URL в вашем браузере. + + 3. Запустите кластер в одном из следующих режимов хранения данных: + + * Данные в оперативной памяти: + + ```bash + ./start.sh ram + ``` + + В этом случае все данные хранятся только в оперативной памяти, и они будут потеряны при остановке кластера. + + * Данные в файле на диске: + + ```bash + ./start.sh disk + ``` + + При первом запуске скрипта будет создан файл `ydb.data` размером 80 ГБ в рабочем каталоге. Убедитесь, что у вас достаточно свободного места на диске для его создания. Этот файл будет использоваться для эмуляции дискового устройства, которое использовалось бы в промышленном окружении. + + Результат: + + ```text + Starting storage process... + Initializing storage ... + Registering database ... + Starting database process... + + Database started. Connection options for YDB CLI: + + -e grpc://localhost:2136 -d /Root/test + ``` + +- Docker + + 1. Создайте каталог для тестирования {{ ydb-short-name }} и используйте его в качестве текущего рабочего каталога: + + ```bash + mkdir ~/ydbd && cd ~/ydbd + ``` + 2. Загрузите текущую версию Docker образа: + + ```bash + docker pull {{ ydb_local_docker_image }}:{{ ydb_local_docker_image_tag }} + ``` + + 3. Запустите Docker контейнер: + + ```bash + docker run -d --rm --name ydb-local -h localhost \ + -p 2135:2135 -p 2136:2136 -p 8765:8765 \ + -v $(pwd)/ydb_certs:/ydb_certs -v $(pwd)/ydb_data:/ydb_data \ + -e GRPC_TLS_PORT=2135 -e GRPC_PORT=2136 -e MON_PORT=8765 \ + {{ ydb_local_docker_image}}:{{ ydb_local_docker_image_tag }} + ``` + + Если контейнер успешно запустился, вы увидите его идентификатор. Контейнеру может потребоваться несколько минут для инициализации. База данных будет недоступна до окончания инициализации. + +{% endlist %} + + +## Запустите первый запрос "Hello, world!" + +Самый простой способ выполнить свой первый запрос к {{ ydb-short-name }} - это встроенный веб-интерфейс. Он запускается по умолчанию на порту 8765 сервера {{ ydb-short-name }}, поэтому, если вы запустили его локально, вам нужно открыть [localhost:8765](http://localhost:8765) в вашем веб-браузере. Если нет, замените `localhost` на имя хоста вашего сервера в этом URL, либо используйте `ssh -L 8765:localhost:8765 my-server-hostname-or-ip.example.com` для настройки проброса порта и все равно откройте [localhost:8765](http://localhost:8765). Вы увидите страницу подобного вида: + +![Стартовая страница веб-интерфейса](_assets/web-ui-home.png) + +{{ ydb-short-name }} спроектирован как многопользовательская система с возможностью одновременной работы тысяч пользователей с одним кластером. Как следствие, большинство логических сущностей внутри кластера {{ ydb-short-name }} находятся в гибкой иерархической структуре, больше похожей на виртуальную файловую систему Unix, чем на схему с фиксированной глубиной, с которой вы, возможно, знакомы из других систем управления базами данных. Как видите, первый уровень иерархии состоит из баз данных, работающих в одном процессе {{ ydb-short-name }}, которые могут принадлежать разным пользователям. `/Root` предназначена для системных целей, а `/Root/test` или `/local` (имя зависит от выбранного способа установки) - это «игровая площадка», созданная в процессе установки на предыдущем шаге. Давайте нажмём на последнюю, `/Root/test` или `/local`, затем введем наш первый запрос и нажмем кнопку запуска: + +```sql +SELECT "Hello, world!"u; +``` + +Запрос возвращает приветствие, как и задумано: + +![SELECT "Hello, world!"u;](_assets/select-hello-world.png) + +{% note info %} + +Заметили странный суффикс `u`? {{ ydb-short-name }} и её язык запросов YQL являются строго типизированными. Обычные строки в {{ ydb-short-name }} могут содержать любые двоичные данные, в то время как этот суффикс указывает, что этот литерал имеет тип данных `Utf8`, который может содержать только валидные последовательности [UTF-8](https://en.wikipedia.org/wiki/UTF-8). [Узнайте больше](../yql/reference/types/index.md) о системе типов {{ ydb-short-name }}. + +{% endnote %} + +Второй по простоте способ выполнения SQL-запроса с использованием {{ ydb-short-name }} - это [интерфейс командной строки (CLI)](../reference/ydb-cli/index.md). Большинство реальных приложений же, скорее всего, будут работать с {{ ydb-short-name }} через один из доступных [наборов инструментов для разработчиков программного обеспечения (SDK)](../reference/ydb-sdk/index.md). Если вы чувствуете себя уверенно — можете продолжить прохождение данного руководства с помощью одного из этих методов вместо веб-интерфейса. + +## Создайте свою первую таблицу + +Основная цель существования систем управления базами данных - сохранение данных для последующего извлечения. Как система, базирующаяся на SQL, основной абстракцией {{ ydb-short-name }} для хранения данных является таблица. Чтобы создать нашу первую таблицу, выполните следующий запрос: + +```sql +CREATE TABLE example +( + key UInt64, + value String, + PRIMARY KEY (key) +); +``` + +Как видите, это простая таблица ключ-значение. Давайте пройдемся по ней пошагово: + +* Каждый тип оператора SQL вроде `CREATE TABLE` имеет подробное описание в [справке по YQL](../yql/reference/index.md). +* `example` - это идентификатор имени таблицы, а `key` и `value` - идентификаторы имен столбцов. Рекомендуется использовать простые имена для таких идентификаторов, но если вам нужно использовать имя с необычными символами, оберните его в обратные кавычки. +* `UInt64` и `String` - это названия типов данных. `String` представляет собой двоичную строку, а `UInt64` - 64-разрядное беззнаковое целое число. Таким образом, наша таблица-пример хранит строковые значения, идентифицируемые беззнаковыми целочисленными ключами. Подробнее [о типах данных](../yql/reference/types/index.md). +* `PRIMARY KEY` - одно из основных понятий SQL, которое оказывает огромное влияние на логику приложения и производительность. В соответствии со стандартом SQL, первичный ключ также подразумевает ограничение уникальности, поэтому таблица не может иметь несколько строк с одинаковыми первичными ключами. В этой примерной таблице довольно просто определить, какой столбец пользователь должен выбрать в качестве первичного ключа, и мы указываем его как `(key)` в круглых скобках после соответствующего ключевого слова. В реальных сценариях таблицы часто содержат десятки столбцов, и первичные ключи могут быть составными (состоять из нескольких столбцов в указанном порядке), поэтому выбор правильного первичного ключа становится больше похожим на искусство. Если вас интересует эта тема, есть [руководство по выбору первичного ключа для максимизации производительности](../best_practices/pk_scalability.md). YDB таблицы обязаны иметь первичный ключ. + + +## Добавление тестовых данных + +Теперь давайте заполним нашу таблицу первыми данными. Самый простой способ - использовать литералы: + +```sql +INSERT INTO example (key, value) +VALUES (123, "hello"), + (321, "world"); +``` + +Пошаговое описание: + +* `INSERT INTO` - это классический оператор SQL для добавления новых строк в таблицу. Однако он не является наиболее производительным, так как согласно стандарту SQL он должен проверить, существуют ли в таблице строки с заданными значениями первичного ключа, и выдать ошибку, если они уже есть. Таким образом, если вы запустите этот запрос несколько раз, все попытки, кроме первой, вернут ошибку. Если логика вашего приложения не требует такого поведения, лучше использовать `UPSERT INTO` вместо `INSERT INTO`. Upsert (от "update or insert") будет безусловно записывать предоставленные значения, перезаписывая существующие строки, если они есть. Остальной синтаксис будет таким же. +* `(key, value)` указывает имена столбцов, которые мы вставляем, и их порядок. Предоставленные значения должны соответствовать этому описанию как по количеству столбцов, так и по их типам данных. +* После ключевого слова `VALUES` следует список кортежей, каждый из которых представляет собой строку таблицы. В этом примере у нас есть две строки, идентифицируемые числами 123 и 321 в столбце `key`, и значениями "hello" и "world" в столбце `value` соответственно. + +Чтобы убедиться, что строки были действительно добавлены в таблицу, существует распространённый запрос, который в данном случае должен вернуть `2`: + +```sql +SELECT COUNT(*) FROM example; +``` + +Несколько деталей в этом запросе: + +* Во `FROM` указывают таблицу, из которой извлекаются данные. +* `COUNT` - это агрегатная функция, подсчитывающая количество значений. По умолчанию, когда нет других специальных выражений вокруг, наличие любой агрегатной функции приводит к сворачиванию результата в одну строку, содержащую агрегаты по всему входным данным (таблице `example` в данном случае). +* Астериск `*` является спецсимволом, который обычно означает "все столбцы"; таким образом, `COUNT` вернет общее количество число строк. + +Еще один распространённый способ заполнить таблицу данными - это объединить операции `INSERT INTO` (или `UPSERT INTO`) и `SELECT`. В этом случае значения для сохранения вычисляются внутри базы данных, а не предоставляются клиентом в виде литералов. Для демонстрации этого подхода мы используем немного более реалистичный запрос: + +```sql +$subquery = SELECT ListFromRange(1000, 10000) AS keys; + +UPSERT INTO example +SELECT + key, + CAST(RandomUuid(key) AS String) AS value +FROM $subquery +FLATTEN LIST BY keys AS key +``` + +В этом запросе происходит немало интересного, давайте рассмотрим его подробнее: + +* `$subquery` - это именованное выражение. Этот синтаксис является расширением YQL по сравнению со стандартным SQL и позволяет делать более читаемые сложные запросы. Он работает так же, как если бы вы написали первый `SELECT` по месту, где `$subquery` используется в последней строке. Однако, использование именованных выражений позволяет легче понять, что происходит шаг за шагом, подобно переменным в обычных языках программирования. +* `ListFromRange` - это функция, которая создает список последовательных целых чисел, начиная с значения, указанного в первом аргументе, и заканчивая значением, указанным во втором аргументе. Также есть третий необязательный аргумент, который позволяет пропускать числа с указанным шагом, но мы не используем его в нашем примере — по умолчанию возвращаются все целые числа в указанном диапазоне. `List` является одним из наиболее распространенных [контейнерных типов данных](../yql/reference/types/containers.md). +* `AS` - это ключевое слово, используемое для задания имени значения, которое мы возвращаем из `SELECT`; в данном примере - `keys`. +* В части `FROM ... FLATTEN LIST BY ... AS ...` есть несколько значимых моментов: + * Другой `SELECT`, использованный в выражении `FROM`, называется подзапросом. Поэтому мы выбрали это имя для нашего именованного выражения `$subquery`, но мы могли бы выбрать что-то более значимое, чтобы объяснить, что это такое. Подзапросы обычно не материализуются; они просто передают вывод одного `SELECT` вводу другого на лету. Они могут использоваться в качестве средства для создания произвольно сложных графов выполнения, особенно в сочетании с другими возможностями YQL. + * Ключевая фраза `FLATTEN LIST BY` изменяет входные данные, передаваемые через `FROM`, следующим образом: для каждой строки во входных данных она берет столбец типа данных `List` и создает несколько строк в соответствии с количеством элементов в этом списке. Обычно этот столбец списка заменяется столбцом с текущим одиночным элементом, но ключевое слово `AS` в данном контексте позволяет получить доступ и ко всему списку (по исходному имени) и текущему элементу (по имени после `AS`). +* `RandomUuid` - это функция, которая возвращает псевдослучайный [UUID версии 4](https://datatracker.ietf.org/doc/html/rfc4122#section-4.4). В отличие от большинства других функций, она не использует значение своего аргумента (столбец `key`); вместо этого этот аргумент указывает на то, что нам нужно вызывать функцию для каждой строки. Смотрите [ссылку](../yql/reference/builtins/basic.md#random) с дополнительными примерами работы этой функции. +* `CAST(... AS ...)` - это часто используемая функция для преобразования значений в указанный тип данных. В этом контексте после `AS` ожидается указание типа данных (в данном случае `String`), а не произвольного имени. +* `UPSERT INTO` слепо записывает значения в указанные таблицы, как мы обсуждали ранее. При использовании в сочетании с `SELECT` он не требует явного указания имен столбцов `(key, value)`, так как столбцы теперь могут быть просто сопоставлены по именам, возвращённым из `SELECT`. + +{% note info "Короткий вопрос!" %} + +Что теперь вернёт запрос `SELECT COUNT(*) FROM example;`? + +{% endnote %} + +## Остановка кластера {#stop} + +Остановите локальный кластер {{ ydb-short-name }} после завершения экспериментов: + +{% list tabs %} + +- Linux x86_64 + + Чтобы остановить локальный кластер, выполните следующую команду: + + ```bash + ~/ydbd/stop.sh + ``` + +- Docker + + Чтобы остановить Docker контейнер с локальным кластером, выполните следующую команду: + + ```bash + docker kill ydb-local + ``` + +{% endlist %} + +При желании вы можете удалить вашу рабочую директорию с помощью команды `rm -rf ~/ydbd` для очистки файловой системы. Все данные внутри локального кластера {{ ydb-short-name }} будут потеряны. + +## Готово! Что дальше? + +После освоения базовых операций из этого руководства, пора переходить перейти к более глубоким темам. Выберите то, что кажется наиболее актуальным в зависимости от вашего сценария использования и роли: + +* Пройдите более подробный [курс по YQL](../yql/reference/), который сосредоточен на написании запросов. +* Попробуйте создать свое первое приложение для хранения данных в {{ ydb-short-name }} с использованием [одного из SDK](../reference/ydb-sdk/index.md). +* Узнайте, как настроить [развертывание {{ ydb-short-name }} в готовую к промышленной эксплуатации среду](../cluster/index.md). +* Почитайте об используемых в {{ ydb-short-name }} [концепциях](../concepts/index.md). diff --git a/ydb/docs/ru/core/toc_i.yaml b/ydb/docs/ru/core/toc_i.yaml index d7df6e3a06..f887a12b02 100644 --- a/ydb/docs/ru/core/toc_i.yaml +++ b/ydb/docs/ru/core/toc_i.yaml @@ -3,7 +3,7 @@ items: - name: Оглавление href: index.yaml - name: Начало работы - href: administration/quickstart.md + href: getting_started/quickstart.md # - name: Начало работы # hidden: true # include: { mode: link, path: getting_started/toc_p.yaml } |