FlinkSQL的读入和写出数据

读取数据

file类型的source

package day06;

import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.DataTypes;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.java.StreamTableEnvironment;
import org.apache.flink.table.descriptors.FileSystem;
import org.apache.flink.table.descriptors.OldCsv;
import org.apache.flink.table.descriptors.Schema;
import org.apache.flink.table.types.DataType;
import org.apache.flink.types.Row;

public class FlinkSQL03_Source_File {

    public static void main(String[] args) throws Exception {

        //1、创建执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        //获取TableAPI执行环境
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        //2、构建文件的连接器
        //这里的path是指的是文件名
        //从文件sensor中读取数据数据,然后将数据放到一张零时表中。
        tableEnv.connect(new FileSystem().path("sensor"))
                .withFormat(new OldCsv())
                .withSchema(new Schema()
                .field("id", DataTypes.STRING())
                .field("ts",DataTypes.BIGINT())
                .field("temp",DataTypes.DOUBLE())
                )
                .createTemporaryTable("sensorTable");
           //source是追加流,因为是一条一条的进来的。

        
        //---------下面的部分相当于不属于source。往外对接的时候,往一些地方写的时候,作为输入流,是支持撤回流的。

         //3、读取数据创建表,通过 TableAPI 查询算子,得到一张表。
        Table sensortable = tableEnv.from("sensorTable");

        //4、TableAPI,然后通过继续查询得到想要的表。
        Table  tableResult = sensortable.select("id,temp").where("id='sensor_1'");

        //5、SQL方式
        Table sqlResult = tableEnv.sqlQuery("select id,ts from sensorTable where id ='sensor_7'");

        //6、转换成流打印输出
        
        //从文件章中读取的数据,不能使用聚合函数,也就是最后的输出流是追加流。
       tableEnv.toAppendStream(tableResult, Row.class).print("Table");
       tableEnv.toAppendStream(sqlResult,Row.class).print("SQL");

        //7、执行
        env.execute();
    }

}

kafka类型的source

package day06;

import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.DataTypes;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.java.StreamTableEnvironment;
import org.apache.flink.table.descriptors.Csv;
import org.apache.flink.table.descriptors.Json;
import org.apache.flink.table.descriptors.Kafka;
import org.apache.flink.table.descriptors.Schema;
import org.apache.flink.types.Row;
import org.apache.kafka.clients.consumer.ConsumerConfig;

public class FlinkSQL04_Source_Kafka {

    public static void main(String[] args) throws Exception {

        //1.创建执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        //获取TableAPI执行环境
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        //2.创建Kafka的连接器
        tableEnv.connect(new Kafka()
                .version("0.11")
                .topic("test")
                .property(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "hadoop102:9092")
                .property(ConsumerConfig.GROUP_ID_CONFIG, "BigData0720"))
                //.withFormat(new Csv())
                .withFormat(new Json())
                .withSchema(new Schema()
                        .field("id", DataTypes.STRING())
                        .field("ts", DataTypes.BIGINT())
                        .field("temp", DataTypes.DOUBLE()))
                .createTemporaryTable("kafka");

        //这里说的是进来的source,是source,将数据读取到一张临时表中.

        
        
//---------------------------------------------------------------------        
        
       //---Table API的做法 
        //3.创建表
        Table table = tableEnv.from("kafka");

        //4.TableAPI
        Table tableResult = table.groupBy("id").select("id,temp.max");
//---------------------------------------------------------------------       
        
        //--SQL
        //5.SQL的做法
        Table sqlResult = tableEnv.sqlQuery("select id,min(temp) from kafka group by id");

        //6.转换为流进行输出
        
        //上面用了聚合函数,所以这里用的是可撤回流。
        tableEnv.toRetractStream(tableResult, Row.class).print("Table");
        tableEnv.toRetractStream(sqlResult, Row.class).print("SQL");

        //7.执行
        env.execute();


        // bin/kafka-console-producer.sh  --broker-list hadoop102:9092 --topic test
        //   {"id":"sensor_1","ts":"15477112198","temp":"46.8"}

    }

}

输出数据

file类型的sink

package day06;

import bean.SensorReading;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.DataTypes;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.java.StreamTableEnvironment;
import org.apache.flink.table.descriptors.FileSystem;
import org.apache.flink.table.descriptors.OldCsv;
import org.apache.flink.table.descriptors.Schema;

public class FlinkSQL05_Sink_File {

