Flink基礎系列33-Table API和Flink SQL之函數 一. 函數 二.案例 參考:

一. 函數

  Flink Table 和 SQL 內置了很多 SQL 中支持的函數;如果有無法滿足的需要,則可以實 現用戶自定義的函數(UDF)來解決。

1.1 系統內置函數

  Flink Table API 和 SQL 爲用戶提供了一組用於數據轉換的內置函數。SQL 中支持的很多 函數,Table API 和 SQL 都已經做了實現,其它還在快速開發擴展中。

  以下是一些典型函數的舉例,全部的內置函數,可以參考官網介紹。
⚫ 比較函數
SQL:
value1 = value2
value1 > value2

Table API:
ANY1 === ANY2
ANY1 > ANY2

⚫ 邏輯函數
SQL:
boolean1 OR boolean2
boolean IS FALSE
NOT boolean

Table API:
BOOLEAN1 || BOOLEAN2
BOOLEAN.isFalse
!BOOLEAN

⚫ 算術函數
SQL:
numeric1 + numeric2
POWER(numeric1, numeric2)

Table API:
NUMERIC1 + NUMERIC2
NUMERIC1.power(NUMERIC2)

⚫ 字符串函數
SQL:
string1 || string2
UPPER(string)
CHAR_LENGTH(string)

Table API:
STRING1 + STRING2
STRING.upperCase()
STRING.charLength()

⚫ 時間函數
SQL:
DATE string
TIMESTAMP string
CURRENT_TIME
INTERVAL string range

Table API:
STRING.toDate
STRING.toTimestamp
currentTime()
NUMERIC.days
NUMERIC.minutes

⚫ 聚合函數
SQL:
COUNT(*)
SUM([ ALL | DISTINCT ] expression)
RANK()
ROW_NUMBER()

Table API:
FIELD.count
FIELD.sum0

1.2 UDF

  用戶定義函數(User-defined Functions,UDF)是一個重要的特性,因爲它們顯著地擴 展了查詢(Query)的表達能力。一些系統內置函數無法解決的需求,我們可以用 UDF 來自 定義實現。

1.2.1 註冊用戶自定義函數 UDF

  在大多數情況下,用戶定義的函數必須先註冊,然後才能在查詢中使用。不需要專門爲Scala 的 Table API 註冊函數。

  函數通過調用 registerFunction()方法在 TableEnvironment 中註冊。當用戶定義的函數被註冊時,它被插入到 TableEnvironment 的函數目錄中,這樣 Table API 或 SQL 解析器就可 以識別並正確地解釋它。

1.2.2 標量函數(Scalar Functions)

  用戶定義的標量函數,可以將 0、1 或多個標量值,映射到新的標量值。 爲了定義標量函數,必須在 org.apache.flink.table.functions 中擴展基類 Scalar Function,並實現(一個或多個)求值(evaluation,eval)方法。標量函數的行爲由求值方法決定, 求值方法必須公開聲明並命名爲 eval(直接 def 聲明,沒有 override)。求值方法的參數類型 和返回類型,確定了標量函數的參數和返回類型。

  在下面的代碼中,我們定義自己的 HashCode 函數,在 TableEnvironment 中註冊它,並 在查詢中調用它。

// 自定義一個標量函數

public static class HashCode extends ScalarFunction {

private int factor = 13;

public HashCode(int factor) {
this.factor = factor;
}


public int eval(String s) {
return s.hashCode() * factor;
}

}

主函數中調用,計算 sensor id 的哈希值(前面部分照抄,流環境、表環境、讀取 source、 建表):

