Spark SQL Dataframe
A dataframe similar to RDD is an abstraction provided for structured data in the Spark SQL library. It is a distributed collection of data which can be considered a table in a relational database with a schema attached. It can also be defined as the collection of named columns. Spark SQL is one of the libraries available in the Spark stack which contains information about the structure and the computation that is being performed on the data. This additional information is used to perform optimizations. A dataframe incorporates the benefits of RDD along with optimization techniques and this API is available in Python, R, Scala, and Java.
The different sources which generate a dataframe are-
- Existing RDD
- Structured data files and databases
- Hive Tables
Need of Dataframe
The spark community has always tried to bring structure to the data, where spark SQL- dataframes are the steps taken in that direction. The initial API of spark, RDD is for unstructured data where the computations and data are both opaque. Thus there was a requirement to create an API that is able to provide additional benefits of optimization. Below are the few requirements which formed the basis of dataframe-
- Process structured and semi- data
- Multiple data sources
- Integration with multiple programming languages
- The number of operations that can be performed on the data such as select & filter.
How to create Spark SQL Dataframe?
Before understanding ways of creating a dataframe it is important to understand another concept by which spark applications create dataframe from different sources. This concept is known as sparksession and is the entry point for all the spark functionality. Earlier we had to create sparkConf, sparkContext or sqlContext individually but with sparksession, all are encapsulated under one session where spark acts as a sparksession object.
val spark = SparkSession
Ways of creating a dataframe
From Existing RDD
There are two ways in which a Dataframe can be created through RDD. One way is using reflection which automatically infers the schema of the data and the other approach is to create a schema programmatically and then apply to the RDD.
- By Inferring the Schema
An easy way of converting an RDD to Dataframe is when it contains case classes due to the Spark’s SQL interface. The arguments passed to the case classes are fetched using reflection and it becomes the name of the columns of the table. Sequences and Arrays can also be defined in case classes. The RDD which will be created using the case class can be implicitly converted to Dataframe using the toDF() method.
val sqlContext = new org.apache.spark.sql.SQLContext(sc)
case class Transport(AutoName: String, year: Int)
val Vehicle = sc.textFile("//path//").map(_.split(",")).map(p => Transport(p(0), p(1)).toDF()
A dataframe Vehicle is created and can be registered as a table against which sql statements can be executed.
- By programmatically specifying the Schema
There may be cases where we are not aware of the schema beforehand or scenarios where case classes cannot take more than 22 fields. In such conditions, we use the approach of programmatically creating the schema. Firstly an RDD of rows is created from the original RDD, i.e converting the rdd object from rdd[t] to rdd[row]. Then create a schema using StructType (Table) and StructField (Field) objects. This schema is applied to the RDD of Rows using the createDataFrame method as which resembles the structure of rdd[row] created earlier.
val Vehicle = sc.textFile("//path")
val schema = StructType(Array(StructField("AutoName",StringType,true),StructField("Year",IntegerType,true)))
scala> val rowRDD = vehicle.map(_.split(",")).map(p => org.apache.spark.sql.Row(p(0),p(1).toInt))
val vehicleSchemaRDD = sqlContext.applySchema(rowRDD, schema)
Through Data Sources
Spark allows the creation of dataframes through multiple sources such as hive, json, parquet, csv and text files that can also be used to create dataframes.
Val file=sqlContext.read.json(“path to the json file”)
Val file=sqlContext.read.csv(“path to the json file”)
Val file=sqlContext.read.text(“path to the json file”)
val hiveData = new org.apache.spark.sql.hive.HiveContext(sc)
val hiveDF = hiveData.sql(“select * from tablename”)
As the data is stored in a tabular format along with the schema, there are a number of operations that can be performed on the dataframes. It allows multiple operations that can be performed on data in dataframes.
Consider file is a dataframe which has been created from a csv file with two columns – FullName and AgePerPA
- printSchema()- To view the schema structure
// |-- AgePerPA: long (nullable = true)
// |-- FullName: string (nullable = true)
- select- Similar to select statement in SQL, showcases the data as mentioned in the select statement.
// | name|
// | Bala|
- Filter- To view the filtered data from the dataframe. The condition mentioned in the command
file.filter($"AgePerPA" > 18).show()
- GroupBy- To groupby the values
- show()- to display the contents of dataframe
Though with dataframes you can catch sql syntax error at compile time itself, it is not capable of handling any analysis related error untill runtime. For example, if a non-existing column name is being refered in the code it won’t be noticed untill runtime. This would lead to wasting the developer’s time and project cost.
Conclusion – Spark SQL Dataframe
This article gives an overall picture(need, creation, limitations) about the dataframe API of Spark SQL. Due to the popularity of dataframe APIs Spark SQL remains one of the widely used libraries. Just like an RDD, it provides features like fault tolerance, lazy evaluation, in-memory processing along with some additional benefits. It can be defined as data distributed across the cluster in a tabular form. Thus a dataframe will have a schema associated with it and can be created through multiple sources via spark session object.
This is a guide to Spark SQL Dataframe. Here we discuss the ways of creating a dataframe with the DataFrame Operations and Limitations. You may also look at the following article to learn more –