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)
.
below refer to :http://blog.csdn.net/duck_genuine/article/details/41550019
- val totalVids=sc.accumulator(0)
- val timesFile=sc.textFile("/user/zhenyuan.yu/DumpIdTimesJob_tmp_out")
- val keysList=List(100, 500, 1000, 2000, 5000, 10000, 20000, 40000, 80000, 100000, 200000, 300000, 500000, 1000000, 2000000, 5000000, 10000000)
- val timesRDD=timesFile.map(f=>{
- val vid_times=f.split("\t")
- var times=vid_times(1).toInt
- times
- }).filter(_>50).map(times=>{
- totalVids+=1
- var key=0
- var end=false
- var i=0
- var size=keysList.size
- while(i<size && !end){
- key=keysList(i)
- if(times<key){
- end=true
- }
- i+=1
- }
- (key,1)
- }).reduceByKey(_+_)
- val rdd=timesRDD.collect()
- println("totalVid:"+totalVids)
- for(i<-0 to rdd.size-1){
- val times_times=rdd(i)
- val percent=times_times._2.toFloat/totalVids.value
- println("times:<"+times_times._1+",vid_num:"+times_times._2+",percent:"+percent)
- }