    public static void main(String[] args) throws Exception {

        //1.获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        //获取TableAPI执行环境
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        //2.读取端口数据转换为JavaBean
        SingleOutputStreamOperator<SensorReading> sensorDS = env.socketTextStream("hadoop102", 9999)
                .map(line -> {
                    String[] fields = line.split(",");
                    return new SensorReading(fields[0],
                            Long.parseLong(fields[1]),
                            Double.parseDouble(fields[2]));
                });

    //-----------常规套路部分。

   //因为我们要做的是sink,所以还没有collect,我们collect的输出端,所以不能创建临时表。
   
       //对于用tableAPI的方式,先是将流转换为表,然后从这张表中查询,得到一张表。
	   //对于sql的这种方式,是用流创建一个临时视图,然后从临时视图中查询,得到一张表。
	   //这两张表将起到中介的作用,将来临时表通过这里的表进行传输到外部的文件。
	   

        //3.对流进行注册,从流中创建表。
        Table table = tableEnv.fromDataStream(sensorDS);

        //4.TableAPI
        Table tableResult = table.select("id,temp");   //将查询的数据放到tableresult这张表中。

        //5.SQL
        tableEnv.createTemporaryView("sensor", sensorDS);                      //将流的数据给了临时视图sensor。这里的视图相当于是一张临时表。
        Table sqlResult = tableEnv.sqlQuery("select id,temp from sensor");    //然后用SQL查询时查询这个视图中的数据,放到sqlResult表中。

   //-----------------写入到文件系统中

        //6.创建文件连接器
		
		//输出路径:tableOut,这是一个文件,在idea上可以看到它的位置。
		//输出的表名:outTable1,临时表,在idea上看不到,因为时临时的。
		
		
		//创建文件连接器,只有collect之后才能创建临时表。
        
        //对于输出到的是文件来说
        //发现,只有collect后面的new xxx() 之后的那个path才是正在的文件的路径。
        tableEnv.connect(new FileSystem().path("tableOut"))
                .withFormat(new OldCsv())
                .withSchema(new Schema()
                        .field("id", DataTypes.STRING())
                        .field("temp", DataTypes.DOUBLE()))
                .createTemporaryTable("outTable1");


        tableEnv.connect(new FileSystem().path("sqlOut"))
                .withFormat(new OldCsv())
                .withSchema(new Schema()
                        .field("id", DataTypes.STRING())
                        .field("temp", DataTypes.DOUBLE()))
                .createTemporaryTable("outTable2");


        //7.将数据写入文件系统
		
		//tableResult中的数据通过临时表,将数据放到tableOut这个文件中。
        tableEnv.insertInto("outTable1", tableResult);
		//sqlResult中的数据通过临时表,将数据放到sqlOut这个文件中。
        tableEnv.insertInto("outTable2", sqlResult);

        
        //8.执行
        env.execute();

    }

}

kafka类型的sink

package day06;

import bean.SensorReading;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.DataTypes;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.java.StreamTableEnvironment;
import org.apache.flink.table.descriptors.*;
import org.apache.kafka.clients.producer.ProducerConfig;

public class FlinkSQL06_Sink_Kafka {

    public static void main(String[] args) throws Exception {

        //1.获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        //获取TableAPI执行环境
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        //2.读取端口数据转换为JavaBean
        SingleOutputStreamOperator<SensorReading> sensorDS = env.socketTextStream("hadoop102", 9999)
                .map(line -> {
                    String[] fields = line.split(",");
                    return new SensorReading(fields[0],
                            Long.parseLong(fields[1]),
                            Double.parseDouble(fields[2]));
                });

  //对传过来的数据进行处理,最后发给Kafka,也就是sink连接至Kafka。是写出的方式,这里用到的是一个insertinto方法。表明直接写出。
  //Kafka也在官网上规定了,只能直接输出,不能用撤回流或者修改的那中方式。      
        
        //3.对流进行注册
        Table table = tableEnv.fromDataStream(sensorDS);

        //4.TableAPI
        Table tableResult = table.select("id,temp");

        //5.SQL
        tableEnv.createTemporaryView("sensor", sensorDS);
        Table sqlResult = tableEnv.sqlQuery("select id,temp from sensor");

        //6.创建Kafka连接器
        tableEnv.connect(new Kafka()
                .topic("test")
                .version("0.11")
                .property(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "hadoop102:9092"))
                //.withFormat(new Json())
                .withFormat(new Csv())
                .withSchema(new Schema()
                        .field("id", DataTypes.STRING())
                        .field("temp", DataTypes.DOUBLE()))
                .createTemporaryTable("kafkaOut");

        
        //7.将数据写入文件系统
        tableEnv.insertInto("kafkaOut", tableResult);  //临时表kafkaOut通过tableResult,写到Kafka。
        tableEnv.insertInto("kafkaOut", sqlResult);    //临时表kafkaOut通过tableResult,写到Kafka。

        //8.执行
        env.execute();

    }

}
kafka到kafka
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.DataTypes;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.java.StreamTableEnvironment;
import org.apache.flink.table.descriptors.Csv;
import org.apache.flink.table.descriptors.Kafka;
import org.apache.flink.table.descriptors.Schema;
import org.apache.flink.types.Row;

