为什么在Spark-shell中加载这个Spark示例代码?

时间:2016-01-24 02:52:59

标签: scala apache-spark

以下示例代码来自Advanced Analytics with Spark一书。当我将它加载到spark-shell(版本1.4.1)时,它会出现以下错误,表明它无法找到StatCounter:

import org.apache.spark.util.StatCounter
<console>:9: error: not found: type StatCounter
        val stats: StatCounter = new StatCounter()
                   ^
<console>:9: error: not found: type StatCounter
        val stats: StatCounter = new StatCounter()
                                     ^
<console>:23: error: not found: type NAStatCounter
        def apply(x: Double) = new NAStatCounter().add(x)

如果我在spark-shell中执行以下操作,则没有问题:

scala> import org.apache.spark.util.StatCounter
import org.apache.spark.util.StatCounter

scala> val statsCounter: StatCounter = new StatCounter()
statsCounter: org.apache.spark.util.StatCounter = (count: 0, mean: 0.000000, stdev: NaN, max: -Infinity, min: Infinity)

问题似乎与spark-shell中的:load命令有关。

以下是代码:

import org.apache.spark.util.StatCounter
class NAStatCounter extends Serializable {
    val stats: StatCounter = new StatCounter()
    var missing: Long = 0

    def add(x: Double): NAStatCounter = {
        if (java.lang.Double.isNaN(x)) {
            missing += 1
        } else {
        stats.merge(x)
        }
        this
    }

    def merge(other: NAStatCounter): NAStatCounter = {
        stats.merge(other.stats)
        missing += other.missing
        this
    }

    override def toString = {
        "stats: " + stats.toString + " NaN: " + missing
    }
}

object NAStatCounter extends Serializable {
    def apply(x: Double) = new NAStatCounter().add(x)
}

1 个答案:

答案 0 :(得分:3)

我和你有完全相同的问题。
我试着解决它,
改变

val stats: StatCounter = new StatCounter() 

INTO

val stats: org.apache.spark.util.StatCounter = new org.apache.spark.util.StatCounter()  

原因可能是系统不知道StatCounter的路径