This topic describes how to import data from Flink to a ClickHouse cluster.
Prerequisites
-
You have created a Flink cluster. For more information, see Create a cluster.
-
You have created a ClickHouse cluster. For more information, see Create a ClickHouse cluster.
Background information
For more information about Flink, see Apache Flink.
Code examples
The following sections provide code examples for stream and batch processing.
-
Stream processing
package com.company.packageName import java.util.concurrent.ThreadLocalRandom import scala.annotation.tailrec import org.apache.flink.api.common.typeinfo.Types import org.apache.flink.api.java.io.jdbc.JDBCAppendTableSink import org.apache.flink.streaming.api.scala._ import org.apache.flink.table.api.scala.{StreamTableEnvironment, table2RowDataStream} object StreamingJob { case class Test(id: Int, key1: String, value1: Boolean, key2: Long, value2: Double) private var dbName: String = "default" private var tableName: String = "" private var ckHost: String = "" private var ckPort: String = "8123" private var user: String = "default" private var password: String = "" def main(args: Array[String]) { parse(args.toList) checkArguments() // set up the streaming execution environment val env = StreamExecutionEnvironment.getExecutionEnvironment val tableEnv = StreamTableEnvironment.create(env) val insertIntoCkSql = s""" | INSERT INTO $tableName ( | id, key1, value1, key2, value2 | ) VALUES ( | ?, ?, ?, ?, ? | ) |""".stripMargin val jdbcUrl = s"jdbc:clickhouse://$ckHost:$ckPort/$dbName" println(s"jdbc url: $jdbcUrl") println(s"insert sql: $insertIntoCkSql") val sink = JDBCAppendTableSink .builder() .setDrivername("ru.yandex.clickhouse.ClickHouseDriver") .setDBUrl(jdbcUrl) .setUsername(user) .setPassword(password) .setQuery(insertIntoCkSql) .setBatchSize(1000) .setParameterTypes(Types.INT, Types.STRING, Types.BOOLEAN, Types.LONG, Types.DOUBLE) .build() val data: DataStream[Test] = env.fromCollection(1 to 1000).map(i => { val rand = ThreadLocalRandom.current() val randString = (0 until rand.nextInt(10, 20)) .map(_ => rand.nextLong()) .mkString("") Test(i, randString, rand.nextBoolean(), rand.nextLong(), rand.nextGaussian()) }) val table = table2RowDataStream(tableEnv.fromDataStream(data)) sink.emitDataStream(table.javaStream) // execute program env.execute("Flink Streaming Scala API Skeleton") } private def printUsageAndExit(exitCode: Int = 0): Unit = { println("Usage: flink run com.company.packageName.StreamingJob /path/to/flink-clickhouse-demo-1.0.0.jar [options]") println(" --dbName Sets the name of the ClickHouse database. Default: default.") println(" --tableName Sets the name of the table in the ClickHouse database.") println(" --ckHost Sets the IP address of the ClickHouse cluster.") println(" --ckPort Sets the port of the ClickHouse cluster. Default: 8123.") println(" --user Sets the username to access the ClickHouse cluster.") println(" --password Sets the password for the ClickHouse user.") System.exit(exitCode) } @tailrec private def parse(args: List[String]): Unit = args match { case ("--help" | "-h") :: _ => printUsageAndExit() case "--dbName" :: value :: tail => dbName = value parse(tail) case "--tableName" :: value :: tail => tableName = value parse(tail) case "--ckHost" :: value :: tail => ckHost = value parse(tail) case "--ckPort" :: value :: tail => ckPort = value parse(tail) case "--user" :: value :: tail => user = value parse(tail) case "--password" :: value :: tail => password = value parse(tail) case Nil => case _ => printUsageAndExit(1) } private def checkArguments(): Unit = { if ("".equals(tableName) || "".equals(ckHost)) { printUsageAndExit(2) } } } -
Batch processing
package com.company.packageName import java.util.concurrent.ThreadLocalRandom import scala.annotation.tailrec import org.apache.flink.Utils import org.apache.flink.api.common.typeinfo.Types import org.apache.flink.api.java.io.jdbc.JDBCAppendTableSink import org.apache.flink.api.scala._ import org.apache.flink.table.api.scala.{BatchTableEnvironment, table2RowDataSet} object BatchJob { case class Test(id: Int, key1: String, value1: Boolean, key2: Long, value2: Double) private var dbName: String = "default" private var tableName: String = "" private var ckHost: String = "" private var ckPort: String = "8123" private var user: String = "default" private var password: String = "" def main(args: Array[String]) { parse(args.toList) checkArguments() // set up the batch execution environment val env = ExecutionEnvironment.getExecutionEnvironment val tableEnv = BatchTableEnvironment.create(env) val insertIntoCkSql = s""" | INSERT INTO $tableName ( | id, key1, value1, key2, value2 | ) VALUES ( | ?, ?, ?, ?, ? | ) |""".stripMargin val jdbcUrl = s"jdbc:clickhouse://$ckHost:$ckPort/$dbName" println(s"jdbc url: $jdbcUrl") println(s"insert sql: $insertIntoCkSql") val sink = JDBCAppendTableSink .builder() .setDrivername("ru.yandex.clickhouse.ClickHouseDriver") .setDBUrl(jdbcUrl) .setUsername(user) .setPassword(password) .setQuery(insertIntoCkSql) .setBatchSize(1000) .setParameterTypes(Types.INT, Types.STRING, Types.BOOLEAN, Types.LONG, Types.DOUBLE) .build() val data = env.fromCollection(1 to 1000).map(i => { val rand = ThreadLocalRandom.current() val randString = (0 until rand.nextInt(10, 20)) .map(_ => rand.nextLong()) .mkString("") Test(i, randString, rand.nextBoolean(), rand.nextLong(), rand.nextGaussian()) }) val table = table2RowDataSet(tableEnv.fromDataSet(data)) sink.emitDataSet(Utils.convertScalaDatasetToJavaDataset(table)) // execute program env.execute("Flink Batch Scala API Skeleton") } private def printUsageAndExit(exitCode: Int = 0): Unit = { println("Usage: flink run com.company.packageName.StreamingJob /path/to/flink-clickhouse-demo-1.0.0.jar [options]") println(" --dbName Sets the name of the ClickHouse database. Default: default.") println(" --tableName Sets the name of the table in the ClickHouse database.") println(" --ckHost Sets the IP address of the ClickHouse cluster.") println(" --ckPort Sets the port of the ClickHouse cluster. Default: 8123.") println(" --user Sets the username to access the ClickHouse cluster.") println(" --password Sets the password for the ClickHouse user.") System.exit(exitCode) } @tailrec private def parse(args: List[String]): Unit = args match { case ("--help" | "-h") :: _ => printUsageAndExit() case "--dbName" :: value :: tail => dbName = value parse(tail) case "--tableName" :: value :: tail => tableName = value parse(tail) case "--ckHost" :: value :: tail => ckHost = value parse(tail) case "--ckPort" :: value :: tail => ckPort = value parse(tail) case "--user" :: value :: tail => user = value parse(tail) case "--password" :: value :: tail => password = value parse(tail) case Nil => case _ => printUsageAndExit(1) } private def checkArguments(): Unit = { if ("".equals(tableName) || "".equals(ckHost)) { printUsageAndExit(2) } } }
Procedure
Step 1: Create ClickHouse tables
-
Log on to the ClickHouse cluster using SSH. For more information, see Log on to a cluster.
-
Start the ClickHouse client:
clickhouse-client -h core-1-1 -mNoteThis example logs on to the
core-1-1node. If you have multiple core nodes, you can log on to any one of them. -
Create the database and tables.
-
Run the following command to create the database clickhouse_database_name.
CREATE DATABASE clickhouse_database_name ON CLUSTER cluster_emr;EMR on ECS automatically creates a cluster named
cluster_emrfor your ClickHouse cluster. You can specify a custom name for the database. -
Run the following command to create the clickhouse_table_name_local table.
CREATE TABLE clickhouse_database_name.clickhouse_table_name_local ON CLUSTER cluster_emr ( id UInt32, key1 String, value1 UInt8, key2 Int64, value2 Float64 ) ENGINE = ReplicatedMergeTree('/clickhouse/tables/{layer}-{shard}/clickhouse_database_name/clickhouse_table_name_local', '{replica}') ORDER BY id;NoteYou can customize the table name, but ensure that it ends with _local. layer, shard, and replica are macros that are automatically generated by Alibaba Cloud EMR for ClickHouse clusters and can be used directly.
-
Run the following command to create the table clickhouse_table_name_all with the same field definitions as the table clickhouse_table_name_local.
NoteYou can customize the table name, but the name must end with _all.
CREATE TABLE clickhouse_database_name.clickhouse_table_name_all ON CLUSTER cluster_emr ( id UInt32, key1 String, value1 UInt8, key2 Int64, value2 Float64 ) ENGINE = Distributed(cluster_emr, clickhouse_database_name, clickhouse_table_name_local, rand());
-
Step 2: Compile and package the code
-
Download and decompress the flink-clickhouse-demo.tgz sample package to your local machine.
-
In the Command Prompt, navigate to the directory that contains the pom.xml file, and run the following command to package the file.
mvn clean packageBased on the
artifactIdin your pom.xml file, the flink-clickhouse-demo-1.0.0.jar JAR file appears in the target directory.
Step 3: Submit the job
-
Log on to the Flink cluster via SSH. For more information, see Log on to a cluster.
-
Upload the packaged flink-clickhouse-demo-1.0.0.jar to the root directory of the Flink cluster.
NoteIn this example, flink-clickhouse-demo-1.0.0.jar is uploaded to the root directory. You can also customize the upload path.
-
Run the following command to submit the job.
The code example is as follows:
-
Stream processing job
flink run -m yarn-cluster \ -c com.aliyun.emr.StreamingJob \ flink-clickhouse-demo-1.0.0.jar \ --dbName clickhouse_database_name \ --tableName clickhouse_table_name_all \ --ckHost ${clickhouse_host} \ --password ${password}; -
Batch processing job
flink run -m yarn-cluster \ -c com.aliyun.emr.BatchJob \ flink-clickhouse-demo-1.0.0.jar \ --dbName clickhouse_database_name \ --tableName clickhouse_table_name_all \ --ckHost ${clickhouse_host} \ --password ${password};
Parameter
Description
dbName
The name of the ClickHouse cluster database, which defaults to
default. This topic uses clickhouse_database_name as an example.tableName
The name of the table in the ClickHouse cluster database. The example in this topic is clickhouse_table_name_all.
ckHost
The private or public IP address of the master node in the ClickHouse cluster. To obtain the IP address, see Get the IP address of the master node.
password
The password for the ClickHouse user.
You can obtain the password on the Configure page of the ClickHouse service from the users.default.password parameter.
On the configuration tab, select the server-users category to view this parameter.
-
Get master node IP address
-
Go to the Nodes page.
-
Log on to the EMR on ECS console.
-
In the top navigation bar, select the region and resource group.
-
On the EMR on ECS page, find the target cluster and click Nodes in the Actions column.
-
-
On the Nodes page, in the master node's row, click the
icon and copy the IP address from the Public IP Address column.