Spark SQL is a Spark module for structured data processing. Unlike the basic Spark RDD API, the interfaces provided
by Spark SQL provide Spark with more information about the structure of both the data and the computation being performed. Internally,
Spark SQL uses this extra information to perform extra optimizations. There are several ways to
interact with Spark SQL including SQL and the Dataset API. When computing a result
the same execution engine is used, independent of which API/language you are using to express the
computation. This unification means that developers can easily switch back and forth between
different APIs based on which provides the most natural way to express a given transformation.
All of the examples on this page use sample data included in the Spark distribution and can be run in
the
spark-shell
,
pyspark
shell, or
sparkR
shell.
One use of Spark SQL is to execute SQL queries.
Spark SQL can also be used to read data from an existing Hive installation. For more on how to
configure this feature, please refer to the
Hive Tables
section. When running
SQL from within another programming language the results will be returned as a
Dataset/DataFrame
.
You can also interact with the SQL interface using the
command-line
or over
JDBC/ODBC
.
Datasets and DataFrames
A Dataset is a distributed collection of data.
Dataset is a new interface added in Spark 1.6 that provides the benefits of RDDs (strong
typing, ability to use powerful lambda functions) with the benefits of Spark SQL’s optimized
execution engine. A Dataset can be
constructed
from JVM objects and then
manipulated using functional transformations (
map
,
flatMap
,
filter
, etc.).
The Dataset API is available in
Scala
and
Java
. Python does not have the support for the Dataset API. But due to Python’s dynamic nature,
many of the benefits of the Dataset API are already available (i.e. you can access the field of a row by name naturally
row.columnName
). The case for R is similar.
A DataFrame is a
Dataset
organized into named columns. It is conceptually
equivalent to a table in a relational database or a data frame in R/Python, but with richer
optimizations under the hood. DataFrames can be constructed from a wide array of
sources
such
as: structured data files, tables in Hive, external databases, or existing RDDs.
The DataFrame API is available in Scala,
Java,
Python
, and
R
.
In Scala and Java, a DataFrame is represented by a Dataset of
Row
s.
In
the Scala API
,
DataFrame
is simply a type alias of
Dataset[Row]
.
While, in
Java API
, users need to use
Dataset<Row>
to represent a
DataFrame
.
Throughout this document, we will often refer to Scala/Java Datasets of
Row
s as DataFrames.
Getting Started
Starting Point: SparkSession
The entry point into all functionality in Spark is the
SparkSession
class. To create a basic
SparkSession
, just use
SparkSession.builder()
:
importorg.apache.spark.sql.SparkSessionvalspark=SparkSession.builder().appName("Spark SQL basic example").config("spark.some.config.option","some-value").getOrCreate()// For implicit conversions like converting RDDs to DataFramesimportspark.implicits._
Find full example code at "examples/src/main/scala/org/apache/spark/examples/sql/SparkSQLExample.scala" in the Spark repo.
The entry point into all functionality in Spark is the SparkSession class. To create a basic SparkSession, just use SparkSession.builder():
Find full example code at "examples/src/main/r/RSparkSQLExample.R" in the Spark repo.
Note that when invoked for the first time, sparkR.session() initializes a global SparkSession singleton instance, and always returns a reference to this instance for successive invocations. In this way, users only need to initialize the SparkSession once, then SparkR functions like read.df will be able to access this global instance implicitly, and users don’t need to pass the SparkSession instance around.
SparkSession in Spark 2.0 provides builtin support for Hive features including the ability to
write queries using HiveQL, access to Hive UDFs, and the ability to read data from Hive tables.
To use these features, you do not need to have an existing Hive setup.
Creating DataFrames
With a SparkSession, applications can create DataFrames from an existing RDD,
from a Hive table, or from Spark data sources.
As an example, the following creates a DataFrame based on the content of a JSON file:
valdf=spark.read.json("examples/src/main/resources/people.json")// Displays the content of the DataFrame to stdoutdf.show()// +----+-------+// | age| name|// +----+-------+// |null|Michael|// | 30| Andy|// | 19| Justin|// +----+-------+
Find full example code at "examples/src/main/scala/org/apache/spark/examples/sql/SparkSQLExample.scala" in the Spark repo.
With a SparkSession, applications can create DataFrames from an existing RDD,
from a Hive table, or from Spark data sources.
As an example, the following creates a DataFrame based on the content of a JSON file:
importorg.apache.spark.sql.Dataset;importorg.apache.spark.sql.Row;Dataset<Row>df=spark.read().json("examples/src/main/resources/people.json");// Displays the content of the DataFrame to stdoutdf.show();// +----+-------+// | age| name|// +----+-------+// |null|Michael|// | 30| Andy|// | 19| Justin|// +----+-------+
Find full example code at "examples/src/main/java/org/apache/spark/examples/sql/JavaSparkSQLExample.java" in the Spark repo.
With a SparkSession, applications can create DataFrames from an existing RDD,
from a Hive table, or from Spark data sources.
As an example, the following creates a DataFrame based on the content of a JSON file:
# spark is an existing SparkSessiondf=spark.read.json("examples/src/main/resources/people.json")# Displays the content of the DataFrame to stdoutdf.show()# +----+-------+# | age| name|# +----+-------+# |null|Michael|# | 30| Andy|# | 19| Justin|# +----+-------+
Find full example code at "examples/src/main/python/sql/basic.py" in the Spark repo.
With a SparkSession, applications can create DataFrames from a local R data.frame,
from a Hive table, or from Spark data sources.
As an example, the following creates a DataFrame based on the content of a JSON file:
df <- read.json("examples/src/main/resources/people.json")# Displays the content of the DataFramehead(df)## age name## 1 NA Michael## 2 30 Andy## 3 19 Justin# Another method to print the first few rows and optionally truncate the printing of long values
showDF(df)## +----+-------+## | age| name|## +----+-------+## |null|Michael|## | 30| Andy|## | 19| Justin|## +----+-------+
Find full example code at "examples/src/main/r/RSparkSQLExample.R" in the Spark repo.
DataFrames provide a domain-specific language for structured data manipulation in Scala, Java, Python and R.
As mentioned above, in Spark 2.0, DataFrames are just Dataset of Rows in Scala and Java API. These operations are also referred as “untyped transformations” in contrast to “typed transformations” come with strongly typed Scala/Java Datasets.
Here we include some basic examples of structured data processing using Datasets:
// This import is needed to use the $-notationimportspark.implicits._// Print the schema in a tree formatdf.printSchema()// root// |-- age: long (nullable = true)// |-- name: string (nullable = true)// Select only the "name" columndf.select("name").show()// +-------+// | name|// +-------+// |Michael|// | Andy|// | Justin|// +-------+// Select everybody, but increment the age by 1df.select($"name",$"age"+1).show()// +-------+---------+// | name|(age + 1)|// +-------+---------+// |Michael| null|// | Andy| 31|// | Justin| 20|// +-------+---------+// Select people older than 21df.filter($"age">21).show()// +---+----+// |age|name|// +---+----+// | 30|Andy|// +---+----+// Count people by agedf.groupBy("age").count().show()// +----+-----+// | age|count|// +----+-----+// | 19| 1|// |null| 1|// | 30| 1|// +----+-----+
Find full example code at "examples/src/main/scala/org/apache/spark/examples/sql/SparkSQLExample.scala" in the Spark repo.
For a complete list of the types of operations that can be performed on a Dataset refer to the API Documentation.
In addition to simple column references and expressions, Datasets also have a rich library of functions including string manipulation, date arithmetic, common math operations and more. The complete list is available in the DataFrame Function Reference.
// col("...") is preferable to df.col("...")import staticorg.apache.spark.sql.functions.col
;// Print the schema in a tree formatdf.printSchema();// root// |-- age: long (nullable = true)// |-- name: string (nullable = true)// Select only the "name" columndf.select("name").show();// +-------+// | name|// +-------+// |Michael|// | Andy|// | Justin|// +-------+// Select everybody, but increment the age by 1df.select(col("name"),col("age").plus(1)).show();// +-------+---------+// | name|(age + 1)|// +-------+---------+// |Michael| null|// | Andy| 31|// | Justin| 20|// +-------+---------+// Select people older than 21df.filter(col("age").gt(21)).show();// +---+----+// |age|name|// +---+----+// | 30|Andy|// +---+----+// Count people by agedf.groupBy("age").count().show();// +----+-----+// | age|count|// +----+-----+// | 19| 1|// |null| 1|// | 30| 1|// +----+-----+
Find full example code at "examples/src/main/java/org/apache/spark/examples/sql/JavaSparkSQLExample.java" in the Spark repo.
For a complete list of the types of operations that can be performed on a Dataset refer to the API Documentation.
In addition to simple column references and expressions, Datasets also have a rich library of functions including string manipulation, date arithmetic, common math operations and more. The complete list is available in the DataFrame Function Reference.
In Python it’s possible to access a DataFrame’s columns either by attribute
(df.age) or by indexing (df['age']). While the former is convenient for
interactive data exploration, users are highly encouraged to use the
latter form, which is future proof and won’t break with column names that
are also attributes on the DataFrame class.
# spark, df are from the previous example# Print the schema in a tree formatdf.printSchema()# root# |-- age: long (nullable = true)# |-- name: string (nullable = true)# Select only the "name" columndf.select("name").show()# +-------+# | name|# +-------+# |Michael|# | Andy|# | Justin|# +-------+# Select everybody, but increment the age by 1df.select(df['name'],df['age']+1).show()# +-------+---------+# | name|(age + 1)|# +-------+---------+# |Michael| null|# | Andy| 31|# | Justin| 20|# +-------+---------+# Select people older than 21df.filter(df['age']>21).show()# +---+----+# |age|name|# +---+----+# | 30|Andy|# +---+----+# Count people by agedf.groupBy("age").count().show()# +----+-----+# | age|count|# +----+-----+# | 19| 1|# |null| 1|# | 30| 1|# +----+-----+
Find full example code at "examples/src/main/python/sql/basic.py" in the Spark repo.
For a complete list of the types of operations that can be performed on a DataFrame refer to the API Documentation.
In addition to simple column references and expressions, DataFrames also have a rich library of functions including string manipulation, date arithmetic, common math operations and more. The complete list is available in the DataFrame Function Reference.
df <- read.json("examples/src/main/resources/people.json")# Show the content of the DataFramehead(df)## age name## 1 NA Michael## 2 30 Andy## 3 19 Justin# Print the schema in a tree format
printSchema(df)## root## |-- age: long (nullable = true)## |-- name: string (nullable = true)# Select only the "name" columnhead(select(df,"name"))## name## 1 Michael## 2 Andy## 3 Justin# Select everybody, but increment the age by 1head(select(df, df$name, df$age +1))## name (age + 1.0)## 1 Michael NA## 2 Andy 31## 3 Justin 20# Select people older than 21head(where(df, df$age >21))## age name## 1 30 Andy# Count people by agehead(count(groupBy(df,"age")))## age count## 1 19 1## 2 NA 1## 3 30 1
Find full example code at "examples/src/main/r/RSparkSQLExample.R" in the Spark repo.
For a complete list of the types of operations that can be performed on a DataFrame refer to the API Documentation.
In addition to simple column references and expressions, DataFrames also have a rich library of functions including string manipulation, date arithmetic, common math operations and more. The complete list is available in the DataFrame Function Reference.
The sql function on a SparkSession enables applications to run SQL queries programmatically and returns the result as a DataFrame.
// Register the DataFrame as a SQL temporary viewdf.createOrReplaceTempView("people")valsqlDF=spark.sql("SELECT * FROM people")sqlDF.show()// +----+-------+// | age| name|// +----+-------+// |null|Michael|// | 30| Andy|// | 19| Justin|// +----+-------+
Find full example code at "examples/src/main/scala/org/apache/spark/examples/sql/SparkSQLExample.scala" in the Spark repo.
The sql function on a SparkSession enables applications to run SQL queries programmatically and returns the result as a Dataset<Row>.
importorg.apache.spark.sql.Dataset;importorg.apache.spark.sql.Row;// Register the DataFrame as a SQL temporary viewdf.createOrReplaceTempView("people");Dataset<Row>sqlDF=spark.sql("SELECT * FROM people");sqlDF.show();// +----+-------+// | age| name|// +----+-------+// |null|Michael|// | 30| Andy|// | 19| Justin|// +----+-------+
Find full example code at "examples/src/main/java/org/apache/spark/examples/sql/JavaSparkSQLExample.java" in the Spark repo.
The sql function on a SparkSession enables applications to run SQL queries programmatically and returns the result as a DataFrame.
# Register the DataFrame as a SQL temporary viewdf.createOrReplaceTempView("people")sqlDF=spark.sql("SELECT * FROM people")sqlDF.show()# +----+-------+# | age| name|# +----+-------+# |null|Michael|# | 30| Andy|# | 19| Justin|# +----+-------+
Find full example code at "examples/src/main/python/sql/basic.py" in the Spark repo.
The sql function enables applications to run SQL queries programmatically and returns the result as a SparkDataFrame.
df <- sql("SELECT * FROM table")
Find full example code at "examples/src/main/r/RSparkSQLExample.R" in the Spark repo.
Global Temporary View
Temporary views in Spark SQL are session-scoped and will disappear if the session that creates it
terminates. If you want to have a temporary view that is shared among all sessions and keep alive
until the Spark application terminates, you can create a global temporary view. Global temporary
view is tied to a system preserved database global_temp, and we must use the qualified name to
refer it, e.g. SELECT * FROM global_temp.view1.
// Register the DataFrame as a global temporary viewdf.createGlobalTempView("people")// Global temporary view is tied to a system preserved database `global_temp`spark.sql("SELECT * FROM global_temp.people").show()// +----+-------+// | age| name|// +----+-------+// |null|Michael|// | 30| Andy|// | 19| Justin|// +----+-------+// Global temporary view is cross-sessionspark.newSession().sql("SELECT * FROM global_temp.people").show()// +----+-------+// | age| name|// +----+-------+// |null|Michael|// | 30| Andy|// | 19| Justin|// +----+-------+
Find full example code at "examples/src/main/scala/org/apache/spark/examples/sql/SparkSQLExample.scala" in the Spark repo.
// Register the DataFrame as a global temporary viewdf.createGlobalTempView("people");// Global temporary view is tied to a system preserved database `global_temp`spark.sql("SELECT * FROM global_temp.people").show();// +----+-------+// | age| name|// +----+-------+// |null|Michael|// | 30| Andy|// | 19| Justin|// +----+-------+// Global temporary view is cross-sessionspark.newSession().sql("SELECT * FROM global_temp.people").show();// +----+-------+// | age| name|// +----+-------+// |null|Michael|// | 30| Andy|
// | 19| Justin|// +----+-------+
Find full example code at "examples/src/main/java/org/apache/spark/examples/sql/JavaSparkSQLExample.java" in the Spark repo.
# Register the DataFrame as a global temporary viewdf.createGlobalTempView("people")# Global temporary view is tied to a system preserved database `global_temp`spark.sql("SELECT * FROM global_temp.people").show()# +----+-------+# | age| name|# +----+-------+# |null|Michael|# | 30| Andy|# | 19| Justin|# +----+-------+# Global temporary view is cross-sessionspark.newSession().sql("SELECT * FROM global_temp.people").show()# +----+-------+# | age| name|# +----+-------+# |null|Michael|# | 30| Andy|# | 19| Justin|# +----+-------+
Find full example code at "examples/src/main/python/sql/basic.py" in the Spark repo.
Creating Datasets
Datasets are similar to RDDs, however, instead of using Java serialization or Kryo they use
a specialized Encoder to serialize the objects
for processing or transmitting over the network. While both encoders and standard serialization are
responsible for turning an object into bytes, encoders are code generated dynamically and use a format
that allows Spark to perform many operations like filtering, sorting and hashing without deserializing
the bytes back into an object.
caseclassPerson(name:String,age:Long)// Encoders are created for case classesvalcaseClassDS=Seq(Person("Andy",32)).toDS()caseClassDS.show()// +----+---+// |name|age|// +----+---+// |Andy| 32|// +----+---+// Encoders for most common types are automatically provided by importing spark.implicits._valprimitiveDS=Seq(1,2,3).toDS()primitiveDS.map(_+1).collect()// Returns: Array(2, 3, 4)// DataFrames can be converted to a Dataset by providing a class. Mapping will be done by namevalpath="examples/src/main/resources/people.json"valpeopleDS=spark.read.json(path).as[Person]peopleDS.show()// +----+-------+// | age| name|// +----+-------+// |null|Michael|// | 30| Andy|// | 19| Justin|// +----+-------+
Find full example code at "examples/src/main/scala/org/apache/spark/examples/sql/SparkSQLExample.scala" in the Spark repo.
importjava.util.Arrays;importjava.util.Collections;importjava.io.Serializable;importorg.apache.spark.api.java.function.MapFunction;importorg.apache.spark.sql.Dataset;importorg.apache.spark.sql.Row;importorg.apache.spark.sql.Encoder;importorg.apache.spark.sql.Encoders;publicstaticclassPersonimplementsSerializable{privateStringname;privateintage;publicStringgetName(){returnname;publicvoidsetName(Stringname){this.name=name;publicintgetAge(){returnage;publicvoidsetAge(intage){this.age=age;// Create an instance of a Bean classPersonperson=newPerson();person.setName("Andy");person.setAge(32);// Encoders are created for Java beansEncoder<Person>personEncoder=Encoders.bean(Person.class);Dataset<Person>javaBeanDS=spark.createDataset(Collections.singletonList(person),personEncoderjavaBeanDS.show();// +---+----+// |age|name|// +---+----+// | 32|Andy|// +---+----+// Encoders for most common types are provided in class EncodersEncoder<Integer>integerEncoder=Encoders.INT();Dataset<Integer>primitiveDS=spark.createDataset(Arrays.asList(1,2,3),integerEncoder);Dataset<Integer>transformedDS=primitiveDS.map((MapFunction<Integer,Integer>)value->value+1,integerEncoder);transformedDS.collect();// Returns [2, 3, 4]// DataFrames can be converted to a Dataset by providing a class. Mapping based on nameStringpath="examples/src/main/resources/people.json";Dataset<Person>peopleDS=spark.read().json(path).as(personEncoder);peopleDS.show();// +----+-------+// | age| name|// +----+-------+// |null|Michael|// | 30| Andy|// | 19| Justin|// +----+-------+
Find full example code at "examples/src/main/java/org/apache/spark/examples/sql/JavaSparkSQLExample.java" in the Spark repo.
Interoperating with RDDs
Spark SQL supports two different methods for converting existing RDDs into Datasets. The first
method uses reflection to infer the schema of an RDD that contains specific types of objects. This
reflection based approach leads to more concise code and works well when you already know the schema
while writing your Spark application.
The second method for creating Datasets is through a programmatic interface that allows you to
construct a schema and then apply it to an existing RDD. While this method is more verbose, it allows
you to construct Datasets when the columns and their types are not known until runtime.
Inferring the Schema Using Reflection
The Scala interface for Spark SQL supports automatically converting an RDD containing case classes
to a DataFrame. The case class
defines the schema of the table. The names of the arguments to the case class are read using
reflection and become the names of the columns. Case classes can also be nested or contain complex
types such as Seqs or Arrays. This RDD can be implicitly converted to a DataFrame and then be
registered as a table. Tables can be used in subsequent SQL statements.
// For implicit conversions from RDDs to DataFramesimportspark.implicits._// Create an RDD of Person objects from a text file, convert it to a DataframevalpeopleDF=spark.sparkContext.textFile("examples/src/main/resources/people.txt").map(_.split(",")).map(attributes=>Person(attributes(0),attributes(1).trim.toInt)).toDF()// Register the DataFrame as a temporary viewpeopleDF.createOrReplaceTempView("people")// SQL statements can be run by using the sql methods provided by SparkvalteenagersDF=spark.sql("SELECT name, age FROM people WHERE age BETWEEN 13 AND 19")// The columns of a row in the result can be accessed by field indexteenagersDF.map(teenager=>"Name: "+teenager(0)).show()// +------------+// | value|// +------------+// |Name: Justin|// +------------+// or by field nameteenagersDF.map(teenager=>"Name: "+teenager.getAs[String]("name")).show()// +------------+// | value|// +------------+// |Name: Justin|// +------------+// No pre-defined encoders for Dataset[Map[K,V]], define explicitlyimplicitvalmapEncoder=org.apache.spark.sql.Encoders.kryo[Map[String, Any]]// Primitive types and case classes can be also defined as// implicit val stringIntMapEncoder: Encoder[Map[String, Any]] = ExpressionEncoder()
// row.getValuesMap[T] retrieves multiple columns at once into a Map[String, T]teenagersDF.map(teenager=>teenager.getValuesMap[Any](List("name","age"))).collect()// Array(Map("name" -> "Justin", "age" -> 19))
Find full example code at "examples/src/main/scala/org/apache/spark/examples/sql/SparkSQLExample.scala" in the Spark repo.
Spark SQL supports automatically converting an RDD of
JavaBeans into a DataFrame.
The BeanInfo, obtained using reflection, defines the schema of the table. Currently, Spark SQL
does not support JavaBeans that contain Map field(s). Nested JavaBeans and List or Array
fields are supported though. You can create a JavaBean by creating a class that implements
Serializable and has getters and setters for all of its fields.
importorg.apache.spark.api.java.JavaRDD;importorg.apache.spark.api.java.function.Function;importorg.apache.spark.api.java.function.MapFunction;importorg.apache.spark.sql.Dataset;importorg.apache.spark.sql.Row;importorg.apache.spark.sql.Encoder;importorg.apache.spark.sql.Encoders;// Create an RDD of Person objects from a text fileJavaRDD<Person>peopleRDD=spark.read().textFile("examples/src/main/resources/people.txt").javaRDD().map(line->{String[]parts=line.split(",");Personperson=newPerson();person.setName(parts[0]);person.setAge(Integer.parseInt(parts[1].trim()));returnperson;// Apply a schema to an RDD of JavaBeans to get a DataFrameDataset<Row>peopleDF=spark.createDataFrame(peopleRDD,Person.class);// Register the DataFrame as a temporary viewpeopleDF.createOrReplaceTempView("people");// SQL statements can be run by using the sql methods provided by sparkDataset<Row>teenagersDF=spark.sql("SELECT name FROM people WHERE age BETWEEN 13 AND 19");// The columns of a row in the result can be accessed by field indexEncoder<String>stringEncoder=Encoders.STRING();Dataset<String>teenagerNamesByIndexDF=teenagersDF.map((MapFunction<Row,String>)row->"Name: "+row.getString(0),stringEncoder);teenagerNamesByIndexDF.show();// +------------+// | value|// +------------+// |Name: Justin|// +------------+// or by field nameDataset<String>teenagerNamesByFieldDF=teenagersDF.map((MapFunction<Row,String>)row->"Name: "+row.<String>getAs("name"),stringEncoder);teenagerNamesByFieldDF.show();// +------------+// | value|// +------------+// |Name: Justin|// +------------+
Find full example code at "examples/src/main/java/org/apache/spark/examples/sql/JavaSparkSQLExample.java" in the Spark repo.
Spark SQL can convert an RDD of Row objects to a DataFrame, inferring the datatypes. Rows are constructed by passing a list of
key/value pairs as kwargs to the Row class. The keys of this list define the column names of the table,
and the types are inferred by sampling the whole dataset, similar to the inference that is performed on JSON files.
frompyspark.sqlimportRowsc=spark.sparkContext# Load a text file and convert each line to a Row.lines=sc.textFile("examples/src/main/resources/people.txt")parts=lines.map(lambdal:l.split(","))people=parts.map(lambdap:Row(name=p[0],age=int(p[1])))# Infer the schema, and register the DataFrame as a table.schemaPeople=spark.createDataFrame(people)schemaPeople.createOrReplaceTempView("people")# SQL can be run over DataFrames that have been registered as a table.teenagers=spark.sql("SELECT name FROM people WHERE age >= 13 AND age <= 19")# The results of SQL queries are Dataframe objects.# rdd returns the content as an :class:`pyspark.RDD` of :class:`Row`.teenNames=teenagers.rdd.map(lambdap:"Name: "+p.name).collect()fornameinteenNames:print(name)# Name: Justin
Find full example code at "examples/src/main/python/sql/basic.py" in the Spark repo.
When case classes cannot be defined ahead of time (for example,
the structure of records is encoded in a string, or a text dataset will be parsed
and fields will be projected differently for different users),
a DataFrame can be created programmatically with three steps.
Create an RDD of Rows from the original RDD;
Create the schema represented by a StructType matching the structure of
Rows in the RDD created in Step 1.
Apply the schema to the RDD of Rows via createDataFrame method provided
by SparkSession.
For example:
importorg.apache.spark.sql.types._// Create an RDDvalpeopleRDD=spark.sparkContext.textFile("examples/src/main/resources/people.txt")// The schema is encoded in a stringvalschemaString="name age"// Generate the schema based on the string of schemavalfields=schemaString.split(" ").map(fieldName=>StructField(fieldName,StringType,nullable=true))valschema=StructType(fields)// Convert records of the RDD (people) to RowsvalrowRDD=peopleRDD.map(_.split(",")).map(attributes=>Row(attributes(0),attributes(1).trim))// Apply the schema to the RDDvalpeopleDF=spark.createDataFrame(rowRDD,schema)// Creates a temporary view using the DataFramepeopleDF.createOrReplaceTempView("people")// SQL can be run over a temporary view created using DataFramesvalresults=spark.sql("SELECT name FROM people")// The results of SQL queries are DataFrames and support all the normal RDD operations// The columns of a row in the result can be accessed by field index or by field nameresults.map(attributes=>"Name: "+attributes(0)).show()// +-------------+// | value|// +-------------+// |Name: Michael|// | Name: Andy|// | Name: Justin|// +-------------+
Find full example code at "examples/src/main/scala/org/apache/spark/examples/sql/SparkSQLExample.scala" in the Spark repo.
When JavaBean classes cannot be defined ahead of time (for example,
the structure of records is encoded in a string, or a text dataset will be parsed and
fields will be projected differently for different users),
a Dataset<Row> can be created programmatically with three steps.
Create an RDD of Rows from the original RDD;
Create the schema represented by a StructType matching the structure of
Rows in the RDD created in Step 1.
Apply the schema to the RDD of Rows via createDataFrame method provided
by SparkSession.
For example:
importjava.util.ArrayList;importjava.util.List;importorg.apache.spark.api.java.JavaRDD;importorg.apache.spark.api.java.function.Function;importorg.apache.spark.sql.Dataset;import
org.apache.spark.sql.Row;importorg.apache.spark.sql.types.DataTypes;importorg.apache.spark.sql.types.StructField;importorg.apache.spark.sql.types.StructType;// Create an RDDJavaRDD<String>peopleRDD=spark.sparkContext().textFile("examples/src/main/resources/people.txt",1).toJavaRDD();// The schema is encoded in a stringStringschemaString="name age";// Generate the schema based on the string of schemaList<StructField>fields=newArrayList<>();for(StringfieldName:schemaString.split(" ")){StructFieldfield=DataTypes.createStructField(fieldName,DataTypes.StringType,true);fields.add(field);StructTypeschema=DataTypes.createStructType(fields);// Convert records of the RDD (people) to RowsJavaRDD<Row>rowRDD=peopleRDD.map((Function<String,Row>)record->{String[]attributes=record.split(",");returnRowFactory.create(attributes[0],attributes[1].trim());// Apply the schema to the RDDDataset<Row>peopleDataFrame=spark.createDataFrame(rowRDD,schema);// Creates a temporary view using the DataFramepeopleDataFrame.createOrReplaceTempView("people");// SQL can be run over a temporary view created using DataFramesDataset<Row>results=spark.sql("SELECT name FROM people");// The results of SQL queries are DataFrames and support all the normal RDD operations// The columns of a row in the result can be accessed by field index or by field nameDataset<String>namesDS=results.map((MapFunction<Row,String>)row->"Name: "+row.getString(0),Encoders.STRING());namesDS.show();// +-------------+// | value|// +-------------+// |Name: Michael|// | Name: Andy|// | Name: Justin|// +-------------+
Find full example code at "examples/src/main/java/org/apache/spark/examples/sql/JavaSparkSQLExample.java" in the Spark repo.
When a dictionary of kwargs cannot be defined ahead of time (for example,
the structure of records is encoded in a string, or a text dataset will be parsed and
fields will be projected differently for different users),
a DataFrame can be created programmatically with three steps.
Create an RDD of tuples or lists from the original RDD;
Create the schema represented by a StructType matching the structure of
tuples or lists in the RDD created in the step 1.
Apply the schema to the RDD via createDataFrame method provided by SparkSession.
For example:
# Import data typesfrompyspark.sql.typesimport*sc=spark.sparkContext# Load a text file and convert each line to a Row.lines=sc.textFile("examples/src/main/resources/people.txt")parts=lines.map(lambdal:l.split(","))# Each line is converted to a tuple.people=parts.map(lambdap:(p[0],p[1].strip()))# The schema is encoded in a string.schemaString="name age"fields=[StructField(field_name,StringType(),True)forfield_nameinschemaString.split()]schema=StructType(fields)# Apply the schema to the RDD.schemaPeople=spark.createDataFrame(people,schema)# Creates a temporary view using the DataFrameschemaPeople.createOrReplaceTempView("people")# SQL can be run over DataFrames that have been registered as a table.results=spark.sql("SELECT name FROM people")results.show()# +-------+# | name|# +-------+# |Michael|# | Andy|# | Justin|# +-------+
Find full example code at "examples/src/main/python/sql/basic.py" in the Spark repo.
The built-in DataFrames functions provide common
aggregations such as count(), countDistinct(), avg(), max(), min(), etc.
While those functions are designed for DataFrames, Spark SQL also has type-safe versions for some of them in
Scala and
Java to work with strongly typed Datasets.
Moreover, users are not limited to the predefined aggregate functions and can create their own.
Untyped User-Defined Aggregate Functions
Users have to extend the UserDefinedAggregateFunction
abstract class to implement a custom untyped aggregate function. For example, a user-defined average
can look like:
importorg.apache.spark.sql.{Row,SparkSession}importorg.apache.spark.sql.expressions.MutableAggregationBufferimportorg.apache.spark.sql.expressions.UserDefinedAggregateFunctionimportorg.apache.spark.sql.types._objectMyAverageextendsUserDefinedAggregateFunction{// Data types of input arguments of this aggregate functiondefinputSchema:StructType=StructType(StructField("inputColumn",LongType)::Nil)// Data types of values in the aggregation bufferdefbufferSchema:StructType={StructType(StructField("sum",LongType)::StructField("count",LongType)::Nil)// The data type of the returned valuedefdataType:DataType=DoubleType// Whether this function always returns the same output on the identical inputdefdeterministic:Boolean=true// Initializes the given aggregation buffer. The buffer itself is a `Row` that in addition to// standard methods like retrieving a value at an index (e.g., get(), getBoolean()), provides// the opportunity to update its values. Note that arrays and maps inside the buffer are still// immutable.definitialize(buffer:MutableAggregationBuffer):Unit={buffer(0)=0Lbuffer(1)=0L// Updates the given aggregation buffer `buffer` with new input data from `input`defupdate(buffer:MutableAggregationBuffer,input:Row):Unit={if(!input.isNullAt(0)){buffer(0)=buffer.getLong(0)+input.getLong(0)buffer(1)=buffer.getLong(1)+1// Merges two aggregation buffers and stores the updated buffer values back to `buffer1`defmerge(buffer1:MutableAggregationBuffer,buffer2:Row):Unit={buffer1(0)=buffer1.getLong(0)+buffer2.getLong(0)buffer1(1)=buffer1.getLong
(1)+buffer2.getLong(1)// Calculates the final resultdefevaluate(buffer:Row):Double=buffer.getLong(0).toDouble/buffer.getLong(1)// Register the function to access itspark.udf.register("myAverage",MyAverage)valdf=spark.read.json("examples/src/main/resources/employees.json")df.createOrReplaceTempView("employees")df.show()// +-------+------+// | name|salary|// +-------+------+// |Michael| 3000|// | Andy| 4500|// | Justin| 3500|// | Berta| 4000|// +-------+------+valresult=spark.sql("SELECT myAverage(salary) as average_salary FROM employees")result.show()// +--------------+// |average_salary|// +--------------+// | 3750.0|// +--------------+
Find full example code at "examples/src/main/scala/org/apache/spark/examples/sql/UserDefinedUntypedAggregation.scala" in the Spark repo.
importjava.util.ArrayList;importjava.util.List;importorg.apache.spark.sql.Dataset;importorg.apache.spark.sql.Row;importorg.apache.spark.sql.SparkSession;importorg.apache.spark.sql.expressions.MutableAggregationBuffer;importorg.apache.spark.sql.expressions.UserDefinedAggregateFunction;importorg.apache.spark.sql.types.DataType;importorg.apache.spark.sql.types.DataTypes;importorg.apache.spark.sql.types.StructField;importorg.apache.spark.sql.types.StructType;publicstaticclassMyAverageextendsUserDefinedAggregateFunction{privateStructTypeinputSchema;privateStructTypebufferSchema;publicMyAverage(){List<StructField>inputFields=newArrayList<>();inputFields.add(DataTypes.createStructField("inputColumn",DataTypes.LongType,true));inputSchema=DataTypes.createStructType(inputFields);List<StructField>bufferFields=newArrayList<>();bufferFields.add(DataTypes.createStructField("sum",DataTypes.LongType,true));bufferFields.add(DataTypes.createStructField("count",DataTypes.LongType,true));bufferSchema=DataTypes.createStructType(bufferFields);// Data types of input arguments of this aggregate functionpublicStructTypeinputSchema(){returninputSchema;// Data types of values in the aggregation bufferpublicStructTypebufferSchema(){returnbufferSchema;// The data type of the returned valuepublicDataTypedataType(){returnDataTypes.DoubleType;// Whether this function always returns the same output on the identical inputpublicbooleandeterministic(){returntrue;// Initializes the given aggregation buffer. The buffer itself is a `Row` that in addition to// standard methods like retrieving a value at an index (e.g., get(), getBoolean()), provides// the opportunity to update its values. Note that arrays and maps inside the buffer are still// immutable.publicvoidinitialize(MutableAggregationBufferbuffer){buffer.update(0,0L);buffer.update(1,0L);// Updates the given aggregation buffer `buffer` with new input data from `input`publicvoidupdate(MutableAggregationBufferbuffer,Rowinput){if(!input.isNullAt(0)){longupdatedSum=buffer.getLong(0)+input.getLong(0);longupdatedCount=buffer.getLong(1)+1;buffer.update(0,updatedSum);buffer.update(1,updatedCount);// Merges two aggregation buffers and stores the updated buffer values back to `buffer1`publicvoidmerge(MutableAggregationBufferbuffer1,Rowbuffer2){longmergedSum=buffer1.getLong(0)+buffer2.getLong(0);longmergedCount=buffer1.getLong(1)+buffer2.getLong(1);buffer1.update(0,mergedSum);buffer1.update(1,mergedCount);// Calculates the final resultpublicDoubleevaluate(Rowbuffer){return((double)buffer.getLong(0))/buffer.getLong(1);// Register the function to access itspark.udf().register("myAverage",newMyAverage());Dataset<Row>df=spark.read().json("examples/src/main/resources/employees.json");df.createOrReplaceTempView("employees");df.show();// +-------+------+// | name|salary|// +-------+------+// |Michael| 3000|// | Andy| 4500|// | Justin| 3500|// | Berta| 4000|// +-------+------+Dataset<Row>result=spark.sql("SELECT myAverage(salary) as average_salary FROM employees");result.show();// +--------------+// |average_salary|// +--------------+// | 3750.0|// +--------------+
Find full example code at "examples/src/main/java/org/apache/spark/examples/sql/JavaUserDefinedUntypedAggregation.java" in the Spark repo.
Type-Safe User-Defined Aggregate Functions
User-defined aggregations for strongly typed Datasets revolve around the Aggregator abstract class.
For example, a type-safe user-defined average can look like:
importorg.apache.spark.sql.{Encoder,Encoders,SparkSession}importorg.apache.spark.sql.expressions.AggregatorcaseclassEmployee(name:String,salary:Long)caseclassAverage(varsum:Long,varcount:Long)objectMyAverageextendsAggregator[Employee, Average, Double]{// A zero value for this aggregation. Should satisfy the property that any b + zero = bdefzero:Average=Average(0L,0L)// Combine two values to produce a new value. For performance, the function may modify `buffer`// and return it instead of constructing a new objectdef
reduce(buffer:Average,employee:Employee):Average={buffer.sum+=employee.salarybuffer.count+=1buffer// Merge two intermediate valuesdefmerge(b1:Average,b2:Average):Average={b1.sum+=b2.sumb1.count+=b2.count// Transform the output of the reductiondeffinish(reduction:Average):Double=reduction.sum.toDouble/reduction.count// Specifies the Encoder for the intermediate value typedefbufferEncoder:Encoder[Average]=Encoders.product// Specifies the Encoder for the final output value typedefoutputEncoder:Encoder[Double]=Encoders.scalaDoublevalds=spark.read.json("examples/src/main/resources/employees.json").as[Employee]ds.show()// +-------+------+// | name|salary|// +-------+------+// |Michael| 3000|// | Andy| 4500|// | Justin| 3500|// | Berta| 4000|// +-------+------+// Convert the function to a `TypedColumn` and give it a namevalaverageSalary=MyAverage.toColumn.name("average_salary")valresult=ds.select(averageSalary)result.show()// +--------------+// |average_salary|// +--------------+// | 3750.0|// +--------------+
Find full example code at "examples/src/main/scala/org/apache/spark/examples/sql/UserDefinedTypedAggregation.scala" in the Spark repo.
importjava.io.Serializable;importorg.apache.spark.sql.Dataset;importorg.apache.spark.sql.Encoder;importorg.apache.spark.sql.Encoders;importorg.apache.spark.sql.SparkSession;importorg.apache.spark.sql.TypedColumn;importorg.apache.spark.sql.expressions.Aggregator;publicstaticclassEmployeeimplementsSerializable{privateStringname;privatelongsalary;// Constructors, getters, setters...publicstaticclassAverageimplementsSerializable{privatelongsum;privatelongcount;// Constructors, getters, setters...publicstaticclassMyAverageextendsAggregator<Employee,Average,Double>{// A zero value for this aggregation. Should satisfy the property that any b + zero = bpublicAveragezero(){returnnewAverage(0L,0L);// Combine two values to produce a new value. For performance, the function may modify `buffer`// and return it instead of constructing a new objectpublicAveragereduce(Averagebuffer,Employeeemployee){longnewSum=buffer.getSum()+employee.getSalary();longnewCount=buffer.getCount()+1;buffer.setSum(newSum);buffer.setCount(newCount);returnbuffer;// Merge two intermediate valuespublicAveragemerge(Averageb1,Averageb2){longmergedSum=b1.getSum()+b2.getSum();longmergedCount=b1.getCount()+b2.getCount();b1.setSum(mergedSum);b1.setCount(mergedCount);returnb1;// Transform the output of the reductionpublicDoublefinish(Averagereduction){return((double)reduction.getSum())/reduction.getCount();// Specifies the Encoder for the intermediate value typepublicEncoder<Average>bufferEncoder(){returnEncoders.bean(Average.class);// Specifies the Encoder for the final output value typepublicEncoder<Double>outputEncoder(){returnEncoders.DOUBLE();Encoder<Employee>employeeEncoder=Encoders.bean(Employee.class);Stringpath="examples/src/main/resources/employees.json";Dataset<Employee>ds=spark.read().json(path).as(employeeEncoder);ds.show();// +-------+------+// | name|salary|// +-------+------+// |Michael| 3000|// | Andy| 4500|// | Justin| 3500|// | Berta| 4000|// +-------+------+MyAveragemyAverage=newMyAverage();// Convert the function to a `TypedColumn` and give it a nameTypedColumn<Employee,Double>averageSalary=myAverage.toColumn().name("average_salary");Dataset<Double>result=ds.select(averageSalary);result.show();// +--------------+// |average_salary|// +--------------+// | 3750.0|// +--------------+
Find full example code at "examples/src/main/java/org/apache/spark/examples/sql/JavaUserDefinedTypedAggregation.java" in the Spark repo.
Data Sources
Spark SQL supports operating on a variety of data sources through the DataFrame interface.
A DataFrame can be operated on using relational transformations and can also be used to create a temporary view.
Registering a DataFrame as a temporary view allows you to run SQL queries over its data. This section
describes the general methods for loading and saving data using the Spark Data Sources and then
goes into specific options that are available for the built-in data sources.
Generic Load/Save Functions
In the simplest form, the default data source (parquet unless otherwise configured by
spark.sql.sources.default) will be used for all operations.
Find full example code at "examples/src/main/r/RSparkSQLExample.R" in the Spark repo.
Manually Specifying Options
You can also manually specify the data source that will be used along with any extra options
that you would like to pass to the data source. Data sources are specified by their fully qualified
name (i.e., org.apache.spark.sql.parquet), but for built-in sources you can also use their short
names (json, parquet, jdbc, orc, libsvm, csv, text). DataFrames loaded from any data
source type can be converted into other types using this syntax.
Find full example code at "examples/src/main/r/RSparkSQLExample.R" in the Spark repo.
Run SQL on files directly
Instead of using read API to load a file into DataFrame and query it, you can also query that
file directly with SQL.
valsqlDF=spark.sql("SELECT * FROM parquet.`examples/src/main/resources/users.parquet`")
Find full example code at "examples/src/main/scala/org/apache/spark/examples/sql/SQLDataSourceExample.scala" in the Spark repo.
Dataset<Row>sqlDF=spark.sql("SELECT * FROM parquet.`examples/src/main/resources/users.parquet`");
Find full example code at "examples/src/main/java/org/apache/spark/examples/sql/JavaSQLDataSourceExample.java" in the Spark repo.
df=spark.sql("SELECT * FROM parquet.`examples/src/main/resources/users.parquet`")
Find full example code at "examples/src/main/python/sql/datasource.py" in the Spark repo.
df <- sql("SELECT * FROM parquet.`examples/src/main/resources/users.parquet`")
Find full example code at "examples/src/main/r/RSparkSQLExample.R" in the Spark repo.
Save Modes
Save operations can optionally take a SaveMode, that specifies how to handle existing data if
present. It is important to realize that these save modes do not utilize any locking and are not
atomic. Additionally, when performing an Overwrite, the data will be deleted before writing out the
new data.
Scala/JavaAny LanguageMeaning
SaveMode.ErrorIfExists (default)
"error" or "errorifexists" (default)
When saving a DataFrame to a data source, if data already exists,
an exception is expected to be thrown.
SaveMode.Append"append"
When saving a DataFrame to a data source, if data/table already exists,
contents of the DataFrame are expected to be appended to existing data.
SaveMode.Overwrite"overwrite"
Overwrite mode means that when saving a DataFrame to a data source,
if data/table already exists, existing data is expected to be overwritten by the contents of
the DataFrame.
SaveMode.Ignore"ignore"
Ignore mode means that when saving a DataFrame to a data source, if data already exists,
the save operation is expected to not save the contents of the DataFrame and to not
change the existing data. This is similar to a CREATE TABLE IF NOT EXISTS in SQL.
Saving to Persistent Tables
DataFrames can also be saved as persistent tables into Hive metastore using the saveAsTable
command. Notice that an existing Hive deployment is not necessary to use this feature. Spark will create a
default local Hive metastore (using Derby) for you. Unlike the createOrReplaceTempView command,
saveAsTable will materialize the contents of the DataFrame and create a pointer to the data in the
Hive metastore. Persistent tables will still exist even after your Spark program has restarted, as
long as you maintain your connection to the same metastore. A DataFrame for a persistent table can
be created by calling the table method on a SparkSession with the name of the table.
For file-based data source, e.g. text, parquet, json, etc. you can specify a custom table path via the
path option, e.g. df.write.option("path", "/some/path").saveAsTable("t"). When the table is dropped,
the custom table path will not be removed and the table data is still there. If no custom table path is
specified, Spark will write data to a default table path under the warehouse directory. When the table is
dropped, the default table path will be removed too.
Starting from Spark 2.1, persistent datasource tables have per-partition metadata stored in the Hive metastore. This brings several benefits:
Since the metastore can return only necessary partitions for a query, discovering all the partitions on the first query to the table is no longer needed.
Hive DDLs such as ALTER TABLE PARTITION ... SET LOCATION are now available for tables created with the Datasource API.
Note that partition information is not gathered by default when creating external datasource tables (those with a path option). To sync the partition information in the metastore, you can invoke MSCK REPAIR TABLE.
Bucketing, Sorting and Partitioning
For file-based data source, it is also possible to bucket and sort or partition the output.
Bucketing and sorting are applicable only to persistent tables:
Find full example code at "examples/src/main/python/sql/datasource.py" in the Spark repo.
partitionBy creates a directory structure as described in the Partition Discovery section.
Thus, it has limited applicability to columns with high cardinality. In contrast
bucketBy distributes
data across a fixed number of buckets and can be used when a number of unique values is unbounded.
Parquet Files
Parquet is a columnar format that is supported by many other data processing systems.
Spark SQL provides support for both reading and writing Parquet files that automatically preserves the schema
of the original data. When writing Parquet files, all columns are automatically converted to be nullable for
compatibility reasons.
Loading Data Programmatically
Using the data from the above example:
// Encoders for most common types are automatically provided by importing spark.implicits._importspark.implicits._valpeopleDF=spark.read.json("examples/src/main/resources/people.json")// DataFrames can be saved as Parquet files, maintaining the schema informationpeopleDF.write.parquet("people.parquet")// Read in the parquet file created above// Parquet files are self-describing so the schema is preserved// The result of loading a Parquet file is also a DataFramevalparquetFileDF=spark.read.parquet("people.parquet")// Parquet files can also be used to create a temporary view and then used in SQL statementsparquetFileDF.createOrReplaceTempView("parquetFile")valnamesDF=spark.sql("SELECT name FROM parquetFile WHERE age BETWEEN 13 AND 19")namesDF.map(attributes=>"Name: "+attributes(0)).show()// +------------+// | value|// +------------+// |Name: Justin|// +------------+
Find full example code at "examples/src/main/scala/org/apache/spark/examples/sql/SQLDataSourceExample.scala" in the Spark repo.
importorg.apache.spark.api.java.function.MapFunction;importorg.apache.spark.sql.Encoders;importorg.apache.spark.sql.Dataset;importorg.apache.spark.sql.Row;Dataset<Row>peopleDF=spark.read().json("examples/src/main/resources/people.json");// DataFrames can be saved as Parquet files, maintaining the schema informationpeopleDF.write().parquet("people.parquet");// Read in the Parquet file created above.// Parquet files are self-describing so the schema is preserved// The result of loading a parquet file is also a DataFrameDataset<Row>parquetFileDF=spark.read().parquet("people.parquet");// Parquet files can also be used to create a temporary view and then used in SQL statementsparquetFileDF.createOrReplaceTempView("parquetFile");Dataset<Row>namesDF=spark.sql("SELECT name FROM parquetFile WHERE age BETWEEN 13 AND 19");Dataset<String>namesDS=namesDF.map((MapFunction<Row,String>)row->"Name: "+row.getString(0),Encoders.STRING());namesDS.show();// +------------+// | value|// +------------+// |Name: Justin|// +------------+
Find full example code at "examples/src/main/java/org/apache/spark/examples/sql/JavaSQLDataSourceExample.java" in the Spark repo.
peopleDF=spark.read.json("examples/src/main/resources/people.json")# DataFrames can be saved as Parquet files, maintaining the schema information.peopleDF.write.parquet("people.parquet")# Read in the Parquet file created above.# Parquet files are self-describing so the schema is preserved.# The result of loading a parquet file is also a DataFrame.parquetFile=spark.read.parquet("people.parquet")# Parquet files can also be used to create a temporary view and then used in SQL statements.parquetFile.createOrReplaceTempView("parquetFile")teenagers=spark.sql("SELECT name FROM parquetFile WHERE age >= 13 AND age <= 19")teenagers.show()# +------+# | name|# +------+# |Justin|# +------+
Find full example code at "examples/src/main/python/sql/datasource.py" in the Spark repo.
df <- read.df("examples/src/main/resources/people.json","json")# SparkDataFrame can be saved as Parquet files, maintaining the schema information.
write.parquet(df,"people.parquet")# Read in the Parquet file created above. Parquet files are self-describing so the schema is preserved.# The result of loading a parquet file is also a DataFrame.
parquetFile <- read.parquet("people.parquet")# Parquet files can also be used to create a temporary view and then used in SQL statements.
createOrReplaceTempView(parquetFile,"parquetFile")
teenagers <- sql("SELECT name FROM parquetFile WHERE age >= 13 AND age <= 19")head(teenagers)## name## 1 Justin# We can also run custom R-UDFs on Spark DataFrames. Here we prefix all the names with "Name:"
schema <- structType(structField("name","string"))
teenNames <- dapply(df,function(p){cbind(paste("Name:", p$name))}, schema)for(teenName in collect(teenNames)$name){cat(teenName,"\n")## Name: Michael## Name: Andy## Name: Justin
Find full example code at "examples/src/main/r/RSparkSQLExample.R" in the Spark repo.
Table partitioning is a common optimization approach used in systems like Hive. In a partitioned
table, data are usually stored in different directories, with partitioning column values encoded in
the path of each partition directory. All built-in file sources (including Text/CSV/JSON/ORC/Parquet)
are able to discover and infer partitioning information automatically.
For example, we can store all our previously used
population data into a partitioned table using the following directory structure, with two extra
columns, gender and country as partitioning columns:
By passing path/to/table to either SparkSession.read.parquet or SparkSession.read.load, Spark SQL
will automatically extract the partitioning information from the paths.
Now the schema of the returned DataFrame becomes:
Notice that the data types of the partitioning columns are automatically inferred. Currently,
numeric data types, date, timestamp and string type are supported. Sometimes users may not want
to automatically infer the data types of the partitioning columns. For these use cases, the
automatic type inference can be configured by
spark.sql.sources.partitionColumnTypeInference.enabled, which is default to true. When type
inference is disabled, string type will be used for the partitioning columns.
Starting from Spark 1.6.0, partition discovery only finds partitions under the given paths
by default. For the above example, if users pass path/to/table/gender=male to either
SparkSession.read.parquet or SparkSession.read.load, gender will not be considered as a
partitioning column. If users need to specify the base path that partition discovery
should start with, they can set basePath in the data source options. For example,
when path/to/table/gender=male is the path of the data and
users set basePath to path/to/table/, gender will be a partitioning column.
Schema Merging
Like ProtocolBuffer, Avro, and Thrift, Parquet also supports schema evolution. Users can start with
a simple schema, and gradually add more columns to the schema as needed. In this way, users may end
up with multiple Parquet files with different but mutually compatible schemas. The Parquet data
source is now able to automatically detect this case and merge schemas of all these files.
Since schema merging is a relatively expensive operation, and is not a necessity in most cases, we
turned it off by default starting from 1.5.0. You may enable it by
setting data source option mergeSchema to true when reading Parquet files (as shown in the
examples below), or
setting the global SQL option spark.sql.parquet.mergeSchema to true.
// Create a simple DataFrame, store into a partition directoryvalsquaresDF=spark.sparkContext.makeRDD(1to5).map(i=>(i,i*i)).toDF("value","square")squaresDF.write.parquet("data/test_table/key=1")// Create another DataFrame in a new partition directory,// adding a new column and dropping an existing columnvalcubesDF=spark.sparkContext.makeRDD(6to10).map(i=>(i,i*i*i)).toDF("value","cube")cubesDF.write.parquet("data/test_table/key=2")// Read the partitioned tablevalmergedDF=spark.read.option("mergeSchema","true").parquet("data/test_table")mergedDF.printSchema()// The final schema consists of all 3 columns in the Parquet files together// with the partitioning column appeared in the partition directory paths// root// |-- value: int (nullable = true)// |-- square: int (nullable = true)// |-- cube: int (nullable = true)// |-- key: int (nullable = true)
Find full example code at "examples/src/main/scala/org/apache/spark/examples/sql/SQLDataSourceExample.scala" in the Spark repo.
importjava.io.Serializable;importjava.util.ArrayList;importjava.util.Arrays;importjava.util.List;importorg.apache.spark.sql.Dataset;importorg.apache.spark.sql.Row;publicstaticclassSquareimplementsSerializable{privateintvalue;privateintsquare;// Getters and setters...publicstaticclassCubeimplementsSerializable{privateintvalue;privateintcube;// Getters and setters...List<Square>squares=newArrayList<>();for(intvalue=1;value<=5;value++){Squaresquare=newSquare();square.setValue(value);square.setSquare(value*value);squares.add(square);// Create a simple DataFrame, store into a partition directoryDataset<Row>squaresDF=spark.createDataFrame(squares,Square.class);squaresDF.write().parquet("data/test_table/key=1");List<Cube>cubes=newArrayList<>();for(intvalue=6;value<=10;value++){Cubecube=newCube();cube.setValue(value);cube.setCube(value*value*value);cubes.add(cube);// Create another DataFrame in a new partition directory,// adding a new column and dropping an existing columnDataset<Row>cubesDF=spark.createDataFrame(cubes,Cube.class);cubesDF.write().parquet("data/test_table/key=2");// Read the partitioned tableDataset<Row>mergedDF=spark.read().option("mergeSchema",true).parquet("data/test_table");mergedDF.printSchema();// The final schema consists of all 3 columns in the Parquet files together// with the partitioning column appeared in the partition directory paths// root// |-- value: int (nullable = true)// |-- square: int (nullable = true)// |-- cube: int (nullable = true)// |-- key: int (nullable = true)
Find full example code at "examples/src/main/java/org/apache/spark/examples/sql/JavaSQLDataSourceExample.java" in the Spark repo.
# spark is from the previous example.# Create a simple DataFrame, stored into a partition directorysc=spark.sparkContextsquaresDF=spark.createDataFrame(sc.parallelize(range(1,6)).map(lambdai:Row(single=i,double=i**2)))squaresDF.write.parquet("data/test_table/key=1")# Create another DataFrame in a new partition directory,# adding a new column and dropping an existing columncubesDF=spark.createDataFrame(sc.parallelize(range(6,11)).map(lambdai:Row(single=i,triple=i**3)))cubesDF.write.parquet("data/test_table/key=2")# Read the partitioned tablemergedDF=spark.read.option("mergeSchema","true").parquet("data/test_table")mergedDF.printSchema()# The final schema consists of all 3 columns in the Parquet files together# with the partitioning column appeared in the partition directory paths.# root# |-- double: long (nullable = true)# |-- single: long (nullable = true)# |-- triple: long (nullable = true)# |-- key: integer (nullable = true)
Find full example code at "examples/src/main/python/sql/datasource.py" in the Spark repo.
df1 <- createDataFrame(data.frame(single=c(12,29),double=c(19,23)))
df2 <- createDataFrame(data.frame(double=c(19,23), triple=c(23,18)))# Create a simple DataFrame, stored into a partition directory
write.df(df1,"data/test_table/key=1","parquet","overwrite")# Create another DataFrame in a new partition directory,# adding a new column and dropping an existing column
write.df(df2,"data/test_table/key=2","parquet","overwrite")# Read the partitioned table
df3 <- read.df("data/test_table","parquet", mergeSchema ="true")
printSchema(df3)# The final schema consists of all 3 columns in the Parquet files together# with the partitioning column appeared in the partition directory paths## root## |-- single: double (nullable = true)## |-- double: double (nullable = true)## |-- triple: double (nullable = true)
## |-- key: integer (nullable = true)
Find full example code at "examples/src/main/r/RSparkSQLExample.R" in the Spark repo.
Hive metastore Parquet table conversion
When reading from and writing to Hive metastore Parquet tables, Spark SQL will try to use its own
Parquet support instead of Hive SerDe for better performance. This behavior is controlled by the
spark.sql.hive.convertMetastoreParquet configuration, and is turned on by default.
Hive/Parquet Schema Reconciliation
There are two key differences between Hive and Parquet from the perspective of table schema
processing.
Hive is case insensitive, while Parquet is not
Hive considers all columns nullable, while nullability in Parquet is significant
Due to this reason, we must reconcile Hive metastore schema with Parquet schema when converting a
Hive metastore Parquet table to a Spark SQL Parquet table. The reconciliation rules are:
Fields that have the same name in both schema must have the same data type regardless of
nullability. The reconciled field should have the data type of the Parquet side, so that
nullability is respected.
The reconciled schema contains exactly those fields defined in Hive metastore schema.
Any fields that only appear in the Parquet schema are dropped in the reconciled schema.
Any fields that only appear in the Hive metastore schema are added as nullable field in the
reconciled schema.
Metadata Refreshing
Spark SQL caches Parquet metadata for better performance. When Hive metastore Parquet table
conversion is enabled, metadata of those converted tables are also cached. If these tables are
updated by Hive or other external tools, you need to refresh them manually to ensure consistent
metadata.
Configuration
Configuration of Parquet can be done using the setConf method on SparkSession or by running
SET key=value commands using SQL.
Property NameDefaultMeaning
spark.sql.parquet.binaryAsString
false
Some other Parquet-producing systems, in particular Impala, Hive, and older versions of Spark SQL, do
not differentiate between binary data and strings when writing out the Parquet schema. This
flag tells Spark SQL to interpret binary data as a string to provide compatibility with these systems.
spark.sql.parquet.int96AsTimestamp
Some Parquet-producing systems, in particular Impala and Hive, store Timestamp into INT96. This
flag tells Spark SQL to interpret INT96 data as a timestamp to provide compatibility with these systems.
spark.sql.parquet.compression.codec
snappy
Sets the compression codec used when writing Parquet files. If either `compression` or
`parquet.compression` is specified in the table-specific options/properties, the precedence would be
`compression`, `parquet.compression`, `spark.sql.parquet.compression.codec`. Acceptable values include:
none, uncompressed, snappy, gzip, lzo.
spark.sql.parquet.filterPushdown
Enables Parquet filter push-down optimization when set to true.
spark.sql.hive.convertMetastoreParquet
When set to false, Spark SQL will use the Hive SerDe for parquet tables instead of the built in
support.
spark.sql.parquet.mergeSchema
false
When true, the Parquet data source merges schemas collected from all data files, otherwise the
schema is picked from the summary file or a random data file if no summary file is available.
When true, enable the metadata-only query optimization that use the table's metadata to
produce the partition columns instead of table scans. It applies when all the columns scanned
are partition columns and the query has an aggregate operator that satisfies distinct
semantics.
ORC Files
Since Spark 2.3, Spark supports a vectorized ORC reader with a new ORC file format for ORC files.
To do that, the following configurations are newly added. The vectorized reader is used for the
native ORC tables (e.g., the ones created using the clause USING ORC) when spark.sql.orc.impl
is set to native and spark.sql.orc.enableVectorizedReader is set to true. For the Hive ORC
serde tables (e.g., the ones created using the clause USING HIVE OPTIONS (fileFormat 'ORC')),
the vectorized reader is used when spark.sql.hive.convertMetastoreOrc is also set to true.
Property NameDefaultMeaningspark.sql.orc.impl
The name of ORC implementation. It can be one of native and hive. native means the native ORC support that is built on Apache ORC 1.4.1. `hive` means the ORC library in Hive 1.2.1.
spark.sql.orc.enableVectorizedReader
Enables vectorized orc decoding in native implementation. If false, a new non-vectorized ORC reader is used in native implementation. For hive implementation, this is ignored.
JSON Datasets
Spark SQL can automatically infer the schema of a JSON dataset and load it as a Dataset[Row].
This conversion can be done using SparkSession.read.json() on either a Dataset[String],
or a JSON file.
Note that the file that is offered as a json file is not a typical JSON file. Each
line must contain a separate, self-contained valid JSON object. For more information, please see
JSON Lines text format, also called newline-delimited JSON.
For a regular multi-line JSON file, set the multiLine option to true.
// Primitive types (Int, String, etc) and Product types (case classes) encoders are// supported by importing this when creating a Dataset.importspark.implicits._// A JSON dataset is pointed to by path.// The path can be either a single text file or a directory storing text filesvalpath="examples/src/main/resources/people.json"valpeopleDF=spark.read.json(path)// The inferred schema can be visualized using the printSchema() methodpeopleDF.printSchema()// root// |-- age: long (nullable = true)// |-- name: string (nullable = true)// Creates a temporary view using the DataFramepeopleDF.createOrReplaceTempView("people")// SQL statements can be run by using the sql methods provided by sparkvalteenagerNamesDF=spark.sql("SELECT name FROM people WHERE age BETWEEN 13 AND 19")teenagerNamesDF.show()// +------+// | name|// +------+// |Justin|// +------+// Alternatively, a DataFrame can be created for a JSON dataset represented by// a Dataset[String] storing one JSON object per stringvalotherPeopleDataset=spark.createDataset("""{"name":"Yin","address":{"city":"Columbus","state":"Ohio"}}"""::Nil)valotherPeople=spark.read.json(otherPeopleDataset)otherPeople.show()// +---------------+----+// | address|name|// +---------------+----+// |[Columbus,Ohio]| Yin|// +---------------+----+
Find full example code at "examples/src/main/scala/org/apache/spark/examples/sql/SQLDataSourceExample.scala" in the Spark repo.
Spark SQL can automatically infer the schema of a JSON dataset and load it as a Dataset<Row>.
This conversion can be done using SparkSession.read().json() on either a Dataset<String>,
or a JSON file.
Note that the file that is offered as a json file is not a typical JSON file. Each
line must contain a separate, self-contained valid JSON object. For more information, please see
JSON Lines text format, also called newline-delimited JSON.
For a regular multi-line JSON file, set the multiLine option to true.
importorg.apache.spark.sql.Dataset;importorg.apache.spark.sql.Row;// A JSON dataset is pointed to by path.// The path can be either a single text file or a directory storing text filesDataset<Row>people=spark.read().json("examples/src/main/resources/people.json");// The inferred schema can be visualized using the printSchema() methodpeople.printSchema();// root// |-- age: long (nullable = true)// |-- name: string (nullable = true)// Creates a temporary view using the DataFramepeople.createOrReplaceTempView("people");// SQL statements can be run by using the sql methods provided by sparkDataset<Row>namesDF=spark.sql("SELECT name FROM people WHERE age BETWEEN 13 AND 19");namesDF.show();// +------+// | name|// +------+// |Justin|// +------+// Alternatively, a DataFrame can be created for a JSON dataset represented by// a Dataset<String> storing one JSON object per string.List<String>jsonData=Arrays.asList("{\"name\":\"Yin\",\"address\":{\"city\":\"Columbus\",\"state\":\"Ohio\"}}");Dataset<String>anotherPeopleDataset=spark.createDataset(jsonData,Encoders.STRING());Dataset<Row>anotherPeople=spark.read().json(anotherPeopleDataset);anotherPeople.show();// +---------------+----+// | address|name|// +---------------+----+// |[Columbus,Ohio]| Yin|// +---------------+----+
Find full example code at "examples/src/main/java/org/apache/spark/examples/sql/JavaSQLDataSourceExample.java" in the Spark repo.
Spark SQL can automatically infer the schema of a JSON dataset and load it as a DataFrame.
This conversion can be done using SparkSession.read.json on a JSON file.
Note that the file that is offered as a json file is not a typical JSON file. Each
line must contain a separate, self-contained valid JSON object. For more information, please see
JSON Lines text format, also called newline-delimited JSON.
For a regular multi-line JSON file, set the multiLine parameter to True.
# spark is from the previous example.sc=spark.sparkContext# A JSON dataset is pointed to by path.# The path can be either a single text file or a directory storing text filespath="examples/src/main/resources/people.json"peopleDF=spark.read.json(path)# The inferred schema can be visualized using the printSchema() methodpeopleDF.printSchema()# root# |-- age: long (nullable = true)# |-- name: string (nullable = true)# Creates a temporary view using the DataFramepeopleDF.createOrReplaceTempView("people")# SQL statements can be run by using the sql methods provided by sparkteenagerNamesDF=spark.sql("SELECT name FROM people WHERE age BETWEEN 13 AND 19")teenagerNamesDF.show()# +------+# | name|# +------+# |Justin|# +------+# Alternatively, a DataFrame can be created for a JSON dataset represented by# an RDD[String] storing one JSON object per stringjsonStrings=['{"name":"Yin","address":{"city":"Columbus","state":"Ohio"}}']otherPeopleRDD=sc.parallelize(jsonStrings)otherPeople=spark.read.json(otherPeopleRDD)otherPeople.show()# +---------------+----+# | address|name|# +---------------+----+# |[Columbus,Ohio]| Yin|# +---------------+----+
Find full example code at "examples/src/main/python/sql/datasource.py" in the Spark repo.
Spark SQL can automatically infer the schema of a JSON dataset and load it as a DataFrame. using
the read.json() function, which loads data from a directory of JSON files where each line of the
files is a JSON object.
Note that the file that is offered as a json file is not a typical JSON file. Each
line must contain a separate, self-contained valid JSON object. For more information, please see
JSON Lines text format, also called newline-delimited JSON.
For a regular multi-line JSON file, set a named parameter multiLine to TRUE.
# A JSON dataset is pointed to by path.# The path can be either a single text file or a directory storing text files.
path <-"examples/src/main/resources/people.json"# Create a DataFrame from the file(s) pointed to by path
people <- read.json(path)# The inferred schema can be visualized using the printSchema() method.
printSchema(people)## root## |-- age: long (nullable = true)## |-- name: string (nullable = true)# Register this DataFrame as a table.
createOrReplaceTempView(people,"people")# SQL statements can be run by using the sql methods.
teenagers <- sql("SELECT name FROM people WHERE age >= 13 AND age <= 19")head(teenagers)## name## 1 Justin
Find full example code at "examples/src/main/r/RSparkSQLExample.R" in the Spark repo.
Spark SQL also supports reading and writing data stored in Apache Hive.
However, since Hive has a large number of dependencies, these dependencies are not included in the
default Spark distribution. If Hive dependencies can be found on the classpath, Spark will load them
automatically. Note that these Hive dependencies must also be present on all of the worker nodes, as
they will need access to the Hive serialization and deserialization libraries (SerDes) in order to
access data stored in Hive.
Configuration of Hive is done by placing your hive-site.xml, core-site.xml (for security configuration),
and hdfs-site.xml (for HDFS configuration) file in conf/.
When working with Hive, one must instantiate SparkSession with Hive support, including
connectivity to a persistent Hive metastore, support for Hive serdes, and Hive user-defined functions.
Users who do not have an existing Hive deployment can still enable Hive support. When not configured
by the hive-site.xml, the context automatically creates metastore_db in the current directory and
creates a directory configured by spark.sql.warehouse.dir, which defaults to the directory
spark-warehouse in the current directory that the Spark application is started. Note that
the hive.metastore.warehouse.dir property in hive-site.xml is deprecated since Spark 2.0.0.
Instead, use spark.sql.warehouse.dir to specify the default location of database in warehouse.
You may need to grant write privilege to the user who starts the Spark application.
importorg.apache.spark.sql.{Row,SaveMode,SparkSession}caseclassRecord(key:Int,value:String)// warehouseLocation points to the default location for managed databases and tablesvalwarehouseLocation=newFile("spark-warehouse").getAbsolutePathvalspark=SparkSession.builder().appName("Spark Hive Example").config("spark.sql.warehouse.dir",warehouseLocation).enableHiveSupport().getOrCreate()importspark.implicits._importspark.sqlsql("CREATE TABLE IF NOT EXISTS src (key INT, value STRING) USING hive")sql("LOAD DATA LOCAL INPATH 'examples/src/main/resources/kv1.txt' INTO TABLE src")// Queries are expressed in HiveQLsql("SELECT * FROM src").show()// +---+-------+// |key| value|// +---+-------+// |238|val_238|// | 86| val_86|// |311|val_311|// ...// Aggregation queries are also supported.sql("SELECT COUNT(*) FROM src").show()// +--------+// |count(1)|// +--------+// | 500 |// +--------+// The results of SQL queries are themselves DataFrames and support all normal functions.valsqlDF=sql("SELECT key, value FROM src WHERE key < 10 ORDER BY key")// The items in DataFrames are of type Row, which allows you to access each column by ordinal.valstringsDS=sqlDF.map{caseRow(key:Int,value:String)=>s"Key: $key, Value: $value"stringsDS.show()// +--------------------+// | value|// +--------------------+// |Key: 0, Value: val_0|// |Key: 0, Value: val_0|// |Key: 0, Value: val_0|// ...// You can also use DataFrames to create temporary views within a SparkSession.valrecordsDF=spark.createDataFrame((1to100).map(i=>Record(i,s"val_$i")))recordsDF.createOrReplaceTempView("records")// Queries can then join DataFrame data with data stored in Hive.sql("SELECT * FROM records r JOIN src s ON r.key = s.key").show()// +---+------+---+------+// |key| value|key| value|// +---+------+---+------+// | 2| val_2| 2| val_2|// | 4| val_4| 4| val_4|// | 5| val_5| 5| val_5|// ...// Create a Hive managed Parquet table, with HQL syntax instead of the Spark SQL native syntax// `USING hive`sql("CREATE TABLE hive_records(key int, value string) STORED AS PARQUET")// Save DataFrame to the Hive managed tablevaldf=spark.table("src")df.write.mode(SaveMode.Overwrite).saveAsTable("hive_records")// After insertion, the Hive managed table has data nowsql("SELECT * FROM hive_records").show()// +---+-------+// |key| value|// +---+-------+// |238|val_238|// | 86| val_86|// |311|val_311|// ...// Prepare a Parquet data directoryvaldataDir="/tmp/parquet_data"spark.range(10).write.parquet(dataDir)// Create a Hive external Parquet tablesql(s"CREATE EXTERNAL TABLE hive_ints(key int) STORED AS PARQUET LOCATION '$dataDir'")// The Hive external table should already have datasql("SELECT * FROM hive_ints").show()// +---+// |key|// +---+// | 0|// | 1|// | 2|// ...// Turn on flag for Hive Dynamic Partitioningspark.sqlContext.setConf("hive.exec.dynamic.partition","true")spark.sqlContext.setConf("hive.exec.dynamic.partition.mode","nonstrict")// Create a Hive partitioned table using DataFrame APIdf.write.partitionBy("key").format("hive").saveAsTable("hive_part_tbl")// Partitioned column `key` will be moved to the end of the schema.sql("SELECT * FROM hive_part_tbl").show()// +-------+---+// | value|key|// +-------+---+// |val_238|238|// | val_86| 86|// |val_311|311|// ...spark.stop()
Find full example code at "examples/src/main/scala/org/apache/spark/examples/sql/hive/SparkHiveExample.scala" in the Spark repo.
importjava.io.File;importjava.io.Serializable;importjava.util.ArrayList;importjava.util.List;importorg.apache.spark.api.java.function.MapFunction;importorg.apache.spark.sql.Dataset;importorg.apache.spark.sql.Encoders;importorg.apache.spark.sql.Row;importorg.apache.spark.sql.SparkSession;publicstaticclassRecordimplementsSerializable{privateintkey;privateStringvalue;publicintgetKey(){returnkey;publicvoidsetKey(intkey){this.key=key;publicStringgetValue(){returnvalue;publicvoidsetValue(Stringvalue){this.value=value;// warehouseLocation points to the default location for managed databases and tablesStringwarehouseLocation=newFile("spark-warehouse").getAbsolutePath();SparkSessionspark=SparkSession.builder().appName("Java Spark Hive Example").config("spark.sql.warehouse.dir",warehouseLocation).enableHiveSupport
().getOrCreate();spark.sql("CREATE TABLE IF NOT EXISTS src (key INT, value STRING) USING hive");spark.sql("LOAD DATA LOCAL INPATH 'examples/src/main/resources/kv1.txt' INTO TABLE src");// Queries are expressed in HiveQLspark.sql("SELECT * FROM src").show();// +---+-------+// |key| value|// +---+-------+// |238|val_238|// | 86| val_86|// |311|val_311|// ...// Aggregation queries are also supported.spark.sql("SELECT COUNT(*) FROM src").show();// +--------+// |count(1)|// +--------+// | 500 |// +--------+// The results of SQL queries are themselves DataFrames and support all normal functions.Dataset<Row>sqlDF=spark.sql("SELECT key, value FROM src WHERE key < 10 ORDER BY key");// The items in DataFrames are of type Row, which lets you to access each column by ordinal.Dataset<String>stringsDS=sqlDF.map((MapFunction<Row,String>)row->"Key: "+row.get(0)+", Value: "+row.get(1),Encoders.STRING());stringsDS.show();// +--------------------+// | value|// +--------------------+// |Key: 0, Value: val_0|// |Key: 0, Value: val_0|// |Key: 0, Value: val_0|// ...// You can also use DataFrames to create temporary views within a SparkSession.List<Record>records=newArrayList<>();for(intkey=1;key<100;key++){Recordrecord=newRecord();record.setKey(key);record.setValue("val_"+key);records.add(record);Dataset<Row>recordsDF=spark.createDataFrame(records,Record.class);recordsDF.createOrReplaceTempView("records");// Queries can then join DataFrames data with data stored in Hive.spark.sql("SELECT * FROM records r JOIN src s ON r.key = s.key").show();// +---+------+---+------+// |key| value|key| value|// +---+------+---+------+// | 2| val_2| 2| val_2|// | 2| val_2| 2| val_2|// | 4| val_4| 4| val_4|// ...
Find full example code at "examples/src/main/java/org/apache/spark/examples/sql/hive/JavaSparkHiveExample.java" in the Spark repo.
fromos.pathimportexpanduser,join,abspathfrompyspark.sqlimportSparkSessionfrompyspark.sqlimportRow# warehouse_location points to the default location for managed databases and tableswarehouse_location=abspath('spark-warehouse')spark=SparkSession \
.builder \
.appName("Python Spark SQL Hive integration example") \
.config("spark.sql.warehouse.dir",warehouse_location) \
.enableHiveSupport() \
.getOrCreate()# spark is an existing SparkSessionspark.sql("CREATE TABLE IF NOT EXISTS src (key INT, value STRING) USING hive")spark.sql("LOAD DATA LOCAL INPATH 'examples/src/main/resources/kv1.txt' INTO TABLE src")# Queries are expressed in HiveQLspark.sql("SELECT * FROM src").show()# +---+-------+# |key| value|# +---+-------+# |238|val_238|# | 86| val_86|# |311|val_311|# ...# Aggregation queries are also supported.spark.sql("SELECT COUNT(*) FROM src").show()# +--------+# |count(1)|# +--------+# | 500 |# +--------+# The results of SQL queries are themselves DataFrames and support all normal functions.sqlDF=spark.sql("SELECT key, value FROM src WHERE key < 10 ORDER BY key")# The items in DataFrames are of type Row, which allows you to access each column by ordinal.stringsDS=sqlDF.rdd.map(lambdarow:"Key: %d, Value: %s"%(row.key,row.value))forrecordinstringsDS.collect():print(record)# Key: 0, Value: val_0# Key: 0, Value: val_0# Key: 0, Value: val_0# ...# You can also use DataFrames to create temporary views within a SparkSession.Record=Row("key","value")recordsDF=spark.createDataFrame([Record(i,"val_"+str(i))foriinrange(1,101)])recordsDF.createOrReplaceTempView("records")# Queries can then join DataFrame data with data stored in Hive.spark.sql("SELECT * FROM records r JOIN src s ON r.key = s.key").show()# +---+------+---+------+# |key| value|key| value|# +---+------+---+------+# | 2| val_2| 2| val_2|# | 4| val_4| 4| val_4|# | 5| val_5| 5| val_5|# ...
Find full example code at "examples/src/main/python/sql/hive.py" in the Spark repo.
When working with Hive one must instantiate SparkSession with Hive support. This
adds support for finding tables in the MetaStore and writing queries using HiveQL.
# enableHiveSupport defaults to TRUE
sparkR.session(enableHiveSupport =TRUE)
sql("CREATE TABLE IF NOT EXISTS src (key INT, value STRING) USING hive")
sql("LOAD DATA LOCAL INPATH 'examples/src/main/resources/kv1.txt' INTO TABLE src")# Queries can be expressed in HiveQL.
results <- collect(sql("FROM src SELECT key, value"))
Find full example code at "examples/src/main/r/RSparkSQLExample.R" in the Spark repo.
Specifying storage format for Hive tables
When you create a Hive table, you need to define how this table should read/write data from/to file system,
i.e. the “input format” and “output format”. You also need to define how this table should deserialize the data
to rows, or serialize rows to data, i.e. the “serde”. The following options can be used to specify the storage
format(“serde”, “input format”, “output format”), e.g. CREATE TABLE src(id int) USING hive OPTIONS(fileFormat 'parquet').
By default, we will read the table files as plain text. Note that, Hive storage handler is not supported yet when
creating table, you can create a table using storage handler at Hive side, and use Spark SQL to read it.
Property NameMeaning
fileFormat
A fileFormat is kind of a package of storage format specifications, including "serde", "input format" and
"output format". Currently we support 6 fileFormats: 'sequencefile', 'rcfile', 'orc', 'parquet', 'textfile' and 'avro'.
inputFormat, outputFormat
These 2 options specify the name of a corresponding `InputFormat` and `OutputFormat` class as a string literal,
e.g. `org.apache.hadoop.hive.ql.io.orc.OrcInputFormat`. These 2 options must be appeared in pair, and you can not
specify them if you already specified the `fileFormat` option.
serde
This option specifies the name of a serde class. When the `fileFormat` option is specified, do not specify this option
if the given `fileFormat` already include the information of serde. Currently "sequencefile", "textfile" and "rcfile"
don't include the serde information and you can use this option with these 3 fileFormats.
All other properties defined with OPTIONS will be regarded as Hive serde properties.
Interacting with Different Versions of Hive Metastore
One of the most important pieces of Spark SQL’s Hive support is interaction with Hive metastore,
which enables Spark SQL to access metadata of Hive tables. Starting from Spark 1.4.0, a single binary
build of Spark SQL can be used to query different versions of Hive metastores, using the configuration described below.
Note that independent of the version of Hive that is being used to talk to the metastore, internally Spark SQL
will compile against Hive 1.2.1 and use those classes for internal execution (serdes, UDFs, UDAFs, etc).
The following options can be used to configure the version of Hive that is used to retrieve metadata:
Property NameDefaultMeaning
spark.sql.hive.metastore.version1.2.1
Version of the Hive metastore. Available
options are 0.12.0 through 1.2.1.
spark.sql.hive.metastore.jarsbuiltin
Location of the jars that should be used to instantiate the HiveMetastoreClient. This
property can be one of three options:
builtin
Use Hive 1.2.1, which is bundled with the Spark assembly when -Phive is
enabled. When this option is chosen, spark.sql.hive.metastore.version must be
either 1.2.1 or not defined.
maven
Use Hive jars of specified version downloaded from Maven repositories. This configuration
is not generally recommended for production deployments.
A classpath in the standard format for the JVM. This classpath must include all of Hive
and its dependencies, including the correct version of Hadoop. These jars only need to be
present on the driver, but if you are running in yarn cluster mode then you must ensure
they are packaged with your application.
spark.sql.hive.metastore.sharedPrefixescom.mysql.jdbc, org.postgresql, com.microsoft.sqlserver, oracle.jdbc
A comma separated list of class prefixes that should be loaded using the classloader that is
shared between Spark SQL and a specific version of Hive. An example of classes that should
be shared is JDBC drivers that are needed to talk to the metastore. Other classes that need
to be shared are those that interact with classes that are already shared. For example,
custom appenders that are used by log4j.
A comma separated list of class prefixes that should explicitly be reloaded for each version
of Hive that Spark SQL is communicating with. For example, Hive UDFs that are declared in a
prefix that typically would be shared (i.e. org.apache.spark.*).
JDBC To Other Databases
Spark SQL also includes a data source that can read data from other databases using JDBC. This
functionality should be preferred over using JdbcRDD.
This is because the results are returned
as a DataFrame and they can easily be processed in Spark SQL or joined with other data sources.
The JDBC data source is also easier to use from Java or Python as it does not require the user to
provide a ClassTag.
(Note that this is different than the Spark SQL JDBC server, which allows other applications to
run queries using Spark SQL).
To get started you will need to include the JDBC driver for your particular database on the
spark classpath. For example, to connect to postgres from the Spark Shell you would run the
following command:
Tables from the remote database can be loaded as a DataFrame or Spark SQL temporary view using
the Data Sources API. Users can specify the JDBC connection properties in the data source options.
user and password are normally provided as connection properties for
logging into the data sources. In addition to the connection properties, Spark also supports
the following case-insensitive options:
Property NameMeaning
The JDBC URL to connect to. The source-specific connection properties may be specified in the URL. e.g., jdbc:postgresql://localhost/test?user=fred&password=secretdbtable
The JDBC table that should be read. Note that anything that is valid in a FROM clause of
a SQL query can be used. For example, instead of a full table you could also use a
subquery in parentheses.
partitionColumn, lowerBound, upperBound
These options must all be specified if any of them is specified. In addition,
numPartitions must be specified. They describe how to partition the table when
reading in parallel from multiple workers.
partitionColumn must be a numeric column from the table in question. Notice
that lowerBound and upperBound are just used to decide the
partition stride, not for filtering the rows in table. So all rows in the table will be
partitioned and returned. This option applies only to reading.
numPartitions
The maximum number of partitions that can be used for parallelism in table reading and
writing. This also determines the maximum number of concurrent JDBC connections.
If the number of partitions to write exceeds this limit, we decrease it to this limit by
calling coalesce(numPartitions) before writing.
isolationLevel
The transaction isolation level, which applies to current connection. It can be one of NONE, READ_COMMITTED, READ_UNCOMMITTED, REPEATABLE_READ, or SERIALIZABLE, corresponding to standard transaction isolation levels defined by JDBC's Connection object, with default of READ_UNCOMMITTED. This option applies only to writing. Please refer the documentation in java.sql.Connection.
sessionInitStatement
After each database session is opened to the remote DB and before starting to read data, this option executes a custom SQL statement (or a PL/SQL block). Use this to implement session initialization code. Example: option("sessionInitStatement", """BEGIN execute immediate 'alter session set "_serial_direct_read"=true'; END;""")truncate
This is a JDBC writer related option. When SaveMode.Overwrite is enabled, this option causes Spark to truncate an existing table instead of dropping and recreating it. This can be more efficient, and prevents the table metadata (e.g., indices) from being removed. However, it will not work in some cases, such as when the new data has a different schema. It defaults to false. This option applies only to writing.
createTableColumnTypes
The database column data types to use instead of the defaults, when creating the table. Data type information should be specified in the same format as CREATE TABLE columns syntax (e.g: "name CHAR(64), comments VARCHAR(1024)"). The specified types should be valid spark sql data types. This option applies only to writing.
customSchema
The custom schema to use for reading data from JDBC connectors. For example, "id DECIMAL(38, 0), name STRING". You can also specify partial fields, and the others use the default type mapping. For example, "id DECIMAL(38, 0)". The column names should be identical to the corresponding column names of JDBC table. Users can specify the corresponding data types of Spark SQL instead of using the defaults. This option applies only to reading.
// Note: JDBC loading and saving can be achieved via either the load/save or jdbc methods// Loading data from a JDBC sourcevaljdbcDF=spark.read.format("jdbc").option("url","jdbc:postgresql:dbserver").option("dbtable","schema.tablename").option("user","username").option("password","password").load()valconnectionProperties=newProperties()connectionProperties.put("user","username")connectionProperties.put("password","password")valjdbcDF2=spark.read.jdbc("jdbc:postgresql:dbserver","schema.tablename",connectionProperties)// Specifying the custom data types of the read schemaconnectionProperties.put("customSchema","id DECIMAL(38, 0), name STRING")valjdbcDF3=spark.read.jdbc("jdbc:postgresql:dbserver","schema.tablename",connectionProperties)// Saving data to a JDBC sourcejdbcDF.write.format("jdbc").option("url","jdbc:postgresql:dbserver").option("dbtable","schema.tablename").option("user","username").option("password","password").save()jdbcDF2.write.jdbc("jdbc:postgresql:dbserver","schema.tablename",connectionProperties)// Specifying create table column data types on writejdbcDF.write.option("createTableColumnTypes","name CHAR(64), comments VARCHAR(1024)").jdbc("jdbc:postgresql:dbserver","schema.tablename",connectionProperties)
Find full example code at "examples/src/main/scala/org/apache/spark/examples/sql/SQLDataSourceExample.scala" in the Spark repo.
// Note: JDBC loading and saving can be achieved via either the load/save or jdbc methods// Loading data from a JDBC sourceDataset<Row>jdbcDF=spark.read().format("jdbc").option("url","jdbc:postgresql:dbserver").option("dbtable","schema.tablename").option("user","username").option("password","password").load();PropertiesconnectionProperties=newProperties();connectionProperties.put("user","username");connectionProperties.put("password","password");Dataset<Row>jdbcDF2=spark.read().jdbc("jdbc:postgresql:dbserver","schema.tablename",connectionProperties);// Saving data to a JDBC sourcejdbcDF.write().format("jdbc").option("url","jdbc:postgresql:dbserver").option("dbtable","schema.tablename").option("user","username").option("password","password").save();jdbcDF2.write().jdbc("jdbc:postgresql:dbserver","schema.tablename",connectionProperties);// Specifying create table column data types on writejdbcDF.write().option("createTableColumnTypes","name CHAR(64), comments VARCHAR(1024)").jdbc("jdbc:postgresql:dbserver","schema.tablename",connectionProperties);
Find full example code at "examples/src/main/java/org/apache/spark/examples/sql/JavaSQLDataSourceExample.java" in the Spark repo.
# Note: JDBC loading and saving can be achieved via either the load/save or jdbc methods# Loading data from a JDBC sourcejdbcDF=spark.read \
.format("jdbc") \
.option("url","jdbc:postgresql:dbserver") \
.option("dbtable","schema.tablename") \
.option("user","username") \
.option("password","password") \
.load()jdbcDF2=spark.read \
.jdbc("jdbc:postgresql:dbserver","schema.tablename",properties={"user":"username","password":"password"})# Specifying dataframe column data types on readjdbcDF3=spark.read \
.format("jdbc") \
.option("url","jdbc:postgresql:dbserver") \
.option("dbtable","schema.tablename") \
.option("user","username") \
.option("password","password") \
.option("customSchema","id DECIMAL(38, 0), name STRING") \
.load()# Saving data to a JDBC sourcejdbcDF.write \
.format("jdbc") \
.option("url","jdbc:postgresql:dbserver") \
.option("dbtable","schema.tablename") \
.option("user","username") \
.option("password","password") \
.save()jdbcDF2.write \
.jdbc("jdbc:postgresql:dbserver","schema.tablename",properties={"user":"username","password":"password"})# Specifying create table column data types on writejdbcDF.write \
.option("createTableColumnTypes","name CHAR(64), comments VARCHAR(1024)") \
.jdbc("jdbc:postgresql:dbserver","schema.tablename",properties={"user":"username","password":"password"})
Find full example code at "examples/src/main/python/sql/datasource.py" in the Spark repo.
# Loading data from a JDBC source
df <- read.jdbc("jdbc:postgresql:dbserver","schema.tablename", user ="username", password ="password")# Saving data to a JDBC source
write.jdbc(df,"jdbc:postgresql:dbserver","schema.tablename", user ="username", password ="password")
Find full example code at "examples/src/main/r/RSparkSQLExample.R" in the Spark repo.
The JDBC driver class must be visible to the primordial class loader on the client session and on all executors. This is because Java’s DriverManager class does a security check that results in it ignoring all drivers not visible to the primordial class loader when one goes to open a connection. One convenient way to do this is to modify compute_classpath.sh on all worker nodes to include your driver JARs.
Some databases, such as H2, convert all names to upper case. You’ll need to use upper case to refer to those names in Spark SQL.
Performance Tuning
For some workloads it is possible to improve performance by either caching data in memory, or by
turning on some experimental options.
Caching Data In Memory
Spark SQL can cache tables using an in-memory columnar format by calling spark.catalog.cacheTable("tableName") or dataFrame.cache().
Then Spark SQL will scan only required columns and will automatically tune compression to minimize
memory usage and GC pressure. You can call spark.catalog.uncacheTable("tableName") to remove the table from memory.
Configuration of in-memory caching can be done using the setConf method on SparkSession or by running
SET key=value commands using SQL.
Property NameDefaultMeaning
spark.sql.inMemoryColumnarStorage.compressed
When set to true Spark SQL will automatically select a compression codec for each column based
on statistics of the data.
spark.sql.inMemoryColumnarStorage.batchSize
10000
Controls the size of batches for columnar caching. Larger batch sizes can improve memory utilization
and compression, but risk OOMs when caching data.
Other Configuration Options
The following options can also be used to tune the performance of query execution. It is possible
that these options will be deprecated in future release as more optimizations are performed automatically.
Property NameDefaultMeaning
spark.sql.files.maxPartitionBytes
134217728 (128 MB)
The maximum number of bytes to pack into a single partition when reading files.
spark.sql.files.openCostInBytes
4194304 (4 MB)
The estimated cost to open a file, measured by the number of bytes could be scanned in the same
time. This is used when putting multiple files into a partition. It is better to over estimated,
then the partitions with small files will be faster than partitions with bigger files (which is
scheduled first).
spark.sql.broadcastTimeout
Timeout in seconds for the broadcast wait time in broadcast joins
10485760 (10 MB)
Configures the maximum size in bytes for a table that will be broadcast to all worker nodes when
performing a join. By setting this value to -1 broadcasting can be disabled. Note that currently
statistics are only supported for Hive Metastore tables where the command
ANALYZE TABLE <tableName> COMPUTE STATISTICS noscan has been run.
spark.sql.shuffle.partitions
Configures the number of partitions to use when shuffling data for joins or aggregations.
Broadcast Hint for SQL Queries
The BROADCAST hint guides Spark to broadcast each specified table when joining them with another table or view.
When Spark deciding the join methods, the broadcast hash join (i.e., BHJ) is preferred,
even if the statistics is above the configuration spark.sql.autoBroadcastJoinThreshold.
When both sides of a join are specified, Spark broadcasts the one having the lower statistics.
Note Spark does not guarantee BHJ is always chosen, since not all cases (e.g. full outer join)
support BHJ. When the broadcast nested loop join is selected, we still respect the hint.
Distributed SQL Engine
Spark SQL can also act as a distributed query engine using its JDBC/ODBC or command-line interface.
In this mode, end-users or applications can interact with Spark SQL directly to run SQL queries,
without the need to write any code.
Running the Thrift JDBC/ODBC server
The Thrift JDBC/ODBC server implemented here corresponds to the HiveServer2
in Hive 1.2.1 You can test the JDBC server with the beeline script that comes with either Spark or Hive 1.2.1.
To start the JDBC/ODBC server, run the following in the Spark directory:
./sbin/start-thriftserver.sh
This script accepts all bin/spark-submit command line options, plus a --hiveconf option to
specify Hive properties. You may run ./sbin/start-thriftserver.sh --help for a complete list of
all available options. By default, the server listens on localhost:10000. You may override this
behaviour via either environment variables, i.e.:
Now you can use beeline to test the Thrift JDBC/ODBC server:
./bin/beeline
Connect to the JDBC/ODBC server in beeline with:
beeline> !connect jdbc:hive2://localhost:10000
Beeline will ask you for a username and password. In non-secure mode, simply enter the username on
your machine and a blank password. For secure mode, please follow the instructions given in the
beeline documentation.
Configuration of Hive is done by placing your hive-site.xml, core-site.xml and hdfs-site.xml files in conf/.
You may also use the beeline script that comes with Hive.
Thrift JDBC server also supports sending thrift RPC messages over HTTP transport.
Use the following setting to enable HTTP mode as system property or in hive-site.xml file in conf/:
hive.server2.transport.mode - Set this to value: http
hive.server2.thrift.http.port - HTTP port number to listen on; default is 10001
hive.server2.http.endpoint - HTTP endpoint; default is cliservice