Sync data from Kafka

更新时间:
复制 MD 格式

This topic describes how to sync real-time data from Message Queue for Apache Kafka to Alibaba Cloud ClickHouse.

Limitations

You can sync data only from Message Queue for Apache Kafka instances and self-managed Kafka clusters that are deployed on ECS instances.

Prerequisites

  • Alibaba Cloud ClickHouse:

    • A destination cluster is created. The cluster and the Message Queue for Apache Kafka instance must be in the same region and use the same VPC. For more information, see Create a cluster.

    • A database account is created for the destination cluster and has permissions to perform operations on the database. For more information, see Account management.

  • Message Queue for Apache Kafka:

Usage notes

  • The topic to which an Alibaba Cloud ClickHouse Kafka external table subscribes cannot have other consumers.

  • When you create a Kafka external table, a materialized view, and a local table, ensure that their field types match.

Procedure

This topic provides an example of how to sync data from Message Queue for Apache Kafka to a distributed table named kafka_table_distributed in the default database of an Alibaba Cloud ClickHouse Community-compatible Edition cluster.

Step 1: How it works

Alibaba Cloud ClickHouse syncs data from Kafka by using its built-in Kafka table engine and materialized view mechanism to enable real-time data consumption and storage. The data pipeline is as follows.

  • Kafka topic: The source data to sync.

  • Alibaba Cloud ClickHouse Kafka external table (a table that uses the Kafka table engine): Pulls source data from a specified Kafka topic.

  • Materialized view: Reads source data from the Kafka external table and inserts the data into a Alibaba Cloud ClickHouse local table.

  • Local table: Stores the synced data.

Step 2: Connect to Alibaba Cloud ClickHouse

For more information, see Connect to a ClickHouse cluster by using DMS.

Step 3: Create a Kafka external table

Alibaba Cloud ClickHouse uses its built-in Kafka table engine to pull source data from a specified Kafka topic. This table has the following characteristics:

  • By default, you cannot directly query a Kafka external table.

  • A Kafka external table only consumes Kafka data; it does not store it. You must use a materialized view to process the data and insert it into a destination table.

The syntax for creating the table is as follows:

Important

The field types in the Kafka external table must match the data types of the Kafka messages.

CREATE TABLE [IF NOT EXISTS] [db.]table_name [ON CLUSTER cluster]
(
    name1 [type1] [DEFAULT|MATERIALIZED|ALIAS expr1],
    name2 [type2] [DEFAULT|MATERIALIZED|ALIAS expr2],
    ...
) ENGINE = Kafka()
SETTINGS
    kafka_broker_list = 'host:port1,host:port2,host:port3',
    kafka_topic_list = 'topic_name1,topic_name2,...',
    kafka_group_name = 'group_name',
    kafka_format = 'data_format'[,]
    [kafka_row_delimiter = 'delimiter_symbol',]
    [kafka_num_consumers = N,]
    [kafka_thread_per_consumer = 1,]
    [kafka_max_block_size = 0,]
    [kafka_skip_broken_messages = N,]
    [kafka_commit_every_batch = 0,]
    [kafka_auto_offset_reset = N]

The following table describes the common parameters.

Parameter

Required

Description

kafka_broker_list

Yes

A comma-separated list of Kafka broker endpoints. For information about how to view endpoints, see View endpoints.

  • If you use Message Queue for Apache Kafka, Alibaba Cloud ClickHouse can resolve the corresponding domain names by default.

  • If you use a self-managed Kafka cluster, Alibaba Cloud ClickHouse supports connections through an IP address or a custom domain name in a specific format. The supported domain name rules are as follows:

    1. Domain names that end with .com.

    2. Domain names that end with .local and contain one of the following keywords: kafka, mysql, or rabbitmq.

kafka_topic_list

Yes

A comma-separated list of topic names. For more information, see Create a topic.

kafka_group_name

Yes

The name of the Kafka consumer group. For more information, see Create a group.

kafka_format

Yes

Alibaba Cloud ClickHouse supports multiple message body formats.

Note

For more information about the message body formats that Alibaba Cloud ClickHouse supports, see Formats for Input and Output Data.

kafka_row_delimiter

No

The character that separates rows. The default value is \n. You can set this parameter based on the actual delimiter used for data writes.

kafka_num_consumers

No

The number of consumers for a single table. The default value is 1.

Note
  1. If the throughput of a single consumer is insufficient, specify more consumers.

  2. The total number of consumers must not exceed the number of partitions in the topic, as each partition can be assigned to only one consumer.

kafka_thread_per_consumer

No

Specifies whether each consumer uses a dedicated thread to consume messages. The default value is 0. Valid values:

  1. 0: All consumers share one thread to consume data.

  2. 1: Each consumer starts an independent thread to consume data.