public static void main(String[] args) throws Exception {
// 1. 創建環境

    StreamExecutionEnvironment env =StreamExecutionEnvironment.getExecutionEnvironment();

    env.setParallelism(1);

    StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);


    // 2. 讀取文件,得到 DataStream
    String filePath = "..\\sensor.txt";
    DataStream<String> inputStream = env.readTextFile(filePath);


    // 3. 轉換成 Java Bean,並指定 timestamp 和 watermark

    DataStream<SensorReading> dataStream = inputStream.map( line -> {
String[] fields = line.split(",");

    return new SensorReading(fields[0], new Long(fields[1]), new Double(fields[2]));
} );


    // 4. 將 DataStream 轉換爲 Table
    Table sensorTable = tableEnv.fromDataStream(dataStream, "id, timestamp as ts, temperature");

    // 5. 調用自定義 hash 函數,對 id 進行 hash 運算
    HashCode hashCode = new HashCode(23);
    tableEnv.registerFunction("hashCode", hashCode);
    Table resultTable = sensorTable.select("id, ts, hashCode(id)");

    //  sql
    tableEnv.createTemporaryView("sensor", sensorTable);
Table resultSqlTable = tableEnv.sqlQuery("select id, ts, hashCode(id) from sensor");
    tableEnv.toAppendStream(resultTable, Row.class).print("result");
    tableEnv.toRetractStream(resultSqlTable, Row.class).print("sql");

    env.execute("scalar function test");

1.2.3 表函數(Table Functions)

  與用戶定義的標量函數類似,用戶定義的表函數,可以將 0、1 或多個標量值作爲輸入 參數;與標量函數不同的是,它可以返回任意數量的行作爲輸出,而不是單個值。

  爲了定義一個表函數,必須擴展 org.apache.flink.table.functions 中的基類 TableFunction 並實現(一個或多個)求值方法。表函數的行爲由其求值方法決定,求值方法必須是 public 的,並命名爲 eval。求值方法的參數類型,決定表函數的所有有效參數。

  返回表的類型由 TableFunction 的泛型類型確定。求值方法使用 protected collect(T)方 法發出輸出行。

  在 Table API 中,Table 函數需要與.joinLateral 或.leftOuterJoinLateral 一起使用。joinLateral 算子,會將外部表中的每一行,與表函數(TableFunction,算子的參數是它 的表達式)計算得到的所有行連接起來。而 leftOuterJoinLateral 算子,則是左外連接,它同樣會將外部表中的每一行與表函數計 算生成的所有行連接起來;並且,對於表函數返回的是空表的外部行,也要保留下來。

  在 SQL 中,則需要使用 Lateral Table(<TableFunction>),或者帶有 ON TRUE 條件的左連 接。

  下面的代碼中,我們將定義一個表函數,在表環境中註冊它,並在查詢中調用它。 自定義 TableFunction:

// 自定義 TableFunction

public static class Split extends TableFunction<Tuple2<String, Integer>> {

private String separator = ",";


public Split(String separator) {
this.separator = separator;
}


// 類似 flatmap,沒有返回值
public void eval(String str) {
for (String s : str.split(separator)) {
collect(new Tuple2<String, Integer>(s, s.length()));
}

}

}

接下來,就是在代碼中調用。首先是 Table API 的方式:

Split split = new Split("_"); tableEnv.registerFunction("split", split); Table resultTable = sensorTable
.joinLateral( "split(id) as (word, length)")
.select("id, ts, word, length");

然後是 SQL 的方式:

tableEnv.createTemporaryView("sensor", sensorTable);

Table resultSqlTable = tableEnv.sqlQuery("select id, ts, word, length " +
"from sensor, lateral table( split(id) ) as splitId(word, length)");

1.2.4 聚合函數(Aggregate Functions)

  用戶自定義聚合函數(User-Defined Aggregate Functions,UDAGGs)可以把一個表中的 數據,聚合成一個標量值。用戶定義的聚合函數,是通過繼承 AggregateFunction 抽象類實 現的。

上圖中顯示了一個聚合的例子。 假設現在有一張表,包含了各種飲料的數據。該表由三列(id、name 和 price)、五行組成數據。現在我們需要找到表中所有飲料的最高價格,即執行 max()聚合,結果將是一個數值。

AggregateFunction 的工作原理如下。
⚫ 首先,它需要一個累加器,用來保存聚合中間結果的數據結構(狀態)。可以通過 調用 AggregateFunction 的 createAccumulator()方法創建空累加器。
⚫ 隨後,對每個輸入行調用函數的 accumulate()方法來更新累加器。
⚫ 處理完所有行後,將調用函數的 getValue()方法來計算並返回最終結果。 AggregationFunction 要求必須實現的方法:
• createAccumulator()
• accumulate()
• getValue()

