详解 Flink Table API 和 Flink SQL 之函数

一、系统内置函数

1. 比较函数

API 函数表达式 示例
Table API ===,>,<,!=,>=,<= id===1001,age>18
SQL =,>,<,!=,>=,<= id=‘1001’,age>18

2. 逻辑函数

API 函数表达式 示例
Table API &&,||,!,.isFalse 1>1 && 2>1,true.isFalse
SQL and,or,is false,not 1>1 and 2>1,true is false

3. 算术函数

API 函数表达式 示例
Table API +,-,*,/,n1.power(n2) 1 + 1,2.power(2)
SQL +,-,*,/,power(n1,n2) 1 + 1,power(2,2)

4. 字符串函数

API 函数表达式 示例
Table API string1 + string2,.upperCase(),.lowerCase(),.charLength() ‘a’ + ‘b’,
‘hello’.upperCase()
SQL string1 || string2,upper(),lower(),char_length() ‘a’ || ‘b’,upper(‘hello’)

5. 时间函数

API 函数表达式 示例
Table API .toDate,.toTimestamp,currentTime(),n.days,n.minutes ‘20230107’.toDate,
2.days,10.minutes
SQL Date string,Timestamp string,current_time,interval string range Date ‘20230107’,interval ‘2’ hour/second/minute/day

6. 聚合函数

API 函数表达式 示例
Table API .count,.sum,.sum0 id.count,age.sum,sum0 表示求和的所有值都为 null 则返回 0
SQL count(),sum(),rank(),row_number() count(*),sum(age)

二、用户自定义函数(UDF)

UDF 显著地扩展了查询的表达能力,可以解决一些系统内置函数无法解决的需求。使用步骤为:自定义 UDF 函数类继承 UserDefinedFunction 抽象类;创建 UDF 实例并在环境中调用 registerFunction() 方法注册;在 Table API 或 SQL 中使用

1. 标量函数

Scalar Function,可以将 0、1 或多个标量值,映射到一个新的标量值,一进一出

/**
	用户自定义标量函数步骤:
	1.自定义函数类继承 ScalarFunction 抽象类,并在类中定义一个 public 的名为 eval 的方法
	2.创建自定义函数实例,使用 table 环境对象调用 registerFunction() 方法注册函数
	3.在 Table API 和 SQL 中使用
*/
public class TestScalarFunction {
   
    public static void main(String[] args) throws Exception {
   
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);
        
        DataStream<String> inputStream = env.readTextFile("./sensor.txt");
        
        DataStream<SensorReading> dataStream = InputStream.map(line -> {
   
            String[] fields = line.split(",");
            return new SensorReading(fields[0], new Long(fields[1]), new Double(fields[2]));
        });
        
        Table sensorTable = tableEnv.fromDataStream(dataStream, "id, timestamp as ts, temperature as temp");
        
        tableEnv.createTemporaryView("sensor", dataTable);
        
        //使用自定义的标量函数 hashCode,查询每条数据 id 的hashCode 值
        //2.创建自定义标量函数实例
        HashCode hashCode = new HashCode(0.8);
        
        //3.在环境中注册函数
        tableEnv.registerFunction("hashCode", hashCode);
        
        //4.使用
        //4.1 Table API
        Table resultTable = sensorTable.select("id, ts, hashCode(id)");
        
        //4.2 SQL
        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()

你可能感兴趣的:(Flink,flink,sql,java,大数据)