Flink 專題 -3窗口滾動和滑動操作

Flink流操作-窗口滾動和滑動操作

Flink存在兩種窗口操作,分別爲滾動操作和滑動操作,兩者主要的區別在於,滾動操作不會重疊,而滑動操作則會讓數據產生重疊 。

https://github.com/soniclavier/bigdata-notebook/tree/master/flink/src/main/scala/com/vishnu/flink/streaming

窗口需求

在Streaming應用程序的情況下,數據是連續的,因此我們不能等待在開始處理之前流式傳輸整個數據。當然,我們可以處理每個傳入的事件,然後轉移到下一個事件,但在某些情況下,我們需要對傳入的數據進行某種聚合 - 例如,有多少用戶在過去10分鐘內點擊了您網頁上的鏈接。在這種情況下,我們必須定義一個窗口並對窗口內的數據進行處理

滾動窗口Tumbling window

滾動窗口滾動數據流。這種類型的窗口是不重疊的 - 即,一個窗口中的事件/數據不會在其他窗口中重疊/出現。

img

你可以配置滾動窗口基於數量,例如基於每5條數據,或者基於時間,例如基於每十秒鐘。

滑動窗口 Sliding Window

滑動窗口與翻滾窗口相對,滑過數據流。因此,滑動窗口可以重疊,它可以對輸入的數據流進行更平滑的聚合 - 因爲您不是從一組輸入跳轉到下一組輸入,而是滑過輸入的數據流。

img

與滾動窗口類似,您也可以根據時間或事件計數配置滑動窗口。

代碼示例

下面的示例顯示了一個字數統計程序,它監聽套接字並計算窗口內每個字接收的次數。這裏的窗口基於計數,每5件物品就會翻滾。

Scala Code - Tumbling Window

Below example shows a word count program that listens to a socket and counts the number of times each word is received within a window. The window here is based on count and it tumbles for every 5 items.

object CountTumblingWindow {
  def main(args: Array[String]) {
    val sev = StreamExecutionEnvironment.getExecutionEnvironment  
    val socTextStream = sev.socketTextStream("localhost",4444)  //read from socket
    val counts = socTextStream.flatMap{_.split("\\s")}  //split sentence into words
      .map { (_, 1) }  //emit 1 for each word	
      .keyBy(0)	 //group based on word
      .countWindow(5)  //window for every 5 items in the group
      .sum(1)						
      .setParallelism(4);  //setting parallelism (optional)
    counts.print()
    sev.execute()
  }
} 

在上面的示例中,每5條數據觸發一次窗口。由於我們正在執行keyby,因此每個窗口將只包含同一組的單詞。

e.g.,
    if stream is : one two one two one two one two one
    window1 = {one,one,one,one,one}
    window2 = {two,two,two,two}
    window1 will triggered but not window 2, it need one more 'two' to reach count 5.

Scala Code - Sliding Window

In the below example, the window slides every 10 seconds and the width of the window is 15 seconds of data. Therefore, there is an overlap between the windows.

object TimeSlidingWindow {
  def main(args: Array[String]) {
    val sev = StreamExecutionEnvironment.getExecutionEnvironment
    val socTextStream = sev.socketTextStream("localhost",4444)
    val counts = socTextStream.flatMap{_.split("\\s")}
      .map { (_, 1) }
      .keyBy(0)
      .timeWindow(Time.seconds(15),Time.seconds(10))
      .sum(1).setParallelism(4);

    counts.print()
    sev.execute()
  }
}

這涵蓋了Flink中Windows類型的基礎知識。我們可以在Flink中執行各種複雜的窗口操作 - 例如,我們可以選擇基於時間滑動窗口,但是根據項目計數觸發執行,並且還選擇在當前窗口中保留少量項目用於下一個窗口處理。我將嘗試在即將發佈的博客中介紹這些高級主題。

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章