我正在尝试使用 apache Spark/scala 查找单词数最多的行。我正在 Spark-Shell 中运行该程序。
当我使用以下代码时,我得到正确的输出:
scala> file1.map(line => line.split(" ").size).reduce((a, b) => if (a > b) a else b)
但是当我尝试使用以下代码收集结果时出现错误:
scala> file1.map(line => line.split(" ").size).reduce((a, b) => if (a > b) a else b).collect()
<console>:30: error: value collect is not a member of Int
file1.map(line => line.split(" ").size).reduce((a, b) => if (a > b) a else b).collect()
为什么在使用 collect()
操作时出现错误?
最佳答案
reduce是将一系列 T
类型的值减少为 T
类型的单个值的操作。
reduce(f: (T, T) ⇒ T): T Reduces the elements of this RDD using the specified commutative and associative binary operator.
在reduce
之后,您将得到最终结果(您也可以为其他转换进行collect
)。
根据您的情况,分配reduce
的值并检查其类型。它是Int
。
val result = file1.
map(line => line.split(" ").size).
reduce((a, b) => if (a > b) a else b)
// check the type of the value from `reduce`
scala> :type result
Int
reduce
与 collect
非常相似,因为两者都是给你一个值的操作,但collect会给你一个Array[T]
...
collect(): Array[T] Return an array that contains all of the elements in this RDD.
...而减少
只是一个值T
。
关于scala - 为什么在reduce结果上collect失败并显示 "error: value collect is not a member of Int"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44420128/