reduce算子是flink流處理中的一個聚合算子,可以對屬於同一個分組的數據進行一些聚合操作。
但有一點需要注意,就是在需要對聚合結果進行除聚合操作之外的操作時,有可能會失效。
比如下面一段代碼:
public static void main(String[] args) throws Exception {
StreamExecutionEnvironment environment = StreamExecutionEnvironment.getExecutionEnvironment();
DataStreamSource<String> source = environment.fromElements("a", "b", "c", "d");
SingleOutputStreamOperator<Tuple3<String, Integer,String>> map = source.map(new MapFunction<String, Tuple3<String, Integer,String>>() {
@Override
public Tuple3<String, Integer,String> map(String value) throws Exception {
Tuple3<String, Integer,String> tuple2 = new Tuple3<>();
tuple2.f0 = value;
tuple2.f1 = 1;
tuple2.f2 = "z";
return tuple2;
}
});
map.keyBy(0)
.reduce(new RichReduceFunction<Tuple3<String, Integer,String>>() {
@Override
public Tuple3<String, Integer,String> reduce(Tuple3<String, Integer,String> value1, Tuple3<String, Integer,String> value2) throws Exception {
String s = "f";
value1.f1=value1.f1+value2.f1;
value1.f2=s;
return value1;
}
}).print();
JobExecutionResult execute = environment.execute();
}
我在代碼中想將聚合結果的第三個元素都改成"f",運行代碼的時候會發現並沒有改變,甚至都沒有進入reduce方法。
這是因爲輸入的流中每個元素都不一樣,因此每個分組都只有一個元素。這時候是不會進入reduce方法的,而是直接返回。
因此,如果要對聚合結果進行非聚合操作的話,可以通過reduce後map裏進行。