Flink常见维表Join方案,收藏学习开发很有用!

大数据
由于维表是一张不断变化的表(静态表只是动态表的一种特例)。那如何 JOIN 一张不断变化的表呢?如果用传统的 JOIN 语法来表达维表 JOIN,是不完整的。因为维表是一直在更新变化的,如果用这个语法那么关联上的是哪个时刻的维表呢?我们是不知道的,结果是不确定的。

本文转载自微信公众号「大数据左右手」,作者左右 。转载本文请联系大数据左右手公众号。

前言

实时数仓,难免会遇到join维表的业务。现总结几种方案,供各位看官选择:

  • 查找关联(同步,异步)
  • 状态编程,预加载数据到状态中,按需取
  • 冷热数据
  • 广播维表
  • Temporal Table Join
  • Lookup Table Join

其中中间留下两个问题,供大家思考,可留言一起讨论?

查找关联

查找关联就是在主流数据中直接访问外部数据(mysql,redis,impala ...)去根据主键或者某种关键条件去关联取值。

适合: 维表数据量大,但是主数据不大的业务实时计算。

缺点:数据量大的时候,会给外部数据源库带来很大的压力,因为某条数据都需要关联。

同步

访问数据库是同步调用,导致 subtak 线程会被阻塞,影响吞吐量

  1. import com.alibaba.fastjson.{JSON, JSONArray, JSONObject} 
  2. import com.wang.stream.env.{FlinkStreamEnv, KafkaSourceEnv} 
  3. import org.apache.flink.api.common.functions.FlatMapFunction 
  4. import org.apache.flink.api.common.serialization.SimpleStringSchema 
  5. import org.apache.flink.streaming.api.scala._ 
  6. import org.apache.flink.streaming.connectors.kafka.FlinkKafkaProducer 
  7. import org.apache.flink.util.Collector 
  8.  
  9.  def analyses(): Unit ={ 
  10.     val env: StreamExecutionEnvironment = FlinkStreamEnv.get() 
  11.     KafkaSourceEnv.getKafkaSourceStream(env,List("test")) 
  12.       .map(JSON.parseObject(_)) 
  13.       .filter(_!=null
  14.       .flatMap( 
  15.         new FlatMapFunction[JSONObject,String] { 
  16.           override def flatMap(jSONObject: JSONObject, collector: Collector[String]): Unit = { 
  17.             // 如果topic就一张表,不用区分,如果多张表,可以通过database 与 table 区分,放到下一步去处理 
  18.             // 表的名字 
  19.             val databaseName:String = jSONObject.getString("database"
  20.             // 表的名字 
  21.             val tableName:String = jSONObject.getString("table"
  22.             // 数据操作类型 INSERT UPDATE DELETE 
  23.             val operationType:String = jSONObject.getString("type"
  24.             // 主体数据 
  25.             val tableData: JSONArray = jSONObject.getJSONArray("data"
  26.             // old 值 
  27.             val old: JSONArray = jSONObject.getJSONArray("old"
  28.             // canal json 可能存在批处理出现data数据多条 
  29.             for (i <- 0 until tableData.size()) { 
  30.               val data: String = tableData.get(i).toString 
  31.               val nObject: JSONObject = JSON.parseObject(data) 
  32.               val orderId: AnyRef = nObject.get("order_id"
  33.               // 下面写(mysql,redis或者hbase)的连接,利用api 通过orderId查找 
  34.                
  35.               // 最后封装数据格式 就是join所得 
  36.               collector.collect(null
  37.             } 
  38.           } 
  39.         } 
  40.       ) 
  41.       .addSink( 
  42.         new FlinkKafkaProducer[String]( 
  43.           ""
  44.           ""
  45.           new SimpleStringSchema() 
  46.         ) 
  47.       ) 
  48.     env.execute(""

异步

AsyncIO 可以并发地处理多个请求,很大程度上减少了对 subtask 线程的阻塞。

  1. def analyses(): Unit ={ 
  2.     val env: StreamExecutionEnvironment = FlinkStreamEnv.get() 
  3.     val source: DataStream[String] = KafkaSourceEnv.getKafkaSourceStream(env, List("test")) 
  4.       .map(JSON.parseObject(_)) 
  5.       .filter(_ != null
  6.       .flatMap( 
  7.         new FlatMapFunction[JSONObject, String] { 
  8.           override def flatMap(jSONObject: JSONObject, collector: Collector[String]): Unit = { 
  9.             // 如果topic就一张表,不用区分,如果多张表,可以通过database 与 table 区分,放到下一步去处理 
  10.             // 表的名字 
  11.             val databaseName: String = jSONObject.getString("database"
  12.             // 表的名字 
  13.             val tableName: String = jSONObject.getString("table"
  14.             // 数据操作类型 INSERT UPDATE DELETE 
  15.             val operationType: String = jSONObject.getString("type"
  16.             // 主体数据 
  17.             val tableData: JSONArray = jSONObject.getJSONArray("data"
  18.             // old 值 
  19.             val old: JSONArray = jSONObject.getJSONArray("old"
  20.             // canal json 可能存在批处理出现data数据多条 
  21.             for (i <- 0 until tableData.size()) { 
  22.               val data: String = tableData.get(i).toString 
  23.               collector.collect(data) 
  24.             } 
  25.           } 
  26.         } 
  27.       ) 
  28.        
  29.     AsyncDataStream.unorderedWait( 
  30.       source, 
  31.       new RichAsyncFunction[String,String] {//自定义的数据源异步处理类 
  32.         override def open(parameters: Configuration): Unit = { 
  33.           // 初始化 
  34.         } 
  35.         override def asyncInvoke(input: String, resultFuture: ResultFuture[String]): Unit = { 
  36.            
  37.           // 将数据搜集 
  38.           resultFuture.complete(null
  39.        } 
  40.  
  41.         override def close(): Unit = { 
  42.           // 关闭 
  43.         } 
  44.     }, 
  45.     1000,//异步超时时间 
  46.     TimeUnit.MILLISECONDS,//时间单位 
  47.     100)//最大异步并发请求数量 
  48.      .addSink( 
  49.         new FlinkKafkaProducer[String]( 
  50.           ""
  51.           ""
  52.           new SimpleStringSchema() 
  53.         ) 
  54.       ) 
  55.  
  56.     env.execute(""
  57.   } 

状态编程,预加载数据到状态中,按需取

首先把维表数据初始化到state中,设置好更新时间,定时去把维表。

优点:flink 自己维护状态数据,"荣辱与共",不需要频繁链接外部数据源,达到解耦。

缺点:不适合大的维表和变化大的维表。

  1. .keyBy(_._1) 
  2. .process( 
  3.   new KeyedProcessFunction[String,(String,String,String,String,String), String]{ 
  4.     private var mapState:MapState[String,Map[String,String]] = _ 
  5.     private var first: Boolean = true 
  6.      
  7.     override def open(parameters: Configuration): Unit = { 
  8.       val config: StateTtlConfig = StateTtlConfig 
  9.         .newBuilder(org.apache.flink.api.common.time.Time.minutes(5)) 
  10.         .setUpdateType(StateTtlConfig.UpdateType.OnReadAndWrite) 
  11.         .setStateVisibility(StateTtlConfig.StateVisibility.NeverReturnExpired) 
  12.         .build() 
  13.       val join = new MapStateDescriptor[String,Map[String,String]]("join",classOf[String],classOf[Map[String,String]]) 
  14.       join.enableTimeToLive(config) 
  15.       mapState = getRuntimeContext.getMapState(join
  16.     } 
  17.     override def processElement( 
  18.                                  in: (String, String, String, String, String), 
  19.                                  context: KeyedProcessFunction[String, (String, String, String, String, String),String]#Context, 
  20.                                  collector: Collector[String]): Unit = { 
  21.       // 加载维表 
  22.       if(first){ 
  23.         first = false 
  24.         val time: Long = System.currentTimeMillis() 
  25.         getSmallDimTableInfo() 
  26.         // 设置好更新时间,定时去把维表 
  27.         context.timerService().registerProcessingTimeTimer(time + 86400000) 
  28.       } 
  29.        
  30.       // 数据处理,过来一条条数据,然后按照自己的业务逻辑去取维表的数据即可 
  31.        
  32.       // 然后封装 放到collect中 
  33.       collector.collect(null
  34.     } 
  35.  
  36.     override def onTimer( 
  37.                           timestamp: Long, 
  38.                           ctx: KeyedProcessFunction[String, (String, String, String, String, String),String]#OnTimerContext, 
  39.                           out: Collector[String]): Unit = { 
  40.       println("触发器执行"
  41.       mapState.clear() 
  42.       getSmallDimTableInfo() 
  43.       println(mapState) 
  44.       ctx.timerService().registerProcessingTimeTimer(timestamp + 86400000) 
  45.     } 
  46.     def getSmallDimTableInfo(): Unit ={ 
  47.  
  48.       // 加载 字典数据 
  49.       val select_dictionary="select dic_code,pre_dictionary_id,dic_name from xxxx" 
  50.       val dictionary: util.List[util.Map[String, AnyRef]] = MysqlUtil.executeQuery(select_dictionary, null
  51.       dictionary.foreach(item=>{ 
  52.         mapState.put("dic_dictionary_"+item.get("pre_dictionary_id").toString,item) 
  53.       }) 
  54.  
  55.     } 
  56.   } 
  57. .filter(_!=null
  58. .addSink( 
  59.   new FlinkKafkaProducer[String]( 
  60.     ""
  61.     ""
  62.     new SimpleStringSchema() 
  63.   ) 
  64. v.execute(""

思考下:直接定义一个Map集合这样的优缺点是什么?可以留言说出自己的看法?

冷热数据

思想:先去状态去取,如果没有,去外部查询,同时去存到状态里面。StateTtlConfig 的过期时间可以设置短点。

优点:中庸取值方案,热备常用数据到内存,也避免了数据join相对过多外部数据源。

缺点:也不能一劳永逸解决某些问题,热备数据过多,或者冷数据过大,都会对state 或者 外部数据库造成压力。

  1. .filter(_._1 != null
  2. .keyBy(_._1) 
  3. .process( 
  4.   new KeyedProcessFunction[String,(String,String,String,String,String), String]{ 
  5.     private var mapState:MapState[String,Map[String,String]] = _ 
  6.     private var first: Boolean = true 
  7.     override def open(parameters: Configuration): Unit = { 
  8.       val config: StateTtlConfig = StateTtlConfig 
  9.         .newBuilder(org.apache.flink.api.common.time.Time.days(1)) 
  10.         .setUpdateType(StateTtlConfig.UpdateType.OnReadAndWrite) 
  11.         .setStateVisibility(StateTtlConfig.StateVisibility.NeverReturnExpired) 
  12.         .build() 
  13.       val join = new MapStateDescriptor[String,Map[String,String]]("join",classOf[String],classOf[Map[String,String]]) 
  14.       join.enableTimeToLive(config) 
  15.       mapState = getRuntimeContext.getMapState(join
  16.     } 
  17.     override def processElement( 
  18.                                  in: (String, String, String, String, String), 
  19.                                  context: KeyedProcessFunction[String, (String, String, String, String, String),String]#Context, 
  20.                                  collector: Collector[String]): Unit = { 
  21.  
  22.       // 数据处理,过来一条条数据,然后按照自己的业务逻辑先去mapState去找,如果没有再去 外部去找 
  23.       if (mapState.contains("xx_id")){ 
  24.         // 如果存在就取 
  25.  
  26.       }else
  27.         // 如果不存在去外部拿,然后放到mapState中 
  28.         val dim_sql="select dic_code,pre_dictionary_id,dic_name from xxxx where id=xx_id" 
  29.         val dim: util.List[util.Map[String, AnyRef]] = MysqlUtil.executeQuery(dim_sql, null
  30.         mapState.put("xx_id",null
  31.       } 
  32.       // 然后封装 放到collect中 
  33.       collector.collect(null
  34.     } 
  35.   } 

广播维表

比如上面提到的字典表,每一个Task都需要这份数据,那么需要join这份数据的时候就可以使用广播维表。

  1. val dimStream=env.addSource(MysqlSource) 
  2.  
  3. // 广播状态 
  4. val broadcastStateDesc=new MapStateDescriptor[String,String]("broadcaststate", BasicTypeInfo.STRING_TYPE_INFO, new MapTypeInfo<>(Long.class, Dim.class)) 
  5.  
  6. // 广播流 
  7. val broadStream=dimStream.broadcast() 
  8.  
  9. // 主数据流 
  10. val mainConsumer = new FlinkKafkaConsumer[String]("topic", new SimpleStringSchema(), kafkaConfig) 
  11.  
  12. val mainStream=env.addSource(mainConsumer) 
  13.  
  14. // 广播状态与维度表关联 
  15. val connectedStream=mainStream.connect(broadStream).map(..User(id,name)).key(_.1) 
  16.  
  17. connectedStream.process(new KeyedBroadcastProcessFunction[String,User,Map[Long,Dim],String] { 
  18.  
  19.      override def processElement(value: User, ctx: KeyedBroadcastProcessFunction[String,User,Map[Long,Dim],String]#ReadOnlyContext, out: Collector[String]): Unit = { 
  20.       // 取到数据就可以愉快的玩耍了 
  21.      val state=ctx.getBroadcastState(broadcastStateDesc) 
  22.        xxxxxx 
  23.          
  24.   } 

「思考:」 如果把维表流也通过实时监控binlog到kafka,当维度数据发生变化时,更新放到状态中,这种方式,是不是更具有时效性呢?

(1)通过canal把变更binlog方式发送到kafka中。

(2)数据流定义成为广播流,广播到数据到主数据流中。

(3)定义一个广播状态存储数据,在主数据进行查找匹配,符合要求则join成功。

Temporal Table Join(FlinkSQL与Flink Table API)

由于维表是一张不断变化的表(静态表只是动态表的一种特例)。那如何 JOIN 一张不断变化的表呢?如果用传统的 JOIN 语法来表达维表 JOIN,是不完整的。因为维表是一直在更新变化的,如果用这个语法那么关联上的是哪个时刻的维表呢?我们是不知道的,结果是不确定的。所以 Flink SQL 的维表 JOIN 语法引入了Temporal Table 的标准语法,用来声明关联的是维表哪个时刻的快照。

普通关联会一直保留关联双侧的数据,数据也就会一直膨胀,直到撑爆内存导致任务失败,Temporal Join则可以定期清理过期数据,在合理的内存配置下即可避免内存溢出。

Event Time Temporal Join

语法

  1. SELECT [column_list] 
  2. FROM table1 [AS <alias1>] 
  3. [LEFTJOIN table2 FOR SYSTEM_TIME AS OF table1.{ proctime | rowtime } [AS <alias2>] 
  4. ON table1.column-name1 = table2.column-name1 

使用事件时间属性(即行时间属性),可以检索过去某个时间点的键值。这允许在一个共同的时间点连接两个表。

举例

假设我们有一个订单表,每个订单都有不同货币的价格。为了将此表正确地规范化为单一货币,每个订单都需要与下订单时的适当货币兑换率相结合。

  1. CREATE TABLE orders ( 
  2.     order_id    STRING, 
  3.     price       DECIMAL(32,2), 
  4.     currency    STRING, 
  5.     order_time  TIMESTAMP(3), 
  6.     WATERMARK FOR order_time AS order_time 
  7. WITH (/* ... */); 
  8.  
  9.  
  10. CREATE TABLE currency_rates ( 
  11.     currency STRING, 
  12.     conversion_rate DECIMAL(32, 2), 
  13.     update_time TIMESTAMP(3) METADATA FROM `values.source.timestamp` VIRTUAL 
  14.     WATERMARK FOR update_time AS update_time, 
  15.     PRIMARY KEY(currency) NOT ENFORCED 
  16. WITH ( 
  17.    'connector' = 'upsert-kafka'
  18.    /* ... */ 
  19. ); 
  20.  
  21. event-time temporal join需要temporal join条件的等价条件中包含的主键 
  22.  
  23. SELECT  
  24.      order_id, 
  25.      price, 
  26.      currency, 
  27.      conversion_rate, 
  28.      order_time, 
  29. FROM orders 
  30. LEFT JOIN currency_rates FOR SYSTEM TIME AS OF orders.order_time 
  31. ON orders.currency = currency_rates.currency 

Processing Time Temporal Join

处理时间时态表连接使用处理时间属性将行与外部版本表中键的最新版本相关联。

根据定义,使用processing-time属性,连接将始终返回给定键的最新值。可以将查找表看作是一个简单的HashMap,它存储来自构建端的所有记录。这种连接的强大之处在于,当在Flink中无法将表具体化为动态表时,它允许Flink直接针对外部系统工作。

使用FOR SYSTEM_TIME AS OF table1.proctime表示当左边表的记录与右边的维表join时,只匹配当前处理时间维表所对应的的快照数据。

Lookup Table Join

Lookup Join 通常用于通过连接外部表(维度表)补充信息,要求一个表具有处理时间属性,另一个表使 Lookup Source Connector。

JDBC 连接器可以用在时态表关联中作为一个可 lookup 的 source (又称为维表)。用到的语法是 Temporal Joins 的语法。

  1. s""
  2.         |CREATE TABLE users( 
  3.         |id int
  4.         |name string, 
  5.         |PRIMARY KEY (id) NOT ENFORCED 
  6.         |) 
  7.         |WITH ( 
  8.         |'connector' = 'jdbc'
  9.         |'url' = 'xxxx'
  10.         |'driver'='$DRIVER_CLASS_NAME'
  11.         |'table-name'='$tableName'
  12.         |'lookup.cache.max-rows'='100'
  13.         |'lookup.cache.ttl'='30s' 
  14.         |) 
  15.         |""".stripMargin 
  16.          
  17.          
  18. s""
  19.        |CREATE TABLE car( 
  20.        |`id`   bigint , 
  21.        |`user_id` bigint
  22.        |`proctime` as PROCTIME() 
  23.        |) 
  24.        |WITH ( 
  25.        |    'connector' = 'kafka'
  26.        |    'topic' = '$topic'
  27.        |    'scan.startup.mode' = 'latest-offset'
  28.        |    'properties.bootstrap.servers' = '$KAFKA_SERVICE'
  29.        |    'properties.group.id' = 'indicator'
  30.        |    'format' = 'canal-json' 
  31.        |) 
  32.        |""".stripMargin 
  33.         
  34.         
  35.         
  36.     SELECT 
  37.         mc.user_id user_id, 
  38.         count(1) AS `value` 
  39.     FROM car mc 
  40.         inner join users FOR SYSTEM_TIME AS OF mc.proctime as u on mc.user_id=s.id 
  41.     group by mc.user_id 

总结

总体来讲,关联维表有四个基础的方式:

(1)查找外部数据源关联

(2)预加载维表关联(内存,状态)

(3)冷热数据储备(算是1和2的结合使用)

(4)维表变更日志关联(广播也好,其他方式的流关联也好)

「同时考虑:」 吞吐量,时效性,外部数据源的负载,内存资源,解耦性等等方面。

四种join方式不存在绝对的一劳永逸,更多的是针对业务场景在各指标上的权衡取舍,因此看官需要结合场景来选择适合的。

 

责任编辑:武晓燕 来源: 大数据左右手
相关推荐

2021-07-13 10:02:52

Pandas函数Linux

2013-08-15 09:52:45

开发框架开发工具开发脚本

2015-10-27 11:02:06

Web开发CSS 库

2016-12-14 19:19:19

Linuxgcc命令行

2016-12-14 20:53:04

Linuxgcc命令行

2014-06-13 11:26:53

CSS库Web开发

2023-03-06 10:42:34

CSS前端

2013-07-12 09:45:16

PHP功能

2021-06-29 10:50:30

Python函数文件

2023-09-07 16:28:46

JavaScrip

2011-05-10 08:47:55

开发者HTML 5W3C

2013-08-23 09:28:37

GitGit 命令

2021-11-30 23:30:45

sql 性能异步

2022-06-29 09:09:38

Python代码

2022-08-23 09:01:02

HTMLWeb

2017-10-25 16:22:58

OpenStack操作Glance

2011-05-16 08:37:56

JavaScript库

2022-07-13 12:53:59

数据存储

2020-11-18 11:14:27

运维架构技术

2014-09-09 09:32:50

项目管理管理工具
点赞
收藏

51CTO技术栈公众号