Rasika
Rasika

Reputation: 507

Flatten RDD[(String,Map[String,Int])] to RDD[String,String,Int]

I am trying to flatten an RDD[(String,Map[String,Int])] to RDD[String,String,Int] and ultimately save it as a dataframe.

    val rdd=hashedContent.map(f=>(f._1,f._2.flatMap(x=> (x._1, x._2))))
    val rdd=hashedContent.map(f=>(f._1,f._2.flatMap(x=>x)))

All having type mismatch errors. Any help on how to flatten structures like this one? EDIT:

    hashedContent -- ("A", Map("acs"->2, "sdv"->2, "sfd"->1)),
                     ("B", Map("ass"->2, "fvv"->2, "ffd"->1)),
                      ("c", Map("dg"->2, "vd"->2, "dgr"->1))

Upvotes: 1

Views: 511

Answers (2)

Tzach Zohar
Tzach Zohar

Reputation: 37852

For completeness: an alternative solution (which might be considered more readable) would be to first convert the RDD into a DataFrame, and then to transform its structure using explode:

import org.apache.spark.sql.functions._
import spark.implicits._

rdd.toDF("c1", "map")
  .select($"c1", explode($"map"))
  .show(false)

// same result:
// +---+---+-----+
// |c1 |key|value|
// +---+---+-----+
// |A  |acs|2    |
// |A  |sdv|2    |
// |A  |sfd|1    |
// |B  |ass|2    |
// |B  |fvv|2    |
// |B  |ffd|1    |
// |c  |dg |2    |
// |c  |vd |2    |
// |c  |dgr|1    |
// +---+---+-----+

Upvotes: 2

mtoto
mtoto

Reputation: 24198

You were close:

rdd.flatMap(x => x._2.map(y => (x._1, y._1, y._2)))
   .toDF()
   .show()
+---+---+---+
| _1| _2| _3|
+---+---+---+
|  A|acs|  2|
|  A|sdv|  2|
|  A|sfd|  1|
|  B|ass|  2|
|  B|fvv|  2|
|  B|ffd|  1|
|  c| dg|  2|
|  c| vd|  2|
|  c|dgr|  1|
+---+---+---+

Data

val data = Seq(("A", Map("acs"->2, "sdv"->2, "sfd"->1)),
               ("B", Map("ass"->2, "fvv"->2, "ffd"->1)),
               ("c", Map("dg"->2, "vd"->2, "dgr"->1)))

val rdd = sc.parallelize(data)

Upvotes: 4

Related Questions