1

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))
2
  • please provide the test data and the value for hashedcontent Commented Aug 29, 2018 at 17:09
  • @Chandan Added. Commented Aug 29, 2018 at 17:15

2 Answers 2

4

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)
Sign up to request clarification or add additional context in comments.

2 Comments

I am getting error at .toDF() Cannot resolve symbol.
try running import sqlContext.implicits._ first, what Spark version you are on?
2

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    |
// +---+---+-----+

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.