Saving MongoDB data to parquet file format using Apache Spark

I am new to Apache spark as well as Scala programming language.

I am trying to fetch data from my local mongoDB database to save it in parquet format using Apache Spark with hadoop connector

This is my code:

package com.examples 
import org.apache.spark.{SparkContext, SparkConf} 
import org.apache.spark.rdd.RDD 
import org.apache.hadoop.conf.Configuration 
import org.bson.BSONObject 
import com.mongodb.hadoop.{MongoInputFormat, BSONFileInputFormat} 
import org.apache.spark.sql 
import org.apache.spark.sql.SQLContext 

object DataMigrator { 

    def main(args: Array[String])
    { 
        val conf = new SparkConf().setAppName("Migration    App").setMaster("local") 
        val sc = new SparkContext(conf) 
        val sqlContext = new SQLContext(sc) 

        // Import statement to implicitly convert an RDD to a DataFrame 
        import sqlContext.implicits._ 

        val mongoConfig = new Configuration() 
        mongoConfig.set("mongo.input.uri",   "mongodb://localhost:27017/mongosails4.case") 

        val mongoRDD = sc.newAPIHadoopRDD(mongoConfig, classOf[MongoInputFormat], classOf[Object], classOf[BSONObject]);     

        val count = countsRDD.count()

        // the count value is aprox 100,000 
        println("================ PRINTING =====================") 
        println(s"ROW COUNT IS $count") 
        println("================ PRINTING =====================") 
    } 
} 

      

The point is that in order to save the data to the parquet file format, you first need to convert the mongoRDD variable to a Spark DataFrame. I've tried something like this:

// convert RDD to DataFrame
val myDf = mongoRDD.toDF()  // this lines throws an error
myDF.write.save("my/path/myData.parquet")

      

and the error I am getting is this: Exception in thread "main" scala.MatchError: java.lang.Object (of class scala.reflect.internal.Types.$TypeRef$$anon$6)

Do you guys have another idea how can I convert the RDD to a DataFrame so that I can save the data in parquet format?

Here's the structure of one document in the mongoDB collection: https://gist.github.com/kingtrocko/83a94238304c2d654fe4

+3


source to share


1 answer


Create a Case class to represent the data stored in your DBObject.
case class Data(x: Int, s: String)

Then map the values โ€‹โ€‹of your rdd to instances of your case class. val dataRDD = mongoRDD.values.map { obj => Data(obj.get("x"), obj.get("s")) }

Now with your RDD [Data] you can create a DataFrame using sqlContext



val myDF = sqlContext.createDataFrame(dataRDD)

This should get you going. I can explain in more detail if necessary.

+1


source







All Articles