Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Spark DataFrame to Pojo Object

Please see below code:

    //Create Spark Context
    SparkConf sparkConf = new SparkConf().setAppName("TestWithObjects").setMaster("local");
    JavaSparkContext javaSparkContext = new JavaSparkContext(sparkConf);
    //Creating RDD
    JavaRDD<Person> personsRDD = javaSparkContext.parallelize(persons);
    //Creating SQL context
    SQLContext sQLContext = new SQLContext(javaSparkContext);
    DataFrame personDataFrame = sQLContext.createDataFrame(personsRDD, Person.class);
    personDataFrame.show();
    personDataFrame.printSchema();
    personDataFrame.select("name").show();
    personDataFrame.registerTempTable("peoples");
    DataFrame result = sQLContext.sql("SELECT * FROM peoples WHERE name='test'");
    result.show();

After this I need to convert the DataFrame - 'result' to Person Object or List. Thanks in advance.

like image 972
Don Mathew Avatar asked Dec 10 '15 05:12

Don Mathew


2 Answers

DataFrame is simply a type alias of Dataset[Row] . These operations are also referred as “untyped transformations” in contrast to “typed transformations” that come with strongly typed Scala/Java Datasets.

The conversion from Dataset[Row] to Dataset[Person] is very simple in spark

DataFrame result = sQLContext.sql("SELECT * FROM peoples WHERE name='test'");

At this point, Spark converts your data into DataFrame = Dataset[Row], a collection of generic Row object, since it does not know the exact type.

// Create an Encoders for Java beans
Encoder<Person> personEncoder = Encoders.bean(Person.class); 
Dataset<Person> personDF = result.as(personEncoder);
personDF.show();

Now, Spark converts the Dataset[Row] -> Dataset[Person] type-specific Scala / Java JVM object, as dictated by the class Person.

Please refer to below link provided by databricks for further details

https://databricks.com/blog/2016/07/14/a-tale-of-three-apache-spark-apis-rdds-dataframes-and-datasets.html

like image 170
Rahul Avatar answered Oct 15 '22 11:10

Rahul


A DataFrame is stored as Rows, so you can use the methods there to cast from untyped to typed. Take a look at the get methods.

like image 28
Justin Pihony Avatar answered Oct 15 '22 10:10

Justin Pihony