除了上述方法之外,還有一些可選擇實現的方法。其中一些方法,可以讓系統執行查詢 更有效率,而另一些方法,對於某些場景是必需的。例如,如果聚合函數應用在會話窗口
(session group window)的上下文中,則 merge()方法是必需的。
• retract()
• merge()
• resetAccumulator()

接下來我們寫一個自定義 AggregateFunction,計算一下每個 sensor 的平均溫度值.

// 定義 AggregateFunction 的 Accumulator

public static class AvgTempAcc {

double sum = 0.0;

int count = 0;

}

// 自定義一個聚合函數,求每個傳感器的平均溫度值,保存狀態(tempSum,  tempCount)

public static class AvgTemp extends AggregateFunction<Double, AvgTempAcc>{

@Override

public Double getValue(AvgTempAcc accumulator) {

return accumulator.sum / accumulator.count;

}

@Override

public AvgTempAcc createAccumulator() {

return new AvgTempAcc();

}

// 實現一個具體的處理計算函數,accumulate

public void accumulate( AvgTempAcc accumulator, Double temp) {
accumulator.sum += temp;

accumulator.count += 1;

}
}

接下來就可以在代碼中調用了。

// 創建一個聚合函數實例

AvgTemp avgTemp = new AvgTemp();


// Table API 的調用

tableEnv.registerFunction("avgTemp", avgTemp); Table resultTable = sensorTable
.groupBy("id")
.aggregate("avgTemp(temperature) as avgTemp")
.select("id, avgTemp");

// sql
tableEnv.createTemporaryView("sensor", sensorTable);
Table resultSqlTable = tableEnv.sqlQuery("select id, avgTemp(temperature) " +
"from sensor group by id");

tableEnv.toRetractStream(resultTable, Row.class).print("result"); tableEnv.toRetractStream(resultSqlTable, Row.class).print("sql");

1.2.5 表聚合函數(Table Aggregate Functions)

  用戶定義的表聚合函數(User-Defined Table Aggregate Functions,UDTAGGs),可以把一 個表中數據,聚合爲具有多行和多列的結果表。這跟 AggregateFunction 非常類似,只是之 前聚合結果是一個標量值,現在變成了一張表。

比如現在我們需要找到表中所有飲料的前 2 個最高價格,即執行 top2()表聚合。我 們需要檢查 5 行中的每一行,得到的結果將是一個具有排序後前 2 個值的表。
用戶定義的表聚合函數,是通過繼承 TableAggregateFunction 抽象類來實現的。

TableAggregateFunction 的工作原理如下。
⚫ 首先,它同樣需要一個累加器(Accumulator),它是保存聚合中間結果的數據結構。
通過調用 TableAggregateFunction 的 createAccumulato(r)方法可以創建空累加器。

⚫ 隨後,對每個輸入行調用函數的 accumulate()方法來更新累加器。

⚫ 處理完所有行後,將調用函數的 emitValue()方法來計算並返回最終結果。

AggregationFunction 要求必須實現的方法:
• createAccumulator()
• accumulate()

除了上述方法之外,還有一些可選擇實現的方法。
• retract()
• merge()
• resetAccumulator()
• emitValue()
• emitUpdateWithRetract()

接下來我們寫一個自定義 TableAggregateFunction,用來提取每個 sensor 最高的兩個溫 度值。

// 先定義一個 Accumulator

public static class Top2TempAcc {

double highestTemp = Double.MIN_VALUE;

double secondHighestTemp = Double.MIN_VALUE;

}

