xstack2000
xstack2000

Reputation: 139

Spark How to RDD[JSONObject] to Dataset

I am reading data from RDD of Element of type com.google.gson.JsonObject. Trying to convert that into DataSet but no clue how to do this.

import com.google.gson.{JsonParser}
import org.apache.hadoop.io.LongWritable
import org.apache.spark.sql.{SparkSession}

object tmp {
  class people(name: String, age: Long, phone: String)
  def main(args: Array[String]): Unit = {
    val spark = SparkSession.builder().master("local[*]").getOrCreate()
    val sc = spark.sparkContext

    val parser = new JsonParser();
    val jsonObject1 = parser.parse("""{"name":"abc","age":23,"phone":"0208"}""").getAsJsonObject()
    val jsonObject2 = parser.parse("""{"name":"xyz","age":33}""").getAsJsonObject()

    val PairRDD = sc.parallelize(List(
      (new LongWritable(1l), jsonObject1),
      (new LongWritable(2l), jsonObject2)
    ))

    val rdd1 =PairRDD.map(element => element._2)

    import spark.implicits._

    //How to create Dataset as schema People from rdd1?
  }
}

Even trying to print rdd1 elements throws

object not serializable (class: org.apache.hadoop.io.LongWritable, value: 1)
- field (class: scala.Tuple2, name: _1, type: class java.lang.Object)
- object (class scala.Tuple2, (1,{"name":"abc","age":23,"phone":"0208"}))

Basically I get this RDD[LongWritable,JsonParser] from BigQuery table which I want to convert to Dataset so I can apply SQL for transformation.

I've left phone in the second record null intentionally, BigQuery return nothing for that element with null value.

Upvotes: 1

Views: 1801

Answers (1)

Shoaib Burq
Shoaib Burq

Reputation: 384

Thanks for the clarification. You need to register the class as Serializable in kryo. The following show work. I am running in spark-shell so had to destroy the old context and create a new spark context with a config that included the registered Kryo Classes

import com.google.gson.{JsonParser}
import org.apache.hadoop.io.LongWritable
import org.apache.spark.SparkContext

sc.stop()

val conf = sc.getConf
conf.registerKryoClasses( Array(classOf[LongWritable], classOf[JsonParser] ))
conf.get("spark.kryo.classesToRegister")

val sc = new SparkContext(conf)

val parser = new JsonParser();
val jsonObject1 = parser.parse("""{"name":"abc","age":23,"phone":"0208"}""").getAsJsonObject()
val jsonObject2 = parser.parse("""{"name":"xyz","age":33}""").getAsJsonObject()

val pairRDD = sc.parallelize(List(
  (new LongWritable(1l), jsonObject1),
  (new LongWritable(2l), jsonObject2)
))


val rdd = pairRDD.map(element => element._2)

rdd.collect()
// res9: Array[com.google.gson.JsonObject] = Array({"name":"abc","age":23,"phone":"0208"}, {"name":"xyz","age":33})

val jsonstrs = rdd.map(e=>e.toString).collect()
val df = spark.read.json( sc.parallelize(jsonstrs) )    
df.printSchema
// root
//  |-- age: long (nullable = true)
//  |-- name: string (nullable = true)
//  |-- phone: string (nullable = true)

Upvotes: 1

Related Questions