实现自定义TableFunction需要继承TableFunction类,然后定义一个public类型的eval方法。结合官网的例子具体来讲解一下。
public static class Split extends TableFunction<Tuple2<String,Integer>> {
private String separator = ",";
public Split(String separator) {
this.separator = separator;
}
public void eval(String str) {
for (String s : str.split(separator)) {
collect(new Tuple2<String,Integer>(s, s.length()));
}
}
}
来解释一下:
/**
* 注册多个eval方法,接收long或者string类型的参数,然后将他们转成string类型
*/
public static class DuplicatorFunction extends TableFunction<String>{
public void eval(Long i){
eval(String.valueOf(i));
}
public void eval(String s){
collect(s);
}
}
/**
* 接收不固定个数的int型参数,然后将所有数据依次返回
*/
public static class FlattenFunction extends TableFunction<Integer>{
public void eval(Integer... args){
for (Integer i: args){
collect(i);
}
}
}
/**
* 通过注册指定返回值类型,flink 1.11 版本开始支持
*/
@FunctionHint(output = @DataTypeHint("ROW< i INT, s STRING >"))
class DuplicatorFunction extends TableFunction<Row> {
public void eval(Integer i, String s) {
collect(Row.of(i, s));
collect(Row.of(i, s));
}
}
这里使用blink的planner,然后把上述三个函数都注册了
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
EnvironmentSettings bsSettings = EnvironmentSettings.newInstance()
.useBlinkPlanner()
.inStreamingMode()
.build();
StreamTableEnvironment tEnv = StreamTableEnvironment.create(env, bsSettings);
tEnv.registerFunction("split", new Split(" "));
tEnv.registerFunction("duplicator", new DuplicatorFunction());
tEnv.registerFunction("flatten", new FlattenFunction());
List<Tuple2<Long,String>> ordersData = new ArrayList<>();
ordersData.add(Tuple2.of(2L, "Euro"));
ordersData.add(Tuple2.of(1L, "US Dollar"));
ordersData.add(Tuple2.of(50L, "Yen"));
ordersData.add(Tuple2.of(3L, "Euro"));
DataStream<Tuple2<Long,String>> ordersDataStream = env.fromCollection(ordersData);
Table orders = tEnv.fromDataStream(ordersDataStream, "amount, currency, proctime.proctime");
tEnv.registerTable("Orders", orders);
Table result = tEnv.sqlQuery(
"SELECT o.currency, T.word, T.length FROM Orders as o LEFT JOIN LATERAL TABLE(split(currency)) as T(word, length) ON TRUE");
tEnv.toAppendStream(result, Row.class).print();
解释一下:
String sql = "SELECT o.currency, T.word, T.length FROM Orders as o ," +
" LATERAL TABLE(split(currency)) as T(word, length)";
String sql2 = "SELECT * FROM Orders as o , " +
"LATERAL TABLE(duplicator(amount))," +
"LATERAL TABLE(duplicator(currency))";
String sql3 = "SELECT * FROM Orders as o , " +
"LATERAL TABLE(flatten(100,200,300))";
今天这个TableFuntion我们就先讲到这里,后续我们通过自定义的TableFuntion来实现一个mysql维表和hbase维表功能,用来在流式数据中补全字段信息.
完整代码请参考:
https://github.com/zhangjun0x01/bigdata-examples/blob/master/flink/src/main/java/sql/function/CustomTableFunction.java
更多精彩内容,欢迎关注我的公众号【大数据技术与应用实战】!