我正在学习flink,我开始使用datastream进行简单的字数计算。为了增强处理,我过滤了输出,只显示找到3个或更多单词的结果。
DataStream<Tuple2<String, Integer>> dataStream = env
.socketTextStream("localhost", 9000)
.flatMap(new Splitter())
.keyBy(0)
.timeWindow(Time.seconds(5))
.apply(new MyWindowFunction())
.sum(1)
.filter(word -> word.f1 >= 3);
我想创建一个windowfunction,根据找到的单词的值对输出进行排序。我试图实现的windowfunction根本无法编译。我正在努力定义windowfunction接口的apply方法和参数。
public static class MyWindowFunction implements WindowFunction<
Tuple2<String, Integer>, // input type
Tuple2<String, Integer>, // output type
Tuple2<String, Integer>, // key type
TimeWindow> {
void apply(Tuple2<String, Integer> key, TimeWindow window, Iterable<Tuple2<String, Integer>> input, Collector<Tuple2<String, Integer>> out) {
String word = ((Tuple2<String, Integer>)key).f0;
Integer count = ((Tuple2<String, Integer>)key).f1;
.........
out.collect(new Tuple2<>(word, count));
}
}
2条答案
按热度按时间34gzjxbg1#
下面是一个运行示例。我没花一年时间就解决了。我刚刚在我的机器上找到了以前没有发布过的解决方案=)
3mpgtkmj2#
这个
.sum(1)
方法将完成您需要的所有操作(不需要使用apply()
),只要Splitter
类(应该是FlatMapFunction
)正在发射Tuple2<String, Integer>
记录,在哪里String
是这个词,而且Integer
总是1
.那么呢
.sum(1)
将为您进行聚合。如果你需要不同的东西sum()
是的,你通常会用.reduce(new MyCustomReduceFunction())
,因为这将是最有效和可扩展的方法,因为不需要在内存中缓冲很多。