关于RDD的打印输出(来自官网)

Printing elements of an RDD

Another common idiom is attempting to print out the elements of an RDD using rdd.foreach(println) or rdd.map(println). On a single machine, this will generate the expected output and print all the RDD’s elements. However, in cluster mode, the output to stdout being called by the executors is now writing to the executor’s stdout instead, not the one on the driver, so stdout on the driver won’t show these! To print all elements on the driver, one can use the collect() method to first bring the RDD to the driver node thus: rdd.collect().foreach(println). This can cause the driver to run out of memory, though, because collect() fetches the entire RDD to a single machine; if you only need to print a few elements of the RDD, a safer approach is to use the take(): rdd.take(100).foreach(println).

关于RDD的输出,官网上是以上叙述:
意思就是:利用rdd.foreach(println) 或者 rdd.map(println),在一台机器上时,会得到理想的输出,打印出所有的RDD的数值;但在集群环境中,输出会被executors唤起,被写到executors的输出,而不是驱动所在的主机,所以在主机上不会显示打印信息,为了能够在主机上打印信息,要使用collect()函数首先把RDD放到主机节点上,rdd.collect().foreach(println),但因为collect()会将整个RDD的数据放到主机上,会使得驱动主机内存溢出。如果你只想打印出有限个RDD数据,一个靠谱的方法就是用take():rdd.take(100).foreach(println)

### Spark RDD 连接操作 示例代码与编程实验 在 Spark RDD 编程中,连接操作通常用于将两个或多个数据集基于键进合并。以下是一个详细的示例代码和解释,展示如何使用 `join` 操作对两个 RDD连接。 #### 示例代码 ```scala import org.apache.spark.SparkContext import org.apache.spark.SparkConf object RDDJoinExample { def main(args: Array[String]) { val conf = new SparkConf().setAppName("RDDJoinExample").setMaster("local[*]") val sc = new SparkContext(conf) // 创建第一个 RDD (Key-Value 对) val rdd1 = sc.parallelize(Seq( ("apple", 1), ("banana", 2), ("orange", 3) )) // 创建第二个 RDD (Key-Value 对) val rdd2 = sc.parallelize(Seq( ("apple", "fruit"), ("banana", "yellow"), ("grape", "small") )) // 使用 join 操作将两个 RDD 基于相同的 key 连接 val joinedRDD = rdd1.join(rdd2) // 打印结果 println("Joined RDD:") joinedRDD.collect.foreach(println) sc.stop() } } ``` #### 解释 上述代码展示了如何通过 `join` 操作将两个 RDD 连接起来。以下是关键点的详细说明: - **创建 RDD**:通过 `parallelize` 方法创建两个包含键值对的 RDD[^4]。 - **连接操作**:`rdd1.join(rdd2)` 将两个 RDD 中具有相同键的元素连接在一起,生成一个新的 RDD,其中每个元素包含来自两个原始 RDD 的值[^2]。 - **惰性计算**:`join` 是一个转换操作,只有在调用动操作(如 `collect`)时才会触发实际计算[^1]。 #### 输出结果 运上述代码后,输出如下: ``` Joined RDD: (apple,(1,fruit)) (banana,(2,yellow)) ``` #### 注意事项 - 如果某个键只存在于其中一个 RDD 中,则不会出现在结果中。例如,`"grape"` 只存在于 `rdd2` 中,因此未出现在最终结果中[^5]。 - 如果需要保留所有键,可以考虑使用 `leftOuterJoin`、`rightOuterJoin` 或 `fullOuterJoin` 等外连接操作[^3]。 --- ####
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值