如何计算流中的唯一字词?

时间:2016-03-31 18:04:26

标签: apache-flink flink-streaming

有没有办法用Flink Streaming计算流中唯一字的数量?结果将是一个不断增加的数字流。

1 个答案:

答案 0 :(得分:8)

您可以通过存储您已经看过的所有单词来解决问题。拥有这些知识,您可以过滤掉所有重复的单词。其余的可以由具有并行性1的地图运算符计算。以下代码片段就是这样做的。

val env = StreamExecutionEnvironment.getExecutionEnvironment

val inputStream = env.fromElements("foo", "bar", "foobar", "bar", "barfoo", "foobar", "foo", "fo")

// filter words out which we have already seen
val uniqueWords = inputStream.keyBy(x => x).filterWithState{
  (word, seenWordsState: Option[Set[String]]) => seenWordsState match {
    case None => (true, Some(HashSet(word)))
    case Some(seenWords) => (!seenWords.contains(word), Some(seenWords + word))
  }
}

// count the number of incoming (first seen) words
val numberUniqueWords = uniqueWords.keyBy(x => 0).mapWithState{
  (word, counterState: Option[Int]) =>
    counterState match {
      case None => (1, Some(1))
      case Some(counter) => (counter + 1, Some(counter + 1))
    }
}.setParallelism(1)

numberUniqueWords.print();

env.execute()