public class FlinkSQL_Test06 {

    public static void main(String[] args) throws Exception {

        //1.创建执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        //2.定义Kafka输入描述器,创建临时表.
        tableEnv.connect(new Kafka()
                .version("0.11")
                .topic("test")   //主题。
                .property("bootstrap.servers", "hadoop102:9092")) 
                .withFormat(new Csv())
                .withSchema(
                new Schema()
                .field("id", DataTypes.STRING())
                .field("ts", DataTypes.BIGINT())
                .field("temp", DataTypes.DOUBLE()) 
                 )
                .createTemporaryTable("KafkaInput");  //创建临时表。


        //4.执行SQL查询数据
        Table table = tableEnv.sqlQuery("select id,temp from KafkaInput where id='sensor_1'");

        //5.定义Kafka输出连接器,创建临时表。
       tableEnv.connect(new Kafka()
                .version("0.11")
                .topic("sinkTest")   //主题。
                .property("bootstrap.servers", "hadoop102:9092")) 
                .withFormat(new Csv())
                .withSchema(
                 new Schema()
                .field("id", DataTypes.STRING())  //我们select的时候就选择了这连个字段,最后查询出来就是这两个字段。
               .field("temp", DataTypes.DOUBLE())
                )            
                .createTemporaryTable("KafkaOutPut"); //创建临时表。

        //6.将数据输出到Kafka的另一个主题
        tableEnv.insertInto("KafkaOutPut", table);

        //7.执行任务
        env.execute();

    }

}

ES类型的Sink

ES知识点回顾
PUT stu
{
  "mappings": {
    "_doc":{
      "properties":{
        "id":{
          "type":"keyword"
        },
        "name":{
          "type":"text"
        },
        "sex":{
          "type":"integer"
        },
        "birth":{
          "type":"date"
        }
      }
    }
  }
}

—————————————华丽分割符————————————————
###############对上面命令做个简单解释
PUT stu (stu类似于MySQL中的数据库名)
{
  "mappings": {	("mappings"可以理解为建表语句 create table关键字)
    "_doc":{		("_doc"相当于MySQL中表名)
      "properties":{	("properties"相当于建表语句中要指定字段及字段类型的关键字)"id":{           (" id "相当于具体某个字段)
          "type":"keyword""type"相当于要指定字段类型的关键字,"keyword "相当于字段的具体类型)

        },
        "name":{
          "type":"text"
        },
        "sex":{
          "type":"integer"
        },
        "birth":{
          "type":"date"
        }
      }
    }
  }
}
//---创建文档

PUT stu/_doc/1001
{
  "id":"001",
  "name":"红红",
  "sex":0,
  "birth":"1999-01-01"
}

—————————————华丽分割符————————————————
###############对上面命令做个简单解释
PUT stu/_doc/1001  (相当于指定要插入到哪个库的哪个表的哪个id中,类似于hbase的rowkey)
{
  "id":"001",		(字段具体的值)
  "name":"红红",
  "sex":0,
  "birth":"1999-01-01"
}