To improve consumption speed, see Kafka performance optimization.

kafka_max_block_size

No

The maximum size, in bytes, of a Kafka message batch. The default is 65536.

kafka_skip_broken_messages

No

The tolerance of the Kafka message parser for dirty data. The default value is 0. If you set kafka_skip_broken_messages=N, the engine skips N Kafka messages that cannot be parsed. One message is equivalent to one row of data.

kafka_commit_every_batch

No

Specifies whether to commit an offset to a Kafka broker for each batch. The default value is 0. Valid values:

  1. 0: The commit is performed only after a full data block is written.

  2. 1: The commit is performed after each batch is written.

kafka_auto_offset_reset

No

The starting offset from which to read Kafka data. Valid values:

  1. earliest (default): Reads data from the earliest offset.

  2. latest: Reads data from the latest offset.

Note

This parameter is not supported by Alibaba Cloud ClickHouse clusters with engine version 21.8.

For more information about the parameters, see Kafka.

Example statement:

CREATE TABLE default.kafka_src_table ON CLUSTER `default`
(-- Define the table structure fields
    id Int32,
    name String               
) ENGINE = Kafka()
SETTINGS
    kafka_broker_list = 'alikafka-post-cn-****-1-vpc.alikafka.aliyuncs.com:9092,alikafka-post-cn-****1-2-vpc.alikafka.aliyuncs.com:9092,alikafka-post-cn-****-3-vpc.alikafka.aliyuncs.com:9092',
    kafka_topic_list = 'testforCK',
    kafka_group_name = 'GroupForTestCK',
    kafka_format = 'CSV';

Step 4: Create the destination storage table

Select a table creation statement based on your cluster edition.

For an Enterprise Edition cluster, you need to create only a local table. For a Community-compatible Edition cluster, you may need to create a distributed table based on your environment and requirements. The following statements are examples. For more information about the CREATE TABLE syntax, see CREATE TABLE.

Enterprise Edition

CREATE TABLE default.kafka_table_local ON CLUSTER default (
  id Int32,
  name String
) ENGINE = MergeTree()
ORDER BY (id);

If executing this statement returns the ON CLUSTER is not allowed for Replicated database error, upgrade the engine version to resolve this issue. For more information about how to upgrade the version, see Upgrade the minor engine version.

Community-compatible Edition

The table engine differs for single-replica and double-replica clusters. Select the appropriate engine based on your replica type.

Important

When you create a table in a double-replica cluster, you must use a Replicated* table engine that supports data replication, such as ReplicatedMergeTree. If you use a non-Replicated table engine in a double-replica cluster, data cannot be replicated between replicas, which may cause data inconsistency.

Single-replica

  1. Create a local table.

    CREATE TABLE default.kafka_table_local ON CLUSTER default (
      id Int32,
      name String
    ) ENGINE = MergeTree()
    ORDER BY (id);
  2. (Optional) Create a distributed table.

    If you need to import files only into a local table, you can skip this step.

    If your cluster has multiple nodes, we recommend that you create a distributed table.

    CREATE TABLE kafka_table_distributed ON CLUSTER default AS default.kafka_table_local
    ENGINE = Distributed(default, default, kafka_table_local, id);

Double-replica

  1. Create a local table.

    CREATE TABLE default.kafka_table_local ON CLUSTER default (
      id Int32,
      name String
    ) ENGINE = ReplicatedMergeTree()
    ORDER BY (id);
  2. (Optional) Create a distributed table.

    If you need to import files only into a local table, you can skip this step.

    If your cluster has multiple nodes, we recommend that you create a distributed table.

    CREATE TABLE kafka_table_distributed ON CLUSTER default AS default.kafka_table_local
    ENGINE = Distributed(default, default, kafka_table_local, id);

Step 5: Create a materialized view

Alibaba Cloud ClickHouse uses a materialized view to read data from the Kafka external table and insert it into a Alibaba Cloud ClickHouse local table.

The syntax for creating a materialized view is as follows:

Important

Ensure the SELECT fields match the destination table's schema. Alternatively, you can use conversion functions to transform the data format to match the destination schema.

CREATE MATERIALIZED VIEW <view_name> ON CLUSTER default TO <dest_table> AS SELECT * FROM <src_table>;

The following table describes the parameters.

Parameter

Required

Description

Example

view_name

Yes

The name of the view.

consumer

dest_table

Yes

The table that stores the synced Kafka data.

  • Community-compatible Edition cluster:

    • For a multi-node cluster, we recommend that you import data to a distributed table.

    • If the destination is a local table, specify the local table.

  • Enterprise Edition cluster: An Enterprise Edition cluster does not have a distributed table. Specify the local table.

  • Community-compatible Edition example: kafka_table_distributed

  • Enterprise Edition example: kafka_table_local

src_table

Yes

