首页 > 解决方案 > Apache Flink:keyby 和窗口操作符

问题描述

我想知道一些与keyedstream相关的机制。代码如下:</p>

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)))

如果我想实现窗口字数。

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

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

谢谢您的帮助。

标签: apache-flinkapache-stormflink-streaming

解决方案


即使每个窗口实际上有多个键,对您的/// 函数的每次调用都是process使用具有相同键的元素进行的。reducesumaggregate

在您的示例中,您可以使用sumFlink 来处理所有事情:

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) ...)
            }
      });

推荐阅读