// 自定義表聚合函數
public static class Top2Temp extends TableAggregateFunction<Tuple2<Double, Integer>, Top2TempAcc> {
@Override

public Top2TempAcc createAccumulator() {

return new Top2TempAcc();

}

// 實現計算聚合結果的函數 accumulate
public void accumulate(Top2TempAcc acc, Double temp) {

if (temp > acc.highestTemp) { acc.secondHighestTemp = acc.highestTemp; acc.highestTemp = temp;
} else if (temp > acc.secondHighestTemp) { acc.secondHighestTemp = temp;
}

}
// 實現一個輸出結果的方法,最終處理完表中所有數據時調用

public void emitValue(Top2TempAcc acc, Collector<Tuple2<Double, Integer>> out) {
out.collect(new Tuple2<>(acc.highestTemp, 1));

out.collect(new Tuple2<>(acc.secondHighestTemp, 2));

}

}

接下來就可以在代碼中調用了。

// 創建一個表聚合函數實例

Top2Temp top2Temp = new Top2Temp(); tableEnv.registerFunction("top2Temp", top2Temp); Table resultTable = sensorTable
.groupBy("id")
.flatAggregate("top2Temp(temperature) as (temp, rank)")
.select("id, temp, rank");

tableEnv.toRetractStream(resultTable, Row.class).print("result");

二.案例

2.1 Scalar Function

代碼:

package org.flink.tableapi.udf;

import org.flink.beans.SensorReading;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.java.StreamTableEnvironment;
import org.apache.flink.table.functions.ScalarFunction;
import org.apache.flink.types.Row;

/**
 * @author 只是甲
 * @date   2021-09-30
 */

public class UdfTest1_ScalarFunction {
    public static void main(String[] args) throws Exception{
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        // 1. 讀取數據
        DataStreamSource<String> inputStream = env.readTextFile("C:\\Users\\Administrator\\IdeaProjects\\FlinkStudy\\src\\main\\resources\\sensor.txt");

        // 2. 轉換成POJO
        DataStream<SensorReading> dataStream = inputStream.map(line -> {
            String[] fields = line.split(",");
            return new SensorReading(fields[0], new Long(fields[1]), new Double(fields[2]));
        });

        // 3. 將流轉換成表
        Table sensorTable = tableEnv.fromDataStream(dataStream, "id, timestamp as ts, temperature as temp");

        // 4. 自定義標量函數,實現求id的hash值
        // 4.1 table API
        HashCode hashCode = new HashCode(23);
        // 需要在環境中註冊UDF
        tableEnv.registerFunction("hashCode", hashCode);
        Table resultTable = sensorTable.select("id, ts, hashCode(id)");

        // 4.2 SQL
        tableEnv.registerTable("sensor", sensorTable);
        Table resultSqlTable = tableEnv.sqlQuery("select id, ts, hashCode(id) from sensor");

        // 打印輸出
        tableEnv.toAppendStream(resultTable, Row.class).print("result");
        tableEnv.toAppendStream(resultSqlTable, Row.class).print("sql");

        env.execute();
    }

    // 實現自定義的ScalarFunction
    public static class HashCode extends ScalarFunction{
        private int factor = 13;

        public HashCode(int factor) {
            this.factor = factor;
        }

        public int eval(String str){
            return str.hashCode() * factor;
        }
    }
}

測試記錄:

2.2 Table Function

代碼:

package org.flink.tableapi.udf;


import org.flink.beans.SensorReading;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.java.StreamTableEnvironment;
import org.apache.flink.table.functions.TableFunction;
import org.apache.flink.types.Row;

/**
 * @author 只是甲
 * @date   2021-09-30
 */

public class UdfTest2_TableFunction {
    public static void main(String[] args) throws Exception{
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        // 1. 讀取數據
        DataStreamSource<String> inputStream = env.readTextFile("C:\\Users\\Administrator\\IdeaProjects\\FlinkStudy\\src\\main\\resources\\sensor.txt");

        // 2. 轉換成POJO
        DataStream<SensorReading> dataStream = inputStream.map(line -> {
            String[] fields = line.split(",");
            return new SensorReading(fields[0], new Long(fields[1]), new Double(fields[2]));
        });

        // 3. 將流轉換成表
        Table sensorTable = tableEnv.fromDataStream(dataStream, "id, timestamp as ts, temperature as temp");

        // 4. 自定義表函數,實現將id拆分,並輸出(word, length)
        // 4.1 table API
        Split split = new Split("_");

        // 需要在環境中註冊UDF
        tableEnv.registerFunction("split", split);
        Table resultTable = sensorTable
                .joinLateral("split(id) as (word, length)")
                .select("id, ts, word, length");

        // 4.2 SQL
        tableEnv.registerTable("sensor", sensorTable);
        Table resultSqlTable = tableEnv.sqlQuery("select id, ts, word, length " +
                " from sensor, lateral table(split(id)) as splitid(word, length)");

        // 打印輸出
        tableEnv.toAppendStream(resultTable, Row.class).print("result");
        tableEnv.toAppendStream(resultSqlTable, Row.class).print("sql");

        env.execute();
    }

