Apache Flink为DataSet提供了许多操作。有点难以理解群集中的数据处理方式。例如,WordCount具有不同的实现。有什么区别?
如果有一些文档可以解释集群中这些工具的数据流,那将非常有用。
// get input data
DataSet<String> text = env.fromElements(
"To be, or not to be,--that is the question:--",
"Whether 'tis nobler in the mind to suffer",
"The slings and arrows of outrageous fortune",
"Or to take arms against a sea of troubles,"
);
// WordCount 1
text.flatMap(new LineSplitter()).groupBy(0).sum(1).print();
// WordCount 2
text.flatMap(new LineSplitter()).groupBy(0).aggregate(Aggregations.SUM, 1).print();
// WordCount 3
text.flatMap(new LineSplitter()).groupBy(0)
.reduce(new ReduceFunction<Tuple2<String, Integer>>() {
@Override
public Tuple2<String, Integer> reduce(Tuple2<String, Integer> t1, Tuple2<String, Integer> t2) throws Exception {
return new Tuple2<String, Integer>(t1.f0, t1.f1+t2.f1);
}
}).print();
// WordCount 4
text.flatMap(new LineSplitter()).groupBy(0)
.reduceGroup(new GroupReduceFunction<Tuple2<String, Integer>, Tuple2<String, Integer>>() {
@Override
public void reduce(Iterable<Tuple2<String, Integer>> iterable, Collector<Tuple2<String, Integer>> collector) throws Exception {
int prefixSum = 0;
String key = null;
for (Tuple2<String, Integer> t : iterable) {
prefixSum += t.f1;
key = t.f0;
}
collector.collect(new Tuple2<String, Integer>(key, prefixSum));
}
}).print();
// WordCount 5
text.flatMap(new LineSplitter())
.reduceGroup(new GroupReduceFunction<Tuple2<String, Integer>, Tuple2<String, Integer>>() {
@Override
public void reduce(Iterable<Tuple2<String, Integer>> iterable, Collector<Tuple2<String, Integer>> collector) throws Exception {
HashMap<String, Integer> map = new HashMap<String, Integer>();
for(Tuple2<String, Integer> t : iterable){
if(map.containsKey(t.f0)){
map.replace(t.f0, map.get(t.f0)+t.f1);
} else {
map.put(t.f0, t.f1);
}
}
for(Map.Entry<String, Integer> pair : map.entrySet()){
collector.collect(new Tuple2<String, Integer>(pair.getKey(), pair.getValue()));
}
}
}).print();
答案 0 :(得分:4)
除WordCount 5外,所有程序的执行都与常规MapReduce WordCount程序非常相似(基于散列的随机播放和基于排序的分组)。
GroupReduceFunction
与WordCount 4中的类似。唯一的区别是内部GroupReduceFunction
实现Combinable
接口以支持部分聚合ReduceFunction
,其执行类似于GroupReduceFunction
。但是,由于界面不同,ReduceFunction
始终可以组合(无需单独的combine
方法)。GroupReduceFunction
未实现Combinable
接口,因此该程序在没有本地预聚合的情况下执行,因此效率低于前三个程序。GroupReduceFunction
无法并行执行。由于没有groupBy()
调用,所有数据都将发送到同一个Reducer并作为一个大型组处理。首先,这将是缓慢的,因为它在单个线程中执行并受到单个机器的网络吞吐量的限制。其次,如果不同键的数量变得太大,则该程序很容易失败,因为使用内存中HashMap
进行分组。