如果您刚开始使用 Spark,并且没有人告诉您使用它,请不要使用 RDD API。在 Spark 中,有很多更好且通常更高效的 Spark SQL API 可以执行此操作以及在大型数据集上执行许多其他分布式计算。
使用 RDD API 就像将汇编程序用于可以使用 Scala(或其他高级编程语言)的东西。在开始你的 Spark 之旅时,我个人建议首先使用 DataFrames 和 Datasets 的更高级别的 Spark SQL API,这肯定是太多了。
给定输入:
$ cat input.txt
Let's have some fun.
To have fun you don't need any plans.
如果您要使用 Dataset API,您可以执行以下操作:
val lines = spark.read.text("input.txt").withColumnRenamed("value", "line")
val wordsPerLine = lines.withColumn("words", explode(split($"line", "\\s+")))
scala> wordsPerLine.show(false)
+-------------------------------------+------+
|line |words |
+-------------------------------------+------+
|Let's have some fun. |Let's |
|Let's have some fun. |have |
|Let's have some fun. |some |
|Let's have some fun. |fun. |
| | |
|To have fun you don't need any plans.|To |
|To have fun you don't need any plans.|have |
|To have fun you don't need any plans.|fun |
|To have fun you don't need any plans.|you |
|To have fun you don't need any plans.|don't |
|To have fun you don't need any plans.|need |
|To have fun you don't need any plans.|any |
|To have fun you don't need any plans.|plans.|
+-------------------------------------+------+
scala> wordsPerLine.
groupBy("line", "words").
count.
withColumn("word_count", struct($"words", $"count")).
select("line", "word_count").
groupBy("line").
agg(collect_set("word_count")).
show(truncate = false)
+-------------------------------------+------------------------------------------------------------------------------+
|line |collect_set(word_count) |
+-------------------------------------+------------------------------------------------------------------------------+
|To have fun you don't need any plans.|[[fun,1], [you,1], [don't,1], [have,1], [plans.,1], [any,1], [need,1], [To,1]]|
|Let's have some fun. |[[have,1], [fun.,1], [Let's,1], [some,1]] |
| |[[,1]] |
+-------------------------------------+------------------------------------------------------------------------------+
完成。 很简单,不是吗?
参见functions 对象(对于explode 和struct 函数)。