Read from specific offsets
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.
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
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()
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
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
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 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.
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?