Flink Scala API - 应用新的WindowFunction vs apply函数

时间:2017-11-24 17:50:48

标签: scala apache-flink

我修改了Flink的基本wordcount示例并使用窗口函数进行了播放。

WindowedStream的apply方法已重载,它接受一个函数:

&mut

以及WindowFunction:

def apply[R: TypeInformation](
    function: (K, W, Iterable[T], Collector[R]) => Unit): DataStream[R] = { ... }

在为WindowedStream上的apply方法提供函数时,我得到了我的代码编译,但我的代码不能用我的WindowFunction编译(我不知道为什么......)。

这是基本流:

def apply[R: TypeInformation](
    function: WindowFunction[T, R, K, W]): DataStream[R] = { ... }

这是我对窗口功能的实现。 这个对我有用:

val windowCounts: WindowedStream[WordWithCount, String, TimeWindow] = text
    .flatMap { w => w.split("\\s") }
    .map { w => WordWithCount(w, 1) }
    .keyBy(t => "all")
    .window(SlidingProcessingTimeWindows.of(Time.seconds(30), Time.seconds(10)))

这个没有编译:

def distinctCount(
    s: String, tw: TimeWindow, input: Iterable[WordWithCount],
    out: Collector[String]): Unit = {
  val discount = input.map(t => t.word).toSet.size
  out.collect(s"Distinct elements: $discount")
}

// compiles
val distinctCountStream = windowCounts.apply { distinctCount _ }

我使用的是Flink 1.3.2,这是我的导入:

class DiscountWindowFunction extends WindowFunction[WordWithCount, String, String, TimeWindow] {
  override def apply(key: String, window: TimeWindow, input: lang.Iterable[WordWithCount], out: Collector[String]): Unit = {
    val discount = input.map(t => t.word).toSet.size
    out.collect(s"Distinct elements: $discount")
  }
  def apply(key: String, window: TimeWindow, input: Iterable[(String, Int)], out: Collector[String]): Unit = {
    apply(key, window, input.asJava, out)
  }
}

// does not compile
val distinctCount = windowCounts.apply(new DiscountWindowFunction())  

1 个答案:

答案 0 :(得分:1)

您已导入Java DataStream API中使用的WindowFunction

替换

时,您的代码应该编译
import org.apache.flink.streaming.api.functions.windowing.WindowFunction

通过

import org.apache.flink.streaming.api.scala.function.WindowFunction

顺便说一下。感谢您提供完整的信息: - )