【发布时间】:2018-05-06 23:25:01
【问题描述】:
Spark 结构化流,尝试使用 mapgroupwithstate。有没有人遇到过 .format("console") 完美工作并完美打印增量状态更改的情况,但是每当我尝试更改 .format("anyStreamingSinkClass") 时,接收器类收到的数据帧只有当前批次但没有内存状态或增量效应。
case class WordCount(word:String,count:Int)
case class WordInfo(totalSum:Int)
case class WordUpdate(word:String,count:Int,expired:Boolean)
val ds = df.as[String].map{ x=>
val arr = x.split(",",-1)
WordCount( arr(0), arr(1).toInt )
}.groupByKey(_.word)
.mapGroupsWithState[WordInfo,WordUpdate](GroupStateTimeout.NoTimeout()) {
case( word:String, allWords:Iterator[WordCount], state:GroupState[WordInfo]) =>
val events = allWords.toSeq
val updatedSession = if (state.exists) {
val existingState = state.get
val updatedEvents = WordInfo(existingState.totalSum + events.map(event ⇒ event.count).sum)
updatedEvents
}
else {
WordInfo(events.map(event => event.count).sum)
}
state.update(updatedSession)
WordUpdate(word,updatedSession.totalSum,false)
}
val query = ds
.writeStream
//.format("console")
.format("com.subhankar.streamDB.ConsoleSinkProvider")
.outputMode(OutputMode.Update())
.trigger(Trigger.ProcessingTime(3.seconds))
//.option("truncate",false)
.option("checkpointLocation","out.b")
.queryName("q2090" )
.start()
query.awaitTermination()
对于接收器格式,我得到 批次 21 的不同计数为 1 x,1 Batch 22 的不同计数为 1 x,2 批次 23 的不同计数为 1 x,3
对于我得到的控制台格式
-------------------------------------------
Batch: 1
-------------------------------------------
+----+-----+-------+
|word|count|expired|
+----+-----+-------+
| x| 1| false|
+----+-----+-------+
-------------------------------------------
Batch: 2
-------------------------------------------
+----+-----+-------+
|word|count|expired|
+----+-----+-------+
| x| 3| false|
+----+-----+-------+
-------------------------------------------
Batch: 3
-------------------------------------------
+----+-----+-------+
|word|count|expired|
+----+-----+-------+
| x| 6| false|
+----+-----+-------+
水槽做一个简单的打印...
override def addBatch(batchId: Long, data: DataFrame) = {
val batchDistinctCount = data.rdd.distinct.count()
if(data.count()>0) {
println(s"Batch ${batchId}'s distinct count is ${batchDistinctCount}")
println(data.map(x=> x.getString(0) + "," + x.getInt(1)).collect().mkString(","))
}
}
【问题讨论】:
标签: apache-spark spark-structured-streaming