Exchanging data with Yandex Managed Service for ClickHouse®
With Yandex Data Processing, you can:
- Upload data from Managed Service for ClickHouse® to Spark DataFrame.
- Export data from Spark DataFrame to Managed Service for ClickHouse®.
If you no longer need the resources you created, delete them.
Required paid resources
The support cost for this solution includes:
- Yandex Data Processing cluster fee: Covers the use of VM computing resources, Compute Cloud network disks, and Cloud Logging for log management (see Yandex Data Processing pricing).
- Managed Service for ClickHouse® cluster fee: Covers the use of computational resources allocated to hosts (including ZooKeeper hosts) and disk space (see Managed Service for ClickHouse® pricing).
- Fee for a NAT gateway (see Virtual Private Cloud pricing).
- Fee for an Object Storage bucket: Covers data storage and bucket operations (see Object Storage pricing).
- Fee for public IP addresses assigned to cluster hosts (see Virtual Private Cloud pricing).
Getting started
Set up the infrastructure:
-
Create a service account named
dataproc-saand assign thedataproc.agentanddataproc.provisionerroles to it. -
In Object Storage, create buckets and configure access to them:
- Create a bucket for the input data and grant the
READpermission for this bucket to the cluster service account. - Create a bucket for the processing output and grant the cluster service account
READ and WRITEpermissions for this bucket.
- Create a bucket for the input data and grant the
-
Create a cloud network named
dataproc-network. -
Within the
dataproc-network, create a subnet in any availability zone. -
Set up a NAT gateway for your new subnet.
-
If you are using security groups, create one named
dataproc-sgin thedataproc-networkand add the following rules:-
One inbound and one outbound rule for service traffic:
- Port range:
0-65535 - Protocol:
Any(Any) - Source/Destination name:
Security group - Security group:
Current(Self)
- Port range:
-
Rule for outgoing HTTPS traffic:
- Port range:
443 - Protocol:
TCP - Destination name:
CIDR - CIDR blocks:
0.0.0.0/0
- Port range:
-
Egress rule to allow TCP access to ClickHouse® on port 8443:
- Port range:
8443 - Protocol:
TCP - Destination name:
CIDR - CIDR blocks:
0.0.0.0/0
- Port range:
-
-
Create a Yandex Data Processing cluster with the host configuration of your choice and the following settings:
- Components:
- SPARK
- YARN
- HDFS
- Service account:
dataproc-sa. - Bucket name: Bucket you created for the output data.
- Network:
dataproc-network. - Security groups:
dataproc-sg.
- Components:
-
Create a Managed Service for ClickHouse® cluster with your preferred configuration and the following settings:
- Public access to cluster hosts: Enabled.
- Database:
db1. - User:
user1.
-
If using security groups, make sure they are configured correctly and allow inbound connections to your Managed Service for ClickHouse® cluster.
-
If you do not have Terraform yet, install it.
-
Get the authentication credentials. You can add them to environment variables or specify them later in the provider configuration file.
-
Configure and initialize a provider. There is no need to create a provider configuration file manually, you can download it
. -
Place the configuration file in a separate working directory and specify the parameter values. If you did not add the authentication credentials to environment variables, specify them in the configuration file.
-
Download the data-proc-data-exchange-with-mch.tf
configuration file to your current working directory.This file describes:
- Network.
- Subnet.
- NAT gateway and route table for Yandex Data Processing.
- Security groups for the Yandex Data Processing and Managed Service for ClickHouse® clusters.
- Service account for the Yandex Data Processing cluster.
- Service account required to create buckets in Object Storage.
- Buckets for input and output data.
- Yandex Data Processing cluster.
- Managed Service for ClickHouse® cluster.
-
In the
data-proc-data-exchange-with-mch.tffile, specify the following:folder_id: Cloud folder ID matching the one in your provider settings.input_bucket: Input data bucket name.output_bucket: Output data bucket name.dp_ssh_key: Absolute path to the public key for the Yandex Data Processing cluster. Learn more about connecting to a Yandex Data Processing host over SSH here.ch_password: ClickHouse® user password.
-
Validate your Terraform configuration files using this command:
terraform validateTerraform will display any configuration errors detected in your files.
-
Create the required infrastructure:
-
Run this command to view the planned changes:
terraform planIf 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.
-
If everything looks correct, apply the changes:
-
Run this command:
terraform apply -
Confirm updating the resources.
-
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
. -
Export data from Managed Service for ClickHouse®
Create a table in the Managed Service for ClickHouse® cluster
-
Connect to the
db1database in the Managed Service for ClickHouse® cluster asuser1. -
Add test data to the database. In this example, we will use a simple table containing people's names and ages.
-
Create a table:
CREATE TABLE persons ( `name` String, `age` UInt8) ENGINE = MergeTree () ORDER BY `name`; -
Populate the table with data:
INSERT INTO persons VALUES ('Anna', 19), ('Michael', 65), ('Alvar', 28), ('Lilith', 50), ('Max', 27), ('Jaimey', 34), ('Dmitry', 42), ('Qiang', 19), ('Augustyna', 20), ('Maria', 28); -
Check the result:
SELECT * FROM persons;
-
Export the table from Managed Service for ClickHouse®
-
Prepare a script file:
-
Create a local file named
ch-to-dataproc.pyand copy the following script into it:ch-to-dataproc.py
from pyspark.sql import SparkSession # Creating a Spark session spark = SparkSession.builder.appName("ClickhouseDataproc").getOrCreate() # Specifying the port and other ClickHouse® cluster settings jdbcPort = 8443 jdbcHostname = "c-<ClickHouse®_cluster_ID>.rw.mdb.yandexcloud.net" jdbcDatabase = "db1" jdbcUrl = f"jdbc:clickhouse://{jdbcHostname}:{jdbcPort}/{jdbcDatabase}?ssl=true" # Transferring the persons table from ClickHouse® to DataFrame df = spark.read.format("jdbc") \ .option("url", jdbcUrl) \ .option("user","user1") \ .option("password","<user1_password>") \ .option("dbtable","persons") \ .load() # Transferring DataFrame to the bucket for validation df.repartition(1).write.mode("overwrite") \ .csv(path='s3a://<output_bucket_name>/csv', header=True, sep=',') -
In your script, specify the following:
- Managed Service for ClickHouse® cluster ID.
user1password.- Output bucket name.
-
In the input bucket, create a folder named
scriptsand upload thech-to-dataproc.pyfile to it.
-
-
Create a PySpark job with the file path to your script specified in the Main python file field:
s3a://<input_bucket_name>/scripts/ch-to-dataproc.py. -
Wait for the job to complete and verify that the output bucket's
csvfolder contains the exported table.
Note
You can view the job logs and search data in them using Yandex Cloud Logging. For more information, see Working with logs.
Import data to Managed Service for ClickHouse®
-
Prepare a script file:
-
Create a local file named
dataproc-to-ch.pyand copy the following script into it:dataproc-to-ch.py
from pyspark.sql import SparkSession from pyspark.sql.types import * # Creating a Spark session spark = SparkSession.builder.appName("DataprocClickhouse").getOrCreate() # Creating a data schema schema = StructType([StructField('name', StringType(), True), StructField('age', IntegerType(), True)]) # Creating DataFrame df = spark.createDataFrame([('Alim', 19), ('Fred' ,65), ('Guanmin' , 28), ('Till', 60), ('Almagul', 27), ('Mary', 34), ('Dmitry', 42)], schema) # Specifying the port and other ClickHouse® cluster settings jdbcPort = 8443 jdbcHostname = "c-<ClickHouse®_cluster_ID>.rw.mdb.yandexcloud.net" jdbcDatabase = "db1" jdbcUrl = f"jdbc:clickhouse://{jdbcHostname}:{jdbcPort}/{jdbcDatabase}?ssl=true" # Transferring DataFrame to ClickHouse® df.write.format("jdbc") \ .mode("error") \ .option("url", jdbcUrl) \ .option("dbtable", "people") \ .option("createTableOptions", "ENGINE = MergeTree() ORDER BY age") \ .option("user","user1") \ .option("password","<ClickHouse®_database_password>") \ .save() -
In your script, specify the following:
- Managed Service for ClickHouse® cluster ID.
user1password.
-
In the input bucket, create a folder named
scriptsand upload thedataproc-to-ch.pyfile to it.
-
-
Create a PySpark job with the file path to your script specified in the Main python file field:
s3a://<input_bucket_name>/scripts/dataproc-to-ch.py. -
Wait for the job to complete and verify that the data has been transferred to Managed Service for ClickHouse®:
-
Connect to the
db1database in the Managed Service for ClickHouse® cluster asuser1. -
Run this query:
SELECT * FROM people;
If the import is successful, the query will return the table contents.
-
Note
You can view the job logs and search data in them using Yandex Cloud Logging. For more information, see Working with logs.
Delete the resources you created
Some resources incur charges. To avoid unnecessary expenses, delete the resources you no longer need:
-
Delete all objects from the buckets. Delete other resources using the method matching their creation method:
ManuallyTerraform-
In the terminal window, go to the directory containing the infrastructure plan.
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.
-
Delete resources:
-
Run this command:
terraform destroy -
Confirm deleting the resources and wait for the operation to complete.
All the resources described in the Terraform manifests will be deleted.
-
-
ClickHouse® is a registered trademark of ClickHouse, Inc