Apache Flink:keyby 和 window 运算符

Apache Flink:keyby and window operator

我想知道keyedstream相关的一些机制。 代码如下:

DataStream<Tuple2<String, Integer>> counts =
            // split up the lines in pairs (2-tuples) containing: (word,1)
            text.flatMap(new Tokenizer())
            // group by the tuple field "0" and sum up tuple field "1"
                    .keyBy(0)
                    .window(TumblingProcessingTimeWindows.of(Time.seconds(3)))

如果我想实现 window wordcount。

Q1:是每个window只有一个键还是多个键?

Q2:对于window中的函数,我只使用简单的sum++或者需要像Apache Storm那样通过[​​=22=]中的hashmap来处理多个键的和。

感谢您的帮助。

即使每个 window 实际上有多个键,每次对 process/reduce/sum/aggregate 函数的调用都是通过具有相同键的元素。

在您的示例中,您可以只使用 sum,Flink 会处理所有事情:

text.flatMap(new Tokenizer())
      .keyBy(0)
      .window(TumblingProcessingTimeWindows.of(Time.seconds(3)))
      .sum(X)

如果您选择 reduce 而不是...

text.flatMap(new Tokenizer())
      .keyBy(0)
      .window(TumblingProcessingTimeWindows.of(Time.seconds(3)))
      .reduce(new ReduceFunction<Tuple2<String, Integer>>(){
            @Override
            public Tuple2<String, Integer> reduce(final Tuple2<String, Integer> first, final Tuple2<String, Integer> second) {
                  (... do something with the guarantee that first[0] == second[0] (same key) ...)
            }
      });