Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get message by key from kafka topic

I try to get message by key from kafka. I found the only one solution is to use StateStore but I think it might be not a good idea. How to get message by key from kafka topic? Is it a good idea to use StateStore for this operation?

like image 337
Іван Гладуш Avatar asked Sep 05 '18 12:09

Іван Гладуш


People also ask

How do I query a message in Kafka topic?

The only fast way to search for a record in Kafka (to oversimplify) is by partition and offset. The new producer class can return, via futures, the partition and offset into which a message was written. You can use these two values to very quickly retrieve the message.

What is key-value in Kafka topic?

A key-value pair defined for a single Kafka Streams record. If the record comes directly from a Kafka topic then its key/value are defined as the message key/value.

How do I know if a Kafka topic has messages?

You can count the number of messages in a Kafka topic simply by consuming the entire topic and counting how many messages are read. To do this from the commandline you can use the kcat tool which can act as a consumer (and producer) and is built around the Unix philosophy of pipelines.


2 Answers

You can't "get messages by key from Kafka".

One solution, if practical, would be to have as many partitions as keys and always route messages for a key to the same partition.

like image 190
Gary Russell Avatar answered Oct 21 '22 20:10

Gary Russell


Every record written to Kafka can optionally have a key (but it doesn't have to!), the key can be accessed a number of ways:

Console consumer:

$ kafka-console-consumer --bootstrap-server <servername>:9092 --topic topicname --from-beginning --property print.key=true --property key.separator=:

kafkacat:

$ kafkacat -b <servername>:9092 -C -t topicname -o beginning -K :

Java Consumer API:

ConsumerRecord#key()

Kafka isn't indexed by key though, it's indexed by offset, and optionally by timestamp. If you need to lookup a key then you'll need to materialize the data to a system that's been designed to lookup by key: relational database, key value store, or some index. You can do this pretty easily with Kafka Connect, or if you'd like to build it into your service you could use the interactive queries feature of Kafka Streams.

like image 20
Chris Matta Avatar answered Oct 21 '22 20:10

Chris Matta