import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.typeinfo.BasicTypeInfo;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.typeutils.RowTypeInfo;
import org.apache.flink.streaming.api.datastream.DataStream;
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.types.Row;
public class table {
public static void main(String[] args) throws Exception {
StreamExecutionEnvironment fbEnv = StreamExecutionEnvironment.getExecutionEnvironment();
StreamTableEnvironment fbTableEnv = StreamTableEnvironment.create(fbEnv);
DataStream<String> ds = fbEnv.fromElements("100,100","200,100");
DataStream<Tuple2<String,String>> ds1 = ds.map(new MapFunction<String, Tuple2<String,String>>() {
@Override
public Tuple2<String, String> map(String s) throws Exception {
String[] args = s.split(",");
return new Tuple2<String,String>(args[0],args[1]);
}
});
//流转表
Table table = fbTableEnv.fromDataStream(ds1,"id,name");
//注册表
fbTableEnv.registerTable("mytable", table);
//执行查询
Table table2 = fbTableEnv.sqlQuery("select * from mytable");
//表转流
DataStream<Row> ds3 = fbTableEnv.toAppendStream(table2,new RowTypeInfo(BasicTypeInfo.STRING_TYPE_INFO, BasicTypeInfo.STRING_TYPE_INFO));
ds3.map(new MapFunction<Row, Tuple2<String,String>>() {
@Override
public Tuple2<String, String> map(Row row) throws Exception {
String id = (String)row.getField(0);
String name = (String)row.getField(1);
return new Tuple2<String,String>(id,name);
}
}).print();
fbEnv.execute();
}
}
Flink SQL
最新推荐文章于 2024-01-10 09:37:14 发布