flink tableApi和 filink sql ---2 table api 写入到文件



sensor_1,1547718199,35.8
sensor_6,1547718201,15.4
sensor_7,1547718202,6.7
sensor_10,1547718205,38.1
sensor_1,1547718129,29.8
sensor_1,1547718158,5.8
sensor_1,1547718140,40.8
sensor_1,1547718111,11.8

package com.tableApiTest

import org.apache.flink.streaming.api.scala._
import org.apache.flink.table.api.{DataTypes, Table}
import org.apache.flink.table.api.scala._
import org.apache.flink.table.descriptors.{Csv, FileSystem, Schema}
object FileOutPutTest {
  def main(args: Array[String]): Unit = {
    //创建环境
    val env=StreamExecutionEnvironment.getExecutionEnvironment
    env.setParallelism(1)
    val tableEnv=StreamTableEnvironment.create(env)

    val filePath="D:\\workspace\\ideastudy\\flinkstudy\\src\\main\\resources\\sensor.txt"
    tableEnv.connect(new FileSystem().path(filePath))
      .withFormat(new Csv())
      .withSchema(new Schema()
        .field("id",DataTypes.STRING())
        .field("timestamp",DataTypes.BIGINT())
        .field("temp",DataTypes.DOUBLE())
      )
      .createTemporaryTable("inputTable")
    val sensorTable=tableEnv.from("inputTable")

    //简单转换操作
    val resultTable = sensorTable
      .select("id,temp")
      .filter("id='sensor_1'")
    //聚合转换
    val aggTable=sensorTable
      .groupBy("id")//基于id分组
      .select('id,'id.count as 'count)


//    resultTable.toAppendStream[(String,Double)].print("result")
//    aggTable.toRetractStream[(String,Long)].print("agg")

    //输出到文件
    //注册输出表
    val output="D:\\workspace\\ideastudy\\flinkstudy\\src\\main\\resources\\output.txt"
    tableEnv.connect(new FileSystem().path(output))
      .withFormat(new Csv())
      .withSchema(new Schema()
        .field("id",DataTypes.STRING())
        .field("temp",DataTypes.DOUBLE())
      )
      .createTemporaryTable("outputTable")


    resultTable.insertInto("outputTable")
    //下面这个会报错,insertInfo 输出到文件是属于 AppendStreamTableSink  只能是插入的操作 不能是
    //更新类的,原有的格式 要和输出的格式一致才可以写入
    aggTable.insertInto("outputTable")

    env.execute("file sink")
  }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值