打印RDD中的内容到logs中【一篇就够】

本文介绍了如何在单机和集群环境下正确打印RDD元素的方法。在单机模式下,直接使用rdd.foreach(println)即可打印所有元素;而在集群模式下,则需采用rdd.collect().foreach(println)或rdd.take(n).foreach(println)来确保输出能在驱动程序中可见,避免因collect()导致内存溢出的风险。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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)

例:下面这样可以正常打印出rdd信息到一台机器上

rdd.collect().foreach(row => {
    println("row.length===:" + row.length)
    for ( i <- 0 to (row.length -1))
        println("===<" + i + ">===:" + row.get(i))
})

下面这样会存在看不到的情况

rdd.foreach(row => {
    println("row.length===:" + row.length)
    for ( i <- 0 to (row.length -1))
        println("===<" + i + ">===:" + row.get(i))
})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

sjmz30071360

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值