# Loading data from YDB to a ClickHouse® data mart

# Loading data from Yandex Managed Service for YDB to Yandex Managed Service for ClickHouse® using Yandex Data Transfer


Data Transfer enables you to transfer data from a database in Managed Service for YDB to a Managed Service for ClickHouse® cluster.

To transfer data:

1. [Prepare your test data](#prepare-data).
1. [Set up and activate the transfer](#prepare-transfer).
1. [Test your transfer](#verify-transfer).

If you no longer need the resources you created, [delete them](#clear-out).


## Required paid resources {#paid-resources}

* Managed Service for YDB database (see [Managed Service for YDB pricing](../../ydb/pricing/index.md)). Its cost depends on the deployment mode:

    * In serverless mode, you pay for data operations as well as the amount of stored data and backups.
    * In dedicated instance mode, you pay for the use of computing resources allocated to the database, storage size, and backups.

* Managed Service for ClickHouse® cluster, which includes computing resources allocated to hosts, storage and backup size (see [Managed Service for ClickHouse® pricing](../../managed-clickhouse/pricing.md)).
* Public IP addresses if public access is enabled for cluster hosts (see [Virtual Private Cloud pricing](../../vpc/pricing.md)).


## Getting started {#before-you-begin}

Set up your infrastructure:

{% list tabs group=instructions %}

- Manually {#manual}

    1. [Create a Managed Service for YDB database](../../ydb/operations/manage-databases.md) named `ydb1` of your preferred configuration.
    1. [Create a Managed Service for ClickHouse® cluster](../../managed-clickhouse/operations/cluster-create.md) of any suitable configuration with publicly accessible hosts and the following settings:

        * **DB name**: `db1`
        * **Username**: `user1`

        {% note info %}
        
        Public access to cluster hosts is required if you plan to connect to the cluster via the internet. This connection option is simpler and is recommended for the purposes of this guide. You can connect to non-public hosts as well but only from Yandex Cloud virtual machines located in the same cloud network as the cluster.
        
        {% endnote %}

    1. If using security groups, make sure they are configured correctly and allow connections to your [Managed Service for ClickHouse® cluster](../../managed-clickhouse/operations/connect/index.md#configuring-security-groups).

    
    1. [Create a service account](../../iam/operations/sa/create.md#create-sa) named `ydb-account` with the `ydb.editor` role. The transfer will use it to access the database.


- Using Terraform {#tf}

    1. If you do not have Terraform yet, [install it](../../tutorials/infrastructure-management/terraform-quickstart.md#install-terraform).
    1. [Get the authentication credentials](../../tutorials/infrastructure-management/terraform-quickstart.md#get-credentials). You can add them to environment variables or specify them later in the provider configuration file.
    1. [Configure and initialize a provider](../../tutorials/infrastructure-management/terraform-quickstart.md#configure-provider). There is no need to create a provider configuration file manually, you can [download it](https://github.com/yandex-cloud-examples/yc-terraform-provider-settings/blob/main/provider.tf).
    1. Place the configuration file in a separate working directory and [specify the parameter values](../../tutorials/infrastructure-management/terraform-quickstart.md#configure-provider). If you did not add the authentication credentials to environment variables, specify them in the configuration file.

    1. Download the [ydb-to-clickhouse.tf](https://github.com/yandex-cloud-examples/yc-data-transfer-from-ydb-to-clickhouse/blob/main/ydb-to-clickhouse.tf) configuration file to the same working directory.

        This file describes:

        * [Network](../../vpc/concepts/network.md#network).
        * [Subnet](../../vpc/concepts/network.md#subnet).
        * [Security group](../../vpc/concepts/security-groups.md) and rules for internet access to the Managed Service for ClickHouse® cluster.
        * Managed Service for YDB database.
        * Target Managed Service for ClickHouse® cluster.
        * Source endpoint.
        * Target endpoint.
        * Transfer.

    1. In the `ydb-to-clickhouse.tf` file, specify the following settings:

        * `mch_version`: ClickHouse® version.
        * `mch_password`: ClickHouse® database owner password.

    1. Validate your Terraform configuration files using this command:

        ```bash
        terraform validate
        ```

        Terraform will display any configuration errors detected in your files.

    1. Create the required infrastructure:

        1. Run this command to view the planned changes:
        
           ```bash
           terraform plan
           ```
        
           If you described the configuration correctly, the terminal will display a list of the resources to update and their parameters. This is a verification step that does not apply changes to your resources.
        
        1. If everything looks correct, apply the changes:
           1. Run this command:
        
              ```bash
              terraform apply
              ```
        
           1. Confirm updating the resources.
           1. Wait for the operation to complete.

        All the required resources will be created in the specified folder. You can check resource availability and their settings in the [management console](https://console.yandex.cloud).

{% endlist %}

## Prepare your test data {#prepare-data}

1. [Connect to the Managed Service for YDB database](../../ydb/operations/connection.md).
1. [Create a row-oriented table](../../ydb/operations/schema.md#create-table) named `table1` with the following columns:

    | Name | Type | Primary key |
    |:-------|:--------|:-------|
    | `Id`   | `Int64` | Yes     |
    | `Name` | `Utf8`  |        |

    You can create this table [using the following SQL query](../../ydb/operations/crud.md#web-sql):

    ```sql
    CREATE TABLE table1 (
        Id Int64,
        Name Utf8,
        PRIMARY KEY (Id)
    )
    ```

1. [Populate the table with data](../../ydb/operations/crud.md#change-data) using the following SQL query:

    ```sql
    INSERT INTO table1 (Id, Name)
    VALUES
        (1, "Anna"),
        (2, "Robert"),
        (3, "Umar"),
        (4, "Algul"),
        (5, "Viktor");
    ```

## Set up and activate the transfer {#prepare-transfer}

{% list tabs group=instructions %}

- Manually {#manual}

    1. [Create a source endpoint](../operations/endpoint/source/ydb.md#endpoint-settings) of the `YDB` type with the following database connection settings:

        * **Connection settings**:
            * **Database**: Select the Managed Service for YDB database from the list.

            
            * **Service account ID**: Select the `ydb-account` service account.


        * **Included paths list**: `table1`.

    1. [Create a target endpoint](../operations/endpoint/target/clickhouse.md#endpoint-settings) of the `ClickHouse®` type with the following cluster connection settings:

        * **Connection type**: `Managed cluster`.
        * **Managed cluster**: `<ClickHouse®_target_cluster_name>` from the drop-down list.
        * **Database**: `db1`.
        * **User**: `user1`.
        * **Password**: `<user_password>`.

    1. [Create a transfer](../operations/transfer.md#create) of the **_Snapshot and replication_** type that will use the endpoints you created.

    1. [Activate the transfer](../operations/transfer.md#activate) and wait for its status to change to **Replicating**.

- Using Terraform {#tf}

    1. In the `ydb-to-clickhouse.tf` file, set `transfer_enabled` to `1`.

    1. Validate your Terraform configuration files using this command:

        ```bash
        terraform validate
        ```

        Terraform will display any configuration errors detected in your files.

    1. Create the required infrastructure:

        1. Run this command to view the planned changes:
        
           ```bash
           terraform plan
           ```
        
           If you described the configuration correctly, the terminal will display a list of the resources to update and their parameters. This is a verification step that does not apply changes to your resources.
        
        1. If everything looks correct, apply the changes:
           1. Run this command:
        
              ```bash
              terraform apply
              ```
        
           1. Confirm updating the resources.
           1. Wait for the operation to complete.

        The transfer will be activated automatically upon creation.

{% endlist %}

## Test your transfer {#verify-transfer}

Make sure the transfer works correctly by testing copying and replication.

### Test copying {#verify-copy}

1. [Connect](../../managed-clickhouse/operations/connect/clients.md) to the `db1` database in the Managed Service for ClickHouse® target cluster.

1. Run this query:

    ```sql
    SELECT * FROM db1.table1;
    ```

    {% cut "Response example" %}

    ```sql
    # | Id  | Name     | __data_transfer_commit_time | __data_transfer_delete_time
    --+-----+----------+-----------------------------+----------------------------
    1 | "1" | "Anna"   | "1722023098109014844"       | "0"
    2 | "2" | "Robert" | "1722023098109014844"       | "0"
    3 | "3" | "Umar"   | "1722023098109014844"       | "0"
    4 | "4" | "Algul"  | "1722023098109014844"       | "0"
    5 | "5" | "Viktor" | "1722023098109014844"       | "0"
    ```

    {% endcut %}

### Test replication {#verify-replication}

1. [Connect to the Managed Service for YDB database](../../ydb/operations/connection.md).

1. [Add data to the table](../../ydb/operations/crud.md#change-data) named `table1`:

    ```sql
    INSERT INTO table1 (Id, Name)
    VALUES
        (6, "Maria"),
        (7, "Alex");
    ```

1. Check that the data has been replicated to the target database:

    1. [Connect](../../managed-clickhouse/operations/connect/clients.md) to the `db1` database in the Managed Service for ClickHouse® target cluster.

    1. Run this query:

        ```sql
        SELECT * FROM db1.table1;
        ```

        {% cut "Response example" %}

        ```sql
        # | Id  | Name     | __data_transfer_commit_time | __data_transfer_delete_time
        --+-----+----------+-----------------------------+----------------------------
        1 | "1" | "Anna"   | "1722023098109014844"       | "0"
        2 | "2" | "Robert" | "1722023098109014844"       | "0"
        3 | "3" | "Umar"   | "1722023098109014844"       | "0"
        4 | "4" | "Algul"  | "1722023098109014844"       | "0"
        5 | "5" | "Viktor" | "1722023098109014844"       | "0"
        6 | "6" | "Maria"  | "1722023655224000000"       | "0"
        7 | "7" | "Alex"   | "1722023655225000000"       | "0"
        ```

        {% endcut %}

## Delete the resources you created {#clear-out}

{% note info %}

Before deleting the resources, [deactivate the transfer](../operations/transfer.md#deactivate).

{% endnote %}

To reduce the consumption of resources, delete those you do not need:

{% list tabs group=instructions %}

- Manually {#manual}

    1. [Delete the transfer](../operations/transfer.md#delete).
    1. [Delete the source and target endpoints](../operations/endpoint/index.md#delete).
    1. [Delete the Managed Service for YDB database](../../ydb/operations/manage-databases.md#delete-db).
    1. [Delete the Managed Service for ClickHouse® cluster](../../managed-clickhouse/operations/cluster-delete.md).

    
    1. [Delete the service account](../../iam/operations/sa/delete.md).


- Using Terraform {#tf}

    1. In the terminal window, go to the directory containing the infrastructure plan.
    
        {% note warning %}
    
        Make sure the directory has no Terraform manifests with the resources you want to keep. Terraform deletes all resources that were created using the manifests in the current directory.
    
        {% endnote %}
    
    1. Delete resources:
    
        1. Run this command:
    
            ```bash
            terraform destroy
            ```
    
        1. Confirm deleting the resources and wait for the operation to complete.
    
        All the resources described in the Terraform manifests will be deleted.

{% endlist %}

_ClickHouse® is a registered trademark of [ClickHouse, Inc](https://clickhouse.com)._