目录
2.4 表聚合函数(Table AggregateFunction)
1 函数
2 用户自定义函数(UDF)
2.1 标量函数(Scalar Function)
一对一
package com.study.liucf.table.udf
import com.study.liucf.bean.LiucfSensorReding
import org.apache.flink.streaming.api.TimeCharacteristic
import org.apache.flink.streaming.api.functions.timestamps.BoundedOutOfOrdernessTimestampExtractor
import org.apache.flink.streaming.api.scala._
import org.apache.flink.streaming.api.windowing.time.Time
import org.apache.flink.table.api.{EnvironmentSettings, Table}
import org.apache.flink.table.api.scala._
import org.apache.flink.table.functions.ScalarFunction
import org.apache.flink.types.Row
object LiucfTableUDFDemo {
def main(args: Array[String]): Unit = {
val env = StreamExecutionEnvironment.getExecutionEnvironment
env.setParallelism(1)
// env.setStreamTimeCharacteristic(TimeCharacteristic.ProcessingTime)
env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime)
val inputStream: DataStream[String] = env.readTextFile("src\\main\\resources\\sensor.txt")
val inputDataStream: DataStream[LiucfSensorReding] = inputStream.map(r => {
val arr = r.split(",")
LiucfSensorReding(arr(0), arr(1).toLong, arr(2).toDouble)
}).assignTimestampsAndWatermarks(
new BoundedOutOfOrdernessTimestampExtractor[LiucfSensorReding](Time.seconds(1)){
override def extractTimestamp(element: LiucfSensorReding): Long = element.timestamp *1000
}
)
//定义表环境
val settings = EnvironmentSettings.newInstance()
.useBlinkPlanner()
.inStreamingMode()
.build()
val tableEnv = StreamTableEnvironment.create(env, settings)
//基于流创建一张表
// val flinkTable: Table = tableEnv.fromDataStream(inputDataStream,'id,'timestamp,'temperature,'pt.proctime)
val flinkTable: Table = tableEnv
.fromDataStream(inputDataStream, 'id, 'timestamp, 'temperature, 'timestamp.rowtime as 'tr)
// 使用自定义UDF函数
//先new 一个udf 实例
val hashCode = new HashCode(5)
// 1 在table api 里的应用
val hashCodeTableAPI: Table = flinkTable.select('id, 'tr, 'temperature, hashCode('id))
hashCodeTableAPI.toAppendStream[Row].print("hashCodeTableAPI")
// 2 在 table sql 里的应用
tableEnv.createTemporaryView("flinkTable_view",flinkTable)
tableEnv.registerFunction("hashCode",hashCode)
val hashCodeTableSql = tableEnv.sqlQuery("select id,tr,temperature,hashCode(id) as hashCode_id from flinkTable_view")
hashCodeTableSql.toAppendStream[Row].print("hashCodeTableSql")
env.execute("LiucfTableUDFDemo")
}
}
/**
*
* @param 权重种子
*/
class HashCode(factor:Int) extends ScalarFunction{
/**
* 注意:这个函数是自定义的,不是重写