Kafka Connector
Overview
The Kafka connector is used to read data from or write data to DMS for Kafka (Topic). It is the most commonly used streaming data connector and supports exactly-once semantics.
| Category | Details |
|---|---|
| Supported type | Source table, result table, and data ingestion target |
| Running mode | Stream mode |
| Data format | For details, see Formats. |
| API type | SQL, DataStream |
| Whether result table can be updated or deleted | Result table data cannot be updated or deleted, but can be inserted. For details about data update and deletion, see Upsert-Kafka Connector. |
Application Scenarios
- Real-time data ingestion: Consumes messages from Kafka for stream processing and analysis.
- Data pipeline: Writes processed result data to Kafka for consumption by downstream systems.
- Event-driven architecture: Triggers real-time computing and responses based on Kafka messages.
- Data integration: Functions as a message broker between different systems to enable data transfer.
- CDC data capture: Works with the Debezium/Canal format to capture changed data.
Notes and Constraints
- Consumer offset committing behavior: If checkpointing is enabled, offsets are committed when the checkpoint completes. If checkpointing is disabled, offsets are automatically committed by the Kafka consumer.
- Topic must be created in advance for default data consumption.
Syntax Structure
CREATE TABLE {table_name} (
{column_name} {column_type},
...
) WITH (
'connector' = 'kafka',
'topic' = '{kafka_topic}',
'properties.bootstrap.servers' = '{broker_list}',
'properties.group.id' = '{consumer_group}',
'scan.startup.mode' = '{startup_mode}',
'format' = '{data_format}',
'{format_specific_param}' = '{value}'
); WITH Parameters
| Parameter | Mandatory | Type | Default Value | Value Range | Description |
|---|---|---|---|---|---|
| connector | Yes | String | None | kafka | Specifies that the connector type is Kafka. This parameter is mandatory and must be set to the fixed value kafka. The Flink runtime loads the corresponding Kafka Source/Sink factory class based on this value and declares the table as a Kafka data source or output table. |
| topic | Yes | String | None | Valid topic name | Specifies the name of the Kafka topic to be consumed. This parameter is mandatory for the source. Multiple topics separated by semicolons (for example, topic-a;topic-b) are supported. The Flink runtime assigns a subtask to each topic partition for parallel consumption, and partitions from multiple topics are merged and scheduled together. |
| properties.bootstrap.servers | Yes | String | None | Host:port list | Specifies the list of Kafka broker addresses. Use commas (,) to separate multiple addresses. This parameter is mandatory for both the source and sink. The Flink runtime uses this configuration to create a Kafka Consumer or Producer client connection. You are advised to configure multiple broker addresses to ensure high availability. |
| properties.group.id | No | String | None | Valid consumer group name | Specifies the ID of a Kafka consumer group. This parameter is mandatory for the source. The Flink runtime uses this group ID to identify the consumer. Consumers with the same group ID share the consumption progress of topic partitions. Different jobs must use different group IDs to avoid partition allocation conflicts. |
| scan.startup.mode | No | String | group-offsets | earliest-offset/latest-offset/group-offsets/specific-offsets/timestamp | Specifies the start position mode when the source is consumed for the first time. The default value is group-offsets.
The Flink runtime determines the initial consumer offset of the Kafka consumer based on this mode, which affects the data read start point when the job starts. |
| scan.startup.specific-offsets | No | String | None | Partition:offset list | Specifies the start offset of each partition. This parameter takes effect only when scan.startup.mode is set to specific-offsets. The format is partition:offset,partition:offset. The Flink runtime sets the initial offset of each partition of the Kafka consumer to the specified position. For partitions that have not been consumed, data is read from the specified offset. |
| scan.startup.timestamp-millis | No | Long | None | Timestamp in milliseconds | Specifies the start timestamp of consumption, in milliseconds. This parameter takes effect only when scan.startup.mode is set to timestamp. The Flink runtime sets the starting offset of the Kafka consumer to the first message whose timestamp is not earlier than the specified timestamp. This is used to resume data consumption from a specific point in time. |
| format | Yes | String | None | json/csv/avro/debezium-json/canal-json/raw | Specifies the deserialization format of messages. This parameter is mandatory for both the source and sink. The Flink runtime loads the corresponding format factory class based on this value to convert between the Kafka message byte stream and Flink table row data. |
| scan.topic-partition-discovery.interval | No | Duration | 5 min | Valid duration, for example, 30 seconds or 5 minutes. | Specifies the check interval for dynamic partition discovery. After this parameter is set, newly added partitions in a topic can be automatically discovered without restarting the job. The Flink runtime starts a background thread to periodically query the topic metadata at this interval. When a new partition is discovered, it is automatically assigned to an idle subtask for consumption. |
| properties.* | No | String | - | Kafka consumer configuration | Any configuration parameter passed to the Kafka consumer, prefixed with properties.. After removing the properties. prefix, the configuration item name is directly passed through to the Kafka consumer. The Flink runtime passes these parameters as-is when creating the Kafka client, which can be used to adjust consumption behavior (such as fetch.min.bytes, max.poll.records, etc.). |
| Parameter | Mandatory | Type | Default Value | Value Range | Description |
|---|---|---|---|---|---|
| connector | Yes | String | None | kafka | Specifies that the connector type is Kafka. This parameter is mandatory and must be set to the fixed value kafka. The Flink runtime loads the corresponding Kafka Source/Sink factory class based on this value and declares the table as a Kafka data source or output table. |
| topic | Yes | String | None | Valid topic name | Specifies the name of the Kafka topic to which data is written. This parameter is mandatory for the sink. When Flink is running, all output records are sent to the topic. If the topic does not exist, you need to create the topic in advance or enable the function of automatically creating a topic in Kafka. |
| properties.bootstrap.servers | Yes | String | None | Host:port list | Specifies the list of Kafka broker addresses. Use commas (,) to separate multiple addresses. This parameter is mandatory for both the source and sink. The Flink runtime uses this configuration to create a Kafka Consumer or Producer client connection. You are advised to configure multiple broker addresses to ensure high availability. |
| format | Yes | String | None | json/csv/avro/debezium-json/canal-json/raw | Specifies the serialization format of messages. This parameter is mandatory for the sink. When Flink is running, it serializes the row data in the Flink table into byte streams in the corresponding format and writes the data to Kafka based on the value of this parameter. |
| sink.partitioner | No | String | default | default/fixed/round-robin/fully qualified name of a custom class | Specifies the partitioning policy for writing data to Kafka. The default value is default. The default policy partitions data by key hash (or uses round-robin if there is no key). The fixed policy writes data to a fixed partition for each sink subtask. The round-robin policy distributes data across all partitions in a round-robin manner. The Flink runtime determines the Kafka partition to which each record is sent based on this policy, affecting the data distribution balance across partitions. |
| sink.semantic | No | String | at-least-once | at-least-once/exactly-once/none | Specifies the semantic guarantee level for the write operation. The default value is at-least-once. If set to exactly-once, the Flink Checkpoint mechanism must be enabled. In at-least-once mode, the Flink runtime immediately commits each record. In exactly-once mode, Kafka transactions are used to commit data only after a checkpoint is complete, ensuring no duplicate data but increasing latency. |
| properties.* | No | String | - | Kafka producer configuration | Any configuration parameter passed to the Kafka producer, prefixed with properties.. After removing the properties. prefix, the configuration item name is directly passed through to the Kafka producer. The Flink runtime passes these parameters as-is when creating the Kafka producer, which can be used to adjust production behavior (such as batch.size, linger.ms, etc.). |
Format parameters
The following are common format-related parameters. They take effect after the format is specified using the format parameter.
JSON format parameters
| Parameter | Mandatory | Type | Default Value | Value Range | Description |
|---|---|---|---|---|---|
| json.fail-on-missing-field | No | Boolean | false | true/false | Specifies whether to report an error when a field defined in the DDL is missing in the JSON message. The default value is false. If set to true, an exception is thrown when a missing field is encountered, causing the job to fail. If set to false, the missing field is set to null and processing continues. The Flink runtime checks each field during deserialization. This parameter determines the fault tolerance policy when a field is missing. |
| json.ignore-parse-errors | No | Boolean | false | true/false | Specifies whether to ignore JSON parsing errors. The default value is false. If set to true, the field is skipped instead of reporting an error when a parsing error occurs. This improves fault tolerance but may cause data loss. When an exception occurs during deserialization, the true mode sets the abnormal field to null and continues processing subsequent fields. The false mode directly throws an exception to terminate the job. |
| json.timestamp-format.standard | No | String | SQL | SQL/ISO-8601 | Specifies the parsing format standard for the timestamp type. The default value is SQL. The SQL format is parsed as yyyy-MM-dd HH:mm:ss.S, and the ISO-8601 format is parsed as yyyy-MM-dd'T'HH:mm:ss.S. The Flink runtime selects the corresponding parser based on this standard, which affects the conversion rules between timestamp strings in JSON and the Flink TIMESTAMP type. |
| json.map-null-key.mode | No | String | FAIL | FAIL/DROP/LITERAL | Specifies how null keys in the Map type are handled. The default value is FAIL. FAIL throws an exception when a null key is encountered; DROP discards the key-value pair of the null key; LITERAL replaces the null key with a specified string. When serializing Map data, the Flink runtime processes null keys according to this policy, which affects the output behavior of Map data containing null keys. |
| json.map-null-key.literal | No | String | "null" | Any string | Specifies the replacement string for the null key when json.map-null-key.mode is set to LITERAL. This parameter takes effect only when json.map-null-key.mode is set to LITERAL. When the Flink runtime serializes Map data, it replaces the null key with the string value specified by this parameter for output. |
CSV format parameters
| Parameter | Mandatory | Type | Default Value | Value Range | Description |
|---|---|---|---|---|---|
| csv.field-delimiter | No | String | , | Single character | Specifies the delimiter of CSV fields. The default value is a comma (,). Only a single character is supported. The Flink runtime uses this delimiter to split or concatenate field values in CSV records. |
| csv.disable-quote-character | No | Boolean | false | true/false | Specifies whether to disable the quotation character. The default value is false. If this parameter is set to true, the quotation character is treated as a common character. When the Flink runtime parses CSV, field values that contain delimiters are no longer protected by quotation marks, which may cause field parsing errors. |
| csv.quote-character | No | String | " | Single character | Specifies the quotation character in the CSV file, which is used to enclose field values that contain delimiters. The default value is double quotation marks ("). This parameter takes effect only when csv.disable-quote-character is set to false. When the Flink runtime parses and generates CSV, it uses this character to identify and enclose field values that contain delimiters or newline characters. |
| csv.allow-comments | No | Boolean | false | true/false | Specifies whether the CSV file can contain comment lines (starting with #). The default value is false. If set to true, lines starting with # are skipped. When the Flink runtime parses CSV records, lines starting with # are treated as comments and ignored, and are not processed as data records. |
| csv.ignore-parse-errors | No | Boolean | false | true/false | Specifies whether to ignore CSV parsing errors. The default value is false. If set to true, fields that encounter parsing errors are set to null and processing continues. When the Flink runtime encounters a format exception during deserialization, in true mode, it skips the erroneous field and continues processing subsequent fields; in false mode, it directly throws an exception and terminates the job. |
| csv.array-element-delimiter | No | String | ; | Any string | Specifies the delimiter for array elements. The default value is a semicolon (;). When the Flink runtime parses and generates array-type fields in CSV, this delimiter is used to split or concatenate array elements. |
Avro format parameters
| Parameter | Mandatory | Type | Default Value | Value Range | Description |
|---|---|---|---|---|---|
| encoding | No | String | binary | binary/json | Specifies the encoding format of Avro. binary indicates binary encoding, and json indicates JSON encoding. The Flink runtime selects the serialization/deserialization method for binary data based on this value. Binary encoding is more compact and efficient, while JSON encoding offers better readability. |
Usage Example
- Example 1: Consume JSON messages from a Kafka topic with the simplest configuration.
-- Create a Kafka source table. CREATE TABLE kafka_source ( user_id BIGINT, event_type STRING, event_time TIMESTAMP(3) ) WITH ( 'connector' = 'kafka', 'topic' = 'user-events', 'properties.bootstrap.servers' = 'kafka-broker:9092', 'properties.group.id' = 'flink-consumer-group', 'scan.startup.mode' = 'latest-offset', 'format' = 'json' ); -- Create the Print result table. CREATE TABLE print_sink ( user_id BIGINT, event_type STRING, event_time TIMESTAMP(3) ) WITH ( 'connector' = 'print' ); -- Submit the job. INSERT INTO print_sink SELECT user_id, event_type, event_time FROM kafka_source;
- Example 2: Start consuming from the earliest offset of the Kafka topic. This is suitable for scenarios requiring full data replay.
-- Create a Kafka source table (start consuming from the earliest offset). CREATE TABLE kafka_source_earliest ( order_id STRING, amount DECIMAL(10, 2), order_time TIMESTAMP(3) ) WITH ( 'connector' = 'kafka', 'topic' = 'orders', 'properties.bootstrap.servers' = 'kafka-broker:9092', 'properties.group.id' = 'order-consumer', 'scan.startup.mode' = 'earliest-offset', 'format' = 'json' ); -- Create the Print result table. CREATE TABLE print_sink ( order_id STRING, amount DECIMAL(10, 2), order_time TIMESTAMP(3) ) WITH ( 'connector' = 'print' ); -- Submit the job. INSERT INTO print_sink SELECT order_id, amount, order_time FROM kafka_source_earliest;
- Example 3: Start consuming data from a specified timestamp. This is suitable for scenarios where data processing needs to be resumed from a specific point in time.
-- Create a Kafka source table (start consuming from a specified timestamp). CREATE TABLE kafka_source_timestamp ( log_id STRING, log_level STRING, message STRING, log_time TIMESTAMP(3) ) WITH ( 'connector' = 'kafka', 'topic' = 'application-logs', 'properties.bootstrap.servers' = 'kafka-broker:9092', 'properties.group.id' = 'log-consumer', 'scan.startup.mode' = 'timestamp', 'scan.startup.timestamp-millis' = '1704067200000', 'format' = 'json' ); -- Create the Print result table. CREATE TABLE print_sink ( log_id STRING, log_level STRING, message STRING, log_time TIMESTAMP(3) ) WITH ( 'connector' = 'print' ); -- Submit the job. INSERT INTO print_sink SELECT log_id, log_level, message, log_time FROM kafka_source_timestamp;
- Example 4: Consume Kafka messages in CSV format with a custom field delimiter.
-- Create a Kafka source table in CSV format. CREATE TABLE kafka_csv_source ( id INT, name STRING, score DOUBLE ) WITH ( 'connector' = 'kafka', 'topic' = 'csv-data', 'properties.bootstrap.servers' = 'kafka-broker:9092', 'properties.group.id' = 'csv-consumer', 'scan.startup.mode' = 'latest-offset', 'format' = 'csv', 'csv.field-delimiter' = '|' ); -- Create the Print result table. CREATE TABLE print_sink ( id INT, name STRING, score DOUBLE ) WITH ( 'connector' = 'print' ); -- Submit the job. INSERT INTO print_sink SELECT id, name, score FROM kafka_csv_source;
What is your overall rating for this page?
Thank you very much for your feedback. We will continue working to improve the documentation.See the reply and handling status in My Cloud VOC.
For any further questions, feel free to contact us through the chatbot.
Chatbot