kafka-python icon indicating copy to clipboard operation
kafka-python copied to clipboard

Read from specific offsets

Open kashifusmani opened this issue 10 years ago • 7 comments

Using kafka-python, is it possible to read a specific range of offsets for given partition(s)? I looked through the documentation of the available consumers at http://kafka-python.readthedocs.org/en/1.0.0/apidoc/kafka.consumer.html but could not find anything that would let me do that.

kashifusmani avatar Apr 13 '16 23:04 kashifusmani

How about:

consumer = KafkaConsumer()
partition = TopicPartition('foo', 0)
start = 1234
end = 2345
consumer.assign([partition])
consumer.seek(partition, start)
for msg in consumer:
    if msg.offset > end:
        break
    else:
        print msg

dpkp avatar Apr 14 '16 00:04 dpkp

That works. Thanks! For anyone trying the above code sample, don't specify the topic name in KafkaConsumer constructor as it will call subscribe() which is incompatible with assign()

kashifusmani avatar Apr 14 '16 16:04 kashifusmani

what about get from the same date, so i want to consume at 29-02-21, the messages show only in 29-02-01 date

Satri12374 avatar Feb 18 '19 01:02 Satri12374

Al

How about:

consumer = KafkaConsumer()
partition = TopicPartition('foo', 0)
start = 1234
end = 2345
consumer.assign([partition])
consumer.seek(partition, start)
for msg in consumer:
    if msg.offset > end:
        break
    else:
        print msg

This also works for confluent_kafka python project

jpardobl avatar Apr 12 '19 13:04 jpardobl

Is this answer out of date? I have the following code, adapted from the example:

    print("Input: " + str(partition) + " " + str(offset))
    consumer = KafkaConsumer(bootstrap_servers=[host])
    partition = TopicPartition(topic, partition)
    consumer.assign([partition])
    consumer.seek(partition, offset)

    # Read the message
    message = next(consumer)
    print("Output: " + str(message.partition) + " " + str(message.offset))

And the following is printed, showing that the seek() call doesn't appear to be changing the consumer position:

Input: 5 17772562
Output: 5 18417158
Input: 5 17772565
Output: 5 18417160
Input: 5 17772566
Output: 5 18417162
Input: 5 17772567
Output: 5 18417163
Input: 5 17772568
Output: 5 18417164

jpblair avatar May 29 '19 21:05 jpblair

@jpblair It is possible that seek is working but the offset is already out of range. Perhaps, that is what's happening here. You can easily check for that by using seekToBeginning and then viewing the earliest available offset.

kashifusmani avatar May 31 '19 16:05 kashifusmani

Isn't this solution inefficient when you want to read all records from offset x till the last message because the consumer will iterate overall all the messages in the topic before getting to offset x?

DhanshreeA avatar Nov 18 '20 06:11 DhanshreeA