//----
GET stu/_search
输出结果如下:
{
  "took" : 9,
  "timed_out" : false,
  "_shards" : {
    "total" : 5,  (切片总数)
    "successful" : 
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {   (命中)
    "total" : 1, (命中总数一条)
    "max_score" : 1.0, (数据在里面存储的时候是有一个评分,这个评分是按照搜索的关键字跟文章的匹配度得来的,如果这个关键字在文章中出现频率较高,这个分数也相应的较大)
    "hits" : [
      {
        "_index" : "stu",
        "_type" : "_doc",
        "_id" : "1001",   //在表中的位置。
        "_score" : 1.0,
        "_source" : {  (具体的数据)
          "id" : "001",
          "name" : "红红",
          "sex" : 0,
          "birth" : "1999-01-01"
                   }
      }
    ]
  }
}
package day06;

import bean.SensorReading;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.DataTypes;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.java.StreamTableEnvironment;
import org.apache.flink.table.descriptors.*;
import org.apache.kafka.clients.producer.ProducerConfig;

public class FlinkSQL07_Sink_ES {

    public static void main(String[] args) throws Exception {

        //1.获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        //获取TableAPI执行环境
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        //2.读取端口数据转换为JavaBean
        SingleOutputStreamOperator<SensorReading> sensorDS = env.socketTextStream("hadoop102", 9999)
                .map(line -> {
                    String[] fields = line.split(",");
                    return new SensorReading(fields[0],
                            Long.parseLong(fields[1]),
                            Double.parseDouble(fields[2]));
                });

        //3.对流进行注册
        Table table = tableEnv.fromDataStream(sensorDS);

        //4.TableAPI
        Table tableResult = table.select("id,temp");

        //5.SQL,从输入的流中创建临时表。
        tableEnv.createTemporaryView("sensor", sensorDS);
        Table sqlResult = tableEnv.sqlQuery("select id,temp from sensor");

        //6.创建ES连接器
        tableEnv.connect(new Elasticsearch()
                .version("6")  //es的版本
                .host("hadoop102", 9200, "http")
                .index("sensor1")        //索引(也就是数据库)
                .documentType("_doc")    //文档所属类型名,相当于MySQL中的表名。
                .bulkFlushMaxActions(1))  //来一条刷写一次
                .withFormat(new Json())   //json格式
                .withSchema(new Schema()
                        .field("id", DataTypes.STRING())
                        .field("temp", DataTypes.DOUBLE()))
                .inAppendMode()              //用的追加模式,es中的id是随机给的。
                .createTemporaryTable("Es");

        //7.将数据写入文件系统,这里的insert只是一个方法,不是流。
       tableEnv.insertInto("Es", tableResult);//临时表Es中的数据,经过表tableResult发送到Elasticsearch。
       tableEnv.insertInto("Es", sqlResult);//临时表Es中的数据,经过表sqlResult发送到Elasticsearch。

        //8.执行
        env.execute();

    }

}
kafka写到ES当中
package day06;

import bean.SensorReading;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.DataTypes;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.java.StreamTableEnvironment;
import org.apache.flink.table.descriptors.*;
import org.apache.kafka.clients.producer.ProducerConfig;

public class FlinkSQL07_Sink_ES {

    public static void main(String[] args) throws Exception {

        //1.获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        //获取TableAPI执行环境
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);


        //2.定义Kafka输入描述器,创建临时表.
        tableEnv.connect(new Kafka()
                .version("0.11")
                .topic("test")   //主题。
                .property("bootstrap.servers", "hadoop102:9092")) 
                .withFormat(new Csv())
                .withSchema(
                new Schema()
                .field("id", DataTypes.STRING())
                .field("ts", DataTypes.BIGINT())
                .field("temp", DataTypes.DOUBLE()) 
                 )
                .createTemporaryTable("KafkaInput");  //创建临时表。


        //5.SQL
        Table sqlResult = tableEnv.sqlQuery("select id,temp from KafkaInput");

        //6.创建ES连接器
        tableEnv.connect(new Elasticsearch()
                .version("6")
                .host("hadoop102", 9200, "http")
                .index("sensor1")
                .documentType("_doc")
                .bulkFlushMaxActions(1))
                .withFormat(new Json())
                .withSchema(new Schema()
                        .field("id", DataTypes.STRING())
                        .field("temp", DataTypes.DOUBLE()))
                .inAppendMode()              //用的追加模式,es中的id是随机给的。
                .createTemporaryTable("Es"); //创建临时表。

        //7.将数据写入文件系统,这里的insert只是一个方法,不是流。
       tableEnv.insertInto("Es", sqlResult);//临时表Es中的数据,经过表sqlResult发送到Elasticsearch。

        //8.执行
        env.execute();

    }

}
例子

使用FlinkSQL实现从Kafka读取数据计算WordCount并将数据写入ES中

package practice;

import bean.word;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer011;
import org.apache.flink.table.api.DataTypes;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.java.StreamTableEnvironment;
import org.apache.flink.table.descriptors.*;
import org.apache.flink.types.Row;
import org.apache.flink.util.Collector;
import org.apache.kafka.clients.consumer.ConsumerConfig;

import java.util.Properties;



/**
 * @author zb
 * @create 2020-12-18 8:32
 */
//输入数据如下:
//hello,atguigu,hello
//hello,spark
//hello,flink
//
//使用FlinkSQL实现从Kafka读取数据计算WordCount并将数据写入ES中




