1+ package com .atguigu .day11
2+
3+ import com .atguigu .day2 .SensorSource
4+ import org .apache .flink .streaming .api .scala .StreamExecutionEnvironment
5+ import org .apache .flink .api .scala ._
6+ import org .apache .flink .table .api ._
7+ import org .apache .flink .table .api .bridge .scala .StreamTableEnvironment
8+ import org .apache .flink .table .functions .TableAggregateFunction
9+ import org .apache .flink .types .Row
10+ import org .apache .flink .util .Collector
11+
12+ object TableAggregateFunctionExample {
13+ def main (args : Array [String ]): Unit = {
14+ val env = StreamExecutionEnvironment .getExecutionEnvironment
15+ env.setParallelism(1 )
16+
17+ val settings = EnvironmentSettings .newInstance().inStreamingMode().build()
18+
19+ val tEnv = StreamTableEnvironment .create(env, settings)
20+
21+ val stream = env.addSource(new SensorSource )
22+
23+ val table = tEnv.fromDataStream(stream)
24+
25+ val top2Temp = new Top2Temp ()
26+
27+ val resultTable = table
28+ .groupBy($" id" )
29+ .flatAggregate(top2Temp($" temperature" ) as (" temp" , " rank" ))
30+ .select($" id" , $" temp" , $" rank" )
31+
32+ tEnv.toRetractStream[Row ](resultTable).print()
33+
34+ env.execute()
35+ }
36+
37+ class Top2TempAcc {
38+ var highestTemp : Double = Double .MinValue
39+ var secondHighestTemp : Double = Double .MinValue
40+ }
41+
42+ class Top2Temp extends TableAggregateFunction [(Double , Int ), Top2TempAcc ] {
43+ override def createAccumulator (): Top2TempAcc = new Top2TempAcc
44+
45+ def accumulate (acc : Top2TempAcc , in : Double ): Unit = {
46+ if (in > acc.highestTemp) {
47+ acc.secondHighestTemp = acc.highestTemp
48+ acc.highestTemp = in
49+ } else if (in > acc.secondHighestTemp) {
50+ acc.secondHighestTemp = in
51+ }
52+ }
53+
54+ def emitValue (acc : Top2TempAcc , out : Collector [(Double , Int )]): Unit = {
55+ out.collect(acc.highestTemp, 1 )
56+ out.collect(acc.secondHighestTemp, 2 )
57+ }
58+ }
59+ }
0 commit comments