Reputation: 59
What is the equivalent of the following pySpark code in Spark-Scala?
rddKeyTwoVal = sc.parallelize([("cat", (0,1)), ("spoon", (2,3))])
rddK2VReorder = rddKeyTwoVal.map(lambda (key, (val1, val2)) : ((key, val1) ,
val2))
rddK2VReorder.collect()
// [(('cat', 0), 1), (('spoon', 2), 3)] -- This is the output.
Upvotes: 2
Views: 399
Reputation: 59
I found my own answer! Posting to help rest of the community. This is cleanest Scala version of the code I posted above. Produces the exact same output.
val rddKeyTwoVal = sc.parallelize(Array(("cat", (0,1)), ("spoon", (2,3))))
val rddK2VReorder = rddKeyTwoVal.map{case (key, (val1, val2)) => ((key, val1),val2)}
rddK2VReorder.collect()
//Use the following for a cleaner output.
rddK2VReorder.collect().foreach(println)
Output:
// With collect() menthod.
Array[((String, Int), Int)] = Array(((cat,0),1), ((spoon,2),3))
// If you use the collect().foreach(println)
((cat,0),1)
((spoon,2),3)
Upvotes: 1
Reputation: 3890
val rddKeyTwoVal = sc.parallelize(Seq(("cat", (0,1)), ("spoon", (2,3))))
val rddK2VReorder = rddKeyTwoVal.map{case (key, (val1, val2)) => ((key, val1), val2)}
rddK2VReorder.collect
or
val rddKeyTwoVal = sc.parallelize(Seq(("cat", (0,1)), ("spoon", (2,3))))
val rddK2VReorder = rddKeyTwoVal.map(r=> ((r._1, r._2._1),r._2._2))
rddK2VReorder.collect
output:
Array(((cat,0),1), ((spoon,2),3))
Thanks @Alec for suggesting first approach
Upvotes: 2