如何只在window结束时才输出windowed聚合的结果?
How to output result of windowed aggregation only when window is finished?
我有一个 KStream
,我想在其中计算事件的某些维度。我是这样做的:
KTable<Windowed<Long>, Counter> ret = input.groupByKey()
.windowedBy(TimeWindows.of(Duration.of(10, SECONDS)))
.aggregate(Counter::new, (k, v, c) -> new Counter(c.count + v.getDimension()));
我想要一个新的 KStream
将这些聚合作为事件。我可以像这样轻松地做到这一点:
ret.toStream().to("output");
问题是 "input" 主题中的每个事件都会对 "output" 主题产生一个事件。我想仅在 window 完成后才向输出主题发布事件。例如,如果 window 是一分钟,则每分钟每个键发送一个事件。
我想我可以这样做:
ret.toStream().foreach((k, v) -> sendToKafkaTopic("output"));
但我想知道是否有更好/更优雅的方法来做到这一点?
您可以使用 KTable KTable.suppress 2.1 版本的新功能
对于窗口计算,此方法允许您每次 window/key 得到一个最终结果。
更多关于 suppres
KIP-328
您可以像这样使用 suppress
更新您的实现:
KTable<Windowed<Long>, Counter> ret = input.groupByKey()
.windowedBy(TimeWindows.of(Duration.of(10, SECONDS)))
.aggregate(Counter::new, (k, v, c) -> new Counter(c.count + v.getDimension()))
.suppress(untilWindowCloses(BufferConfig.unbounded()));
ret.toStream().to("output"); // now stream should flush events to the output topic only when the window closes
我有一个 KStream
,我想在其中计算事件的某些维度。我是这样做的:
KTable<Windowed<Long>, Counter> ret = input.groupByKey()
.windowedBy(TimeWindows.of(Duration.of(10, SECONDS)))
.aggregate(Counter::new, (k, v, c) -> new Counter(c.count + v.getDimension()));
我想要一个新的 KStream
将这些聚合作为事件。我可以像这样轻松地做到这一点:
ret.toStream().to("output");
问题是 "input" 主题中的每个事件都会对 "output" 主题产生一个事件。我想仅在 window 完成后才向输出主题发布事件。例如,如果 window 是一分钟,则每分钟每个键发送一个事件。
我想我可以这样做:
ret.toStream().foreach((k, v) -> sendToKafkaTopic("output"));
但我想知道是否有更好/更优雅的方法来做到这一点?
您可以使用 KTable KTable.suppress 2.1 版本的新功能
对于窗口计算,此方法允许您每次 window/key 得到一个最终结果。
更多关于 suppres
KIP-328
您可以像这样使用 suppress
更新您的实现:
KTable<Windowed<Long>, Counter> ret = input.groupByKey()
.windowedBy(TimeWindows.of(Duration.of(10, SECONDS)))
.aggregate(Counter::new, (k, v, c) -> new Counter(c.count + v.getDimension()))
.suppress(untilWindowCloses(BufferConfig.unbounded()));
ret.toStream().to("output"); // now stream should flush events to the output topic only when the window closes