Apache Flink:如何应用多个计数 window 函数?

Apache Flink: How to apply multiple counting window functions?

我有一个键控数据流,需要计算不同时间段(1 分钟、5 分钟、1 天、1 周)的翻滚计数。

是否可以在单个应用程序中计算所有四个 window 计数?

是的,这是可能的。

如果您正在使用事件时间,您可以简单地级联 windows 增加时间间隔。所以你这样做:

DataStream<String> data = ...
// append a Long 1 to each record to count it.
DataStream<Tuple2<String, Long>> withOnes = data.map(new AppendOne); 

DataStream<Tuple2<String, Long>> 1minCnts = withOnes
  // key by String field
  .keyBy(0) 
  // define time window
  .timeWindow(Time.of(1, MINUTES))
  // sum ones of the Long field
  // in practice you want to use an incrementally aggregating ReduceFunction and 
  // a WindowFunction to extract the start/end timestamp of the window
  .sum(1);

// emit 1-min counts to wherever you need it
1minCnts.addSink(new YourSink());

// compute 5-min counts based on 1-min counts
DataStream<Tuple2<String, Long>> 5minCnts = 1minCnts
  // key by String field
  .keyBy(0)
  // define time window of 5 minutes
  .timeWindow(Time.of(5, MINUTES))
  // sum the 1-minute counts in the Long field
  .sum(1);

// emit 5-min counts to wherever you need it
5minCnts.addSink(new YourSink());

// continue with 1 day window and 1 week window

注意这是可能的,因为:

  1. Sum 是一个关联函数(您可以通过对部分和求和来计算和)。
  2. 翻滚 windows 对齐得很好,没有重叠。

关于增量聚合的评论ReduceFunction

通常,您希望在 window 操作的输出中包含 window 的开始 and/or 结束时间戳(否则同一键的所有结果看起来都一样) .可以从 WindowFunctionapply() 方法的 window 参数访问 window 的开始和结束时间。但是,WindowFunction 不会增量聚合记录,而是收集它们并在 window 末尾聚合记录。因此,使用 ReduceFunction 进行增量聚合并使用 WindowFunction 将 window 的开始 and/or 结束时间附加到结果会更有效。 documentation讨论细节。

如果你想用处理时间来计算这个,你不能级联 windows 但必须从输入数据流扇出到四个 window 函数。