Read and resume a Kafka partition

This example reads ten messages from a fresh Kafka topic in three batches. The offset returned after each batch tells MatrixOne where to resume. Use one MySQL session for all the SQL below.

Start Kafka and MatrixOne. From the Kafka installation directory, create a topic with one partition and produce ten CSV messages:

bin/kafka-topics.sh --bootstrap-server 127.0.0.1:9092 --create --topic cookbook_orders --partitions 1 --replication-factor 1
seq 1 10 | awk '{print $1 ",item" $1}' | bin/kafka-console-producer.sh --bootstrap-server 127.0.0.1:9092 --topic cookbook_orders

The topic should be new, so its messages have offsets 0 through 9. Connect to MatrixOne with a MySQL client and create the external table:

CREATE DATABASE cookbook_kafka;
CREATE EXTERNAL TABLE cookbook_kafka.orders (id BIGINT, name VARCHAR(100))
ENGINE = KAFKA WITH (
  'brokers' = '127.0.0.1:9092',
  'topic' = 'cookbook_orders'
);

Read four messages from the beginning. __mo_read_start_id = -1 starts at the earliest offset. The query returns a count of 4 and offsets 0 through 3; LAST_KAFKA_MESSAGE_ID() then returns 3.

SELECT COUNT(*), MIN(__mo_message_id), MAX(__mo_message_id)
FROM cookbook_kafka.orders
WHERE __mo_read_start_id = -1 AND __mo_read_size = 4;
SELECT LAST_KAFKA_MESSAGE_ID();

Start the next read at offset 3. The start offset is exclusive, so this batch returns offsets 4 through 7 and the last message ID becomes 7.

SELECT COUNT(*), MIN(__mo_message_id), MAX(__mo_message_id)
FROM cookbook_kafka.orders
WHERE __mo_read_start_id = 3 AND __mo_read_size = 4;
SELECT LAST_KAFKA_MESSAGE_ID();

Pass the session’s last message ID directly into the next read. The final batch returns two messages at offsets 8 and 9; the last message ID becomes 9. If more messages arrive later, use 9 as the next start offset in the same way.

SELECT COUNT(*), MIN(__mo_message_id), MAX(__mo_message_id)
FROM cookbook_kafka.orders
WHERE __mo_read_start_id = LAST_KAFKA_MESSAGE_ID() AND __mo_read_timeout = 2;
SELECT LAST_KAFKA_MESSAGE_ID();
DROP DATABASE cookbook_kafka;

The matching MatrixOne Kafka integration test verifies the same three-batch offset sequence.