需求:
有一个kafka队列,我需要从中找到我想要的一条数据,目前知道的是数据的生成时间的大致范围和value中的一个字段内容。
from kafka import KafkaConsumer
import json
# 要找的目标时间戳和文本
timstmp = '1603344765476'
txt = '随便一个字段.pptx'
consumer = KafkaConsumer(group,topic,ip...)
思路:
基本逻辑:查询kafka的数据需要用到offset, partition来定位消费的开始的点。然后开始遍历队列的记录,拿出来匹配要找的内容。
定位到 offset后可以获取该offset的 timestamp
,和要找的时间戳对比,
小了往前找,大了往后找,
就是根据时间戳和offset的顺序找到满足要求的offset。
为了快速查到目标offset,可以使用二分法加快查找的速度。
具体实现如下:
代码:
# 获取partition信息
a = consumer.assignment()
tp=a.pop()
# 查找对应时间戳的 offset
bs, es = consumer.beginning_offsets([tp]).get(tp), consumer.end_offsets([tp]).get(tp)
nos = int((bs+ es)/2)
print(bs, nos, es)
while True:
consumer.seek(tp,nos)
resp = consumer.poll(timeout_ms=10000, max_records=1)
resp_v = resp.values()
a=None
for x in resp_v:
a = x[0]
print(bs, nos, es, fromtimestamp(a.timestamp/1000),'offset:',a.offset)
the_time = a.timestamp
the_offset = a.offset
if the_time < timstmp:
bs, nos = nos ,int((nos+es)/2)
elif the_time > timstmp:
nos, es = int((nos+bs)/2), nos
else:
break
if nos==es or bs==nos:
break
print('目标offset',bs, nos, es)
# 从 offset=nos开始消费队列
consumer.seek(tp,nos)
for a in consumer:
print(fromtimestamp(a.timestamp/1000),'offset:',a.offset)
if txt in a.value.decode():
print(a)
break