public class Flink08 {
    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        //2.从Kafka读取数据创建流
        Properties properties = new Properties();
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "hadoop102:9092");
        properties.put(ConsumerConfig.GROUP_ID_CONFIG, "Bigdata");
        properties.setProperty("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        properties.setProperty("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        properties.setProperty("auto.offset.reset", "latest");

        DataStreamSource<String> sensorDS = env.addSource(new FlinkKafkaConsumer011<String>(
                "test",
                new SimpleStringSchema(),
                properties));


        SingleOutputStreamOperator<word> wordDS = sensorDS.flatMap(new FlatMapFunction<String, word>() {
            @Override
            public void flatMap(String value, Collector<word> out) throws Exception {
                String[] fields = value.split(",");
                for (String field : fields) {
                    out.collect(new word(field, 1L));
                }
            }
        });


        //5.SQL
        tableEnv.createTemporaryView("wordDS", wordDS);
        Table sqlResult = tableEnv.sqlQuery("select id,count(id) ct from wordDS group by id");

        //6.创建ES连接器
        tableEnv.connect(new Elasticsearch()
                .version("6")
                .host("hadoop102", 9200, "http")
                .index("wordcount")
                .documentType("_doc")
                .bulkFlushMaxActions(1))
                .withFormat(new Json())
                .withSchema(new Schema()
                        .field("id", DataTypes.STRING())
                        .field("ct", DataTypes.BIGINT()))
                .inUpsertMode()
                .createTemporaryTable("Es");

        tableEnv.toRetractStream(sqlResult, Row.class).print();
        tableEnv.insertInto("Es", sqlResult);

        //7.执行
        env.execute();
    }
}

//开窗,事件时间只看WeaterMark


package bean;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @author zb
 * @create 2020-12-11 10:47
 */

@Data
@NoArgsConstructor
@AllArgsConstructor
public class word {
    private String id;
    private Long count;

}

Sink_ES_Upsert

package day06;

import bean.SensorReading;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.DataTypes;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.java.StreamTableEnvironment;
import org.apache.flink.table.descriptors.Elasticsearch;
import org.apache.flink.table.descriptors.Json;
import org.apache.flink.table.descriptors.Schema;
import org.apache.flink.types.Row;

public class FlinkSQL08_Sink_ES_Upsert {

    public static void main(String[] args) throws Exception {

        //1.获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        //获取TableAPI执行环境
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        //2.定义Kafka输入描述器,创建临时表.
        tableEnv.connect(new Kafka()
                .version("0.11") //Kafka的版本。
                .topic("test")   //主题。
                .property("bootstrap.servers", "hadoop102:9092")) 
                .withFormat(new Csv())
                .withSchema(
                new Schema()
                .field("id", DataTypes.STRING())
                .field("ts", DataTypes.BIGINT())
                .field("temp", DataTypes.DOUBLE()) 
                 )
                .createTemporaryTable("KafkaInput");  //创建临时表。


        //5.SQL
        Table sqlResult = tableEnv.sqlQuery("select id,min(temp) from KafkaInput group by id");

        //6.创建ES连接器
        tableEnv.connect(new Elasticsearch()
                .version("6")   //es的版本。
                .host("hadoop102", 9200, "http")
                .index("sensor4")
                .documentType("_doc")
                .bulkFlushMaxActions(1))
                .withFormat(new Json())
                .withSchema(new Schema()
                        .field("id", DataTypes.STRING())
                        .field("ts", DataTypes.BIGINT())
                        .field("temp", DataTypes.DOUBLE()))
                .inUpsertMode()  //用的是upsert模式。
                .createTemporaryTable("Es");

        //7.将数据写入文件系统
        tableEnv.insertInto("Es", sqlResult);

        //8.执行
        env.execute();

    }

}

需要注意的地方:

//-----TableApi-需要注意的一点是:

 Table table = tableEnv.fromDataStream(sensorDS);
 Table tableResult = table.groupBy("id,ts").select("id,ts,temp.min");


  我们要添加字段的时候,在ES中添加之外,也就是这里添加field的时候
      .withSchema(new Schema()
                        .field("id", DataTypes.STRING())
                        .field("ts", DataTypes.BIGINT())
                        .field("temp", DataTypes.DOUBLE()))

要注意的是,查询语句中,这些字段都是会出现的,如果一个是出现在group by之后,那么其他的肯定出现在聚合函数里面。

group by后面字段,作为ES中的doc_id。

两个流进行测试的时候,第一个流进行写入到ES之后,注释掉之后,换成另一个流的时候,因为是一条新的流,流中没有进行可以比较的数据,它的布尔值是一个true,那么就会写到ES里面,那么同一个id下的数据就会被覆盖掉。因为系统里面已经有数据了,没有办法和其他的流之前写入的数据进行比较,所以会覆盖掉。
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值