DStream Window Operations

Window Operations

Spark Streaming also provides windowed computations, which allow you to apply transformations over a sliding window of data. The following figure illustrates this sliding window
The window slides over a source DStream, the source RDDs that fall within the window are combined and operated upon to produce the RDDs of the windowed DStream. In this specific case, the operation is applied over the last 3 time units of data, and slides by 2 time units. This shows that any window operation needs to specify two parameters.
window length - The duration of the window.
sliding interval - The interval at which the window operation is performed.
Example:
1
// Reduce last 30 seconds of data, every 10 seconds
2
//val windowedWordCounts = pairs
3
// .reduceByKeyAndWindow((a:Int,b:Int) => (a + b), Seconds(30), Seconds(10))
4
​
5
package com.jentekco.spark
6
import org.apache.spark._
7
import org.apache.spark.streaming._
8
//import org.apache.spark.streaming
9
.StreamingContext._
10
import org.apache.log4j._
11
object WordCount {
12
def main(args: Array[String]): Unit = {
13
Logger.getLogger("org").setLevel(Level.ERROR)
14
​
15
val sparkConf = new SparkConf()
16
.setMaster("local[2]").setAppName("HdfsWordCount")
17
// Create the context
18
val ssc = new StreamingContext(sparkConf, Seconds(2))
19
​
20
val lines = ssc.textFileStream
21
("hdfs://10.0.0.46:9000/tmp/spark/")
22
val words = lines.flatMap(_.split(" "))
23
val wordCounts = words.map(x => (x, 1))
24
.reduceByKeyAndWindow((a:Int,b:Int) =>
25
(a + b), Seconds(30), Seconds(10))
26
wordCounts.print(100)
27
ssc.start()
28
ssc.awaitTermination()
29
} }
Copied!
​
Last modified 1yr ago
Copy link