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

b4wnujal  于 2021-06-25  发布在  Flink
关注(0)|答案(1)|浏览(337)

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

nmpmafwu

nmpmafwu1#

你可以通过存储你已经看到的所有单词来解决这个问题。有了这些知识,你就可以过滤掉所有重复的单词。剩下的可以由一个具有并行性的map操作符来计算 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()

相关问题