为什么我的简单火花代码不能打印任何东西?
why my simple spark code can not print anything?
def main(args: Array[String]): Unit = {
val sparkConf = new SparkConf().setMaster("local[*]").setAppName("Operator")
val sc = new SparkContext(sparkConf)
val rdd1: RDD[Int] = sc.makeRDD(List(2, 4, 6, 8), 2)
// just print datas partition info then reture partition datas with no changes
val rdd2: RDD[Int] = rdd1.mapPartitionsWithIndex((par, datas) => {
println("data and partition info : par = " + par + " datas = " + datas.mkString(" "))
datas // return datas again
})
// i think there are 2,4,6,8 four elements in rdd2
// so i foreach rdd2 but nothing output, why this happen?
rdd2.collect().foreach(println)
sc.stop()
}
我正在研究spark,我用spark写了一个简单的演示代码。但有一些问题我不明白。
我不明白为什么代码 rdd2.collect().foreach(println)
不能打印任何东西?
你的问题是你在 mapPartition 函数中返回一个迭代器,当你使用 mkString 函数时,它已经被遍历过。迭代器是特殊的集合,有助于处理一个一个地读取元素的大分区。它们被用在 RDD api 的不同函数中,例如 forEach、mapPartition、zipPartition 等....看看它们如何 work。并注意以下语句:“在调用迭代器上的方法后永远不要使用迭代器。”。删除 println 行,它应该可以工作。
def main(args: Array[String]): Unit = {
val sparkConf = new SparkConf().setMaster("local[*]").setAppName("Operator")
val sc = new SparkContext(sparkConf)
val rdd1: RDD[Int] = sc.makeRDD(List(2, 4, 6, 8), 2)
// just print datas partition info then reture partition datas with no changes
val rdd2: RDD[Int] = rdd1.mapPartitionsWithIndex((par, datas) => {
println("data and partition info : par = " + par + " datas = " + datas.mkString(" "))
datas // return datas again
})
// i think there are 2,4,6,8 four elements in rdd2
// so i foreach rdd2 but nothing output, why this happen?
rdd2.collect().foreach(println)
sc.stop()
}
我正在研究spark,我用spark写了一个简单的演示代码。但有一些问题我不明白。
我不明白为什么代码 rdd2.collect().foreach(println)
不能打印任何东西?
你的问题是你在 mapPartition 函数中返回一个迭代器,当你使用 mkString 函数时,它已经被遍历过。迭代器是特殊的集合,有助于处理一个一个地读取元素的大分区。它们被用在 RDD api 的不同函数中,例如 forEach、mapPartition、zipPartition 等....看看它们如何 work。并注意以下语句:“在调用迭代器上的方法后永远不要使用迭代器。”。删除 println 行,它应该可以工作。