The Kafka external table.

kafka_src_table

Example statements:

Enterprise Edition

CREATE MATERIALIZED VIEW consumer ON CLUSTER default TO kafka_table_local AS SELECT * FROM kafka_src_table;

Community-compatible Edition

This example stores source data in the kafka_table_distributed distributed table.

CREATE MATERIALIZED VIEW consumer ON CLUSTER default TO kafka_table_distributed AS SELECT * FROM kafka_src_table;

Step 6: Verify the data sync

  1. Send messages to the topic in Message Queue for Apache Kafka.

    1. Log on to the Message Queue for Apache Kafka console.

    2. On the Instances page, click the name of the destination instance.

    3. On the Topic Management page, find the destination topic and choose More > Experience Sending Message from the Actions column.

    4. In the Quickly Experience Message Sending and Receiving dialog box, enter the Message Content.

      This topic uses the messages 1,a and 2,b as examples.

    5. Click OK.

  2. Log on to Alibaba Cloud ClickHouse and query the distributed table to check whether the data is synced.

    For information about how to log on to Alibaba Cloud ClickHouse, see Connect to a ClickHouse cluster by using DMS.

    Use the following query statement to verify the data:

    Enterprise Edition

    SELECT * FROM kafka_table_local; 

    Community-compatible Edition

    The following statement provides an example of how to query a distributed table.

    • If the destination table is a local table, you must replace the distributed table name with the local table name in the query.

    • If you use a multi-node Community-compatible Edition cluster, we strongly recommend that you query the distributed table. If you query a local table directly, you will retrieve data from only one node, which can result in an incomplete dataset.

    SELECT * FROM kafka_table_distributed; 

    If the query returns a result, the data has been successfully synced from Kafka to Alibaba Cloud ClickHouse.

    The query result is as follows:

    ┌─id─┬─name─┐
    │  1 │  a   │
    │  2 │  b   │
    └────┴──────┘

    If the query returns an unexpected result, you can troubleshoot the issue by following the instructions in Step 7 (Optional): View the consumption status of the Kafka external table.

Step 7 (Optional): View consumption status

If the synced data is inconsistent with the Kafka data, you can query a system table to view the consumption status of the Kafka external table and troubleshoot message consumption exceptions.

Enterprise and community-compatible (v23.8 or later)

Query the system.kafka_consumers system table to view the consumption status of the Kafka external table. The query statement is as follows:

select * from system.kafka_consumers;

The following table describes the fields in the system.kafka_consumers table.

Field

Description

database

The database that contains the Kafka external table.

table

The name of the Kafka external table.

consumer_id

The Kafka consumer ID.

A table can have multiple consumers. The number of consumers is specified by the kafka_num_consumers parameter when you create a Kafka external table.

assignments.topic

The Kafka topic.

assignments.partition_id

The Kafka partition ID.

A partition can be assigned to only one consumer.

assignments.current_offset

The current offset.

exceptions.time

The timestamps when the last 10 exceptions occurred.

exceptions.text

The text of the last 10 exceptions.

last_poll_time

The timestamp of the last poll.

num_messages_read

The number of messages read by the consumer.

last_commit_time

The timestamp of the last commit.

num_commits

The total number of commits for the consumer.

last_rebalance_time

The timestamp of the last Kafka rebalance.

num_rebalance_revocations

The number of times partitions were revoked from the consumer.

num_rebalance_assignments

The number of times partitions were assigned to the consumer.

is_currently_used

Indicates whether the consumer is in use.

last_used

The last time the consumer was used, represented as a UNIX timestamp in microseconds.

rdkafka_stat

The internal statistics of the library. For more information, see librdkafka statistics.

The default value is 3000, which indicates that statistics are generated every 3 seconds.

Note

You can disable statistics collection for Kafka external tables in Alibaba Cloud ClickHouse by setting statistics_interval_ms=0.

Community-compatible (earlier than v23.8)

Query the system.kafka system table to view the consumption status of the Kafka external table. The query statement is as follows:

SELECT * FROM system.kafka;

The following table describes the fields in the system.kafka table.

Field

Description

database

The name of the database where the Kafka external table resides.

table

The name of the Kafka external table.

topic

The name of the topic that the Kafka external table consumes.

consumer_group

The name of the consumer group that the Kafka external table belongs to.

last_read_message_count

The number of messages read from the Kafka external table.

status

The message consumption status of the Kafka external table. Valid values:

  • no_view: No view is created for the Kafka external table.

  • attach_view: A view is created for the Kafka external table.

  • normal: The status is normal.

    When a Kafka external table consumes data, its consumption status is normal.

  • skip_parse: Parsing errors are skipped.

  • error: A consumption exception occurs.

exception

The details of the exception.

Note

If the status is error, this field contains the exception details.

FAQ