Flink单流算子

DataStream

1. map/flatMap

  • MapFunction
O map(T value) throws Exception;

输入一个元素,输出一个元素,其中包含了变换逻辑

  • RichMapFunction

继承了MapFunction,可以获取RuntimeContext,用于查询当前算子当前并发的运行状态、accumulator以及broadcast variables等。

  • FlatMapFunction
void flatMap(T value, Collector out) throws Exception;

输入一个元素,输出若干个元素(可以是0个),其中包含了变换逻辑

  • RichFlatMapFunction

类似RichMapFunction

2. filter

  • FilterFunction
    boolean filter(T value) throws Exception;
    包含筛选逻辑,需要保留的返回true,否则返回false

3. process

  • ProcessFunction
void processElement(I value, Context ctx, Collector out)

用于处理数据,out用于向下游发射数据,ctx则用于查询时间戳、注册TimerService等等,也可以获取state用于暂时存储数据

onTimer(long timestamp, OnTimerContext ctx, Collector out)

注册了TimerService后(同一个时间戳多次注册只会触发一次),当watermark没过这个时间戳时,就会触发事件,调用onTimer方法,可以执行一些逻辑,比如把统计的结果合并成一条记录,用out输出等等

4. project

  • SingleOutputStreamOperator project(int... fieldIndexes)

只有Tuple才能这样操作,就是将原来的Tuple映射成新的Tuple,fieldIndexes表示原来的Tuple中的数据的索引,取出的数据按fieldIndexes的顺序,排成新的Tuple

5. windowAll / countWindowAll / timeWindowAll

表示以不同的方式获取不分key的AllWindowedStream

6. addSink / print/printToErr / writeAsText / writeAsText / writeToSocket / writeUsingOutputFormat

各种花式输出~

AllWindowedStream

1. reduce

将一个流的一个window的数据聚合成一个数据,数据类型一致

  • ReduceFunction
T reduce(T value1, T value2) throws Exception;

输入两个数据,输出一个数据,其中包含了归并的逻辑,算子会不断重复,直至剩下一个元素。用户需要自己保证reduce方法的结果与元素的处理先后、组合方式无关。

2. aggregate

将一个窗口的数据聚合成一条,与reduce类似,但是更灵活

  • AggregateFunction
ACC createAccumulator();

创建一个累加器,用于保存状态,最好是增量的,可以节约存储,不用保存所有记录

ACC add(IN value, ACC accumulator);

增加一个元素

OUT getResult(ACC accumulator);

从accumulator中获得输出元素

ACC merge(ACC a, ACC b);

用于合并accumulator,复用对象,调用这个方法后,之前的accumulator就不再用了

  • AllWindowFunction
void apply(W window, Iterable values, Collector out) throws Exception;

用于将AggregateFunction中合并得到的的OUT 数据通过out输出。这里的IN是AggregateFunction的OUT

  • ProcessAllWindowFunction
public abstract void process(Context context, Iterable elements, Collector out) throws Exception;

与AllWindowFunction类似,但是多了可以使用context的功能

3. process

也使用ProcessAllWindowFunction,与aggregate不同的是,处理的是窗口中的每一个元素,而不是聚合后的元素

4. apply

也使用ReduceFunction、AllWindowFunction,与reduce、aggregate不同的是,处理的是窗口中的每一个元素,而不是聚合后的元素

5. fold

FoldFunction
T fold(T accumulator, O value) throws Exception;
与reduce、aggregate类似,把每个数据都归并到一个accumulator中去,最后产生一个输出数据

6. sum / min / max / minBy / maxBy

一些预定义好的聚合方法,按字面意思

7. sideOutputLateData

sideOutputLateData(OutputTag outputTag)
将迟到的数据输出,outputTag是输出流的tag
可以通过SingleOutputStreamOperator#getSideOutput(OutputTag)来获得迟到数据的流

KeyedStream

1. reduce

2. aggregate

3. process

4. fold

5. sum / min / max / minBy / maxBy

6. window / countWindow / timeWindow

方法的作用与DataStream类似,表示以不同的方式获取分key的WindowedStream

WindowedStream

1. reduce

2. aggregate

3. process

4. apply

5. fold

6. sum / min / max / minBy / maxBy

7. sideOutputLateData

方法的作用与AllWindowStream类似,只是作用于某个pane(也就是window中单独的key的数据)

你可能感兴趣的:(Flink单流算子)