    // 實現自定義TableFunction
    public static class Split extends TableFunction<Tuple2<String, Integer>>{
        // 定義屬性,分隔符
        private String separator = ",";

        public Split(String separator) {
            this.separator = separator;
        }

        // 必須實現一個eval方法,沒有返回值
        public void eval( String str ){
            for( String s: str.split(separator) ){
                collect(new Tuple2<>(s, s.length()));
            }
        }
    }
}

測試記錄:

2.3 Aggregate Function

代碼:

package org.flink.tableapi.udf;


import org.flink.beans.SensorReading;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.java.StreamTableEnvironment;
import org.apache.flink.table.functions.AggregateFunction;
import org.apache.flink.types.Row;


/**
 * @author 只是甲
 * @date   2021-09-30
 */

public class UdfTest3_AggregateFunction {
    public static void main(String[] args) throws Exception{
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        // 1. 讀取數據
        DataStreamSource<String> inputStream = env.readTextFile("C:\\Users\\Administrator\\IdeaProjects\\FlinkStudy\\src\\main\\resources\\sensor.txt");

        // 2. 轉換成POJO
        DataStream<SensorReading> dataStream = inputStream.map(line -> {
            String[] fields = line.split(",");
            return new SensorReading(fields[0], new Long(fields[1]), new Double(fields[2]));
        });

        // 3. 將流轉換成表
        Table sensorTable = tableEnv.fromDataStream(dataStream, "id, timestamp as ts, temperature as temp");

        // 4. 自定義聚合函數,求當前傳感器的平均溫度值
        // 4.1 table API
        AvgTemp avgTemp = new AvgTemp();

        // 需要在環境中註冊UDF
        tableEnv.registerFunction("avgTemp", avgTemp);
        Table resultTable = sensorTable
                .groupBy("id")
                .aggregate( "avgTemp(temp) as avgtemp" )
                .select("id, avgtemp");

        // 4.2 SQL
        tableEnv.registerTable("sensor", sensorTable);
        Table resultSqlTable = tableEnv.sqlQuery("select id, avgTemp(temp) " +
                " from sensor group by id");

        // 打印輸出
        tableEnv.toRetractStream(resultTable, Row.class).print("result");
        tableEnv.toRetractStream(resultSqlTable, Row.class).print("sql");

        env.execute();
    }

    // 實現自定義的AggregateFunction
    public static class AvgTemp extends AggregateFunction<Double, Tuple2<Double, Integer>>{
        @Override
        public Double getValue(Tuple2<Double, Integer> accumulator) {
            return accumulator.f0 / accumulator.f1;
        }

        @Override
        public Tuple2<Double, Integer> createAccumulator() {
            return new Tuple2<>(0.0, 0);
        }

        // 必須實現一個accumulate方法,來數據之後更新狀態
        public void accumulate( Tuple2<Double, Integer> accumulator, Double temp ){
            accumulator.f0 += temp;
            accumulator.f1 += 1;
        }
    }
}

測試記錄:

參考:

  1. https://www.bilibili.com/video/BV1qy4y1q728
  2. https://ashiamd.github.io/docsify-notes/#/study/BigData/Flink/%E5%B0%9A%E7%A1%85%E8%B0%B7Flink%E5%85%A5%E9%97%A8%E5%88%B0%E5%AE%9E%E6%88%98-%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0?id=_11-table-api%e5%92%8cflink-sql
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章