Spark SQL and DataFrames - Spark 2.2.0 Documentation
Spark SQL and DataFrames - Spark 2.2.0 Documentation
0 Documentation
https://spark.apache.org/docs/2.2.0/sql-programming-guide.html 1/35
5/28/2019 Spark SQL and DataFrames - Spark 2.2.0 Documentation
Overview
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.
SQL
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.
https://spark.apache.org/docs/2.2.0/sql-programming-guide.html 2/35
5/28/2019 Spark SQL and DataFrames - Spark 2.2.0 Documentation
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 Rows. 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 Rows as DataFrames.
Getting Started
Starting Point: SparkSession
Scala Java Python R
The entry point into all functionality in Spark is the SparkSession class. To create a basic SparkSession, just use
SparkSession.builder():
import org.apache.spark.sql.SparkSession
Creating DataFrames
Scala Java Python R
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:
val df = spark.read.json("examples/src/main/resources/people.json")
https://spark.apache.org/docs/2.2.0/sql-programming-guide.html 3/35
5/28/2019 Spark SQL and DataFrames - Spark 2.2.0 Documentation
// +----+-------+
// |null|Michael|
// | 30| Andy|
// | 19| Justin|
// +----+-------+
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:
https://spark.apache.org/docs/2.2.0/sql-programming-guide.html 4/35
5/28/2019 Spark SQL and DataFrames - Spark 2.2.0 Documentation
// +---+----+
// | 30|Andy|
// +---+----+
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.
The sql function on a SparkSession enables applications to run SQL queries programmatically and returns the result as
a DataFrame.
https://spark.apache.org/docs/2.2.0/sql-programming-guide.html 5/35
5/28/2019 Spark SQL and DataFrames - Spark 2.2.0 Documentation
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.
Scala Java
// Note: Case classes in Scala 2.10 can support only up to 22 fields. To work around this limit,
// you can use custom classes that implement the Product interface
case class Person(name: String, age: Long)
// Encoders for most common types are automatically provided by importing spark.implicits._
https://spark.apache.org/docs/2.2.0/sql-programming-guide.html 6/35
5/28/2019 Spark SQL and DataFrames - Spark 2.2.0 Documentation
val primitiveDS = 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 name
val path = "examples/src/main/resources/people.json"
val peopleDS = spark.read.json(path).as[Person]
peopleDS.show()
// +----+-------+
// | age| name|
// +----+-------+
// |null|Michael|
// | 30| Andy|
// | 19| Justin|
// +----+-------+
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.
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.
// SQL statements can be run by using the sql methods provided by Spark
val teenagersDF = spark.sql("SELECT name, age FROM people WHERE age BETWEEN 13 AND 19")
https://spark.apache.org/docs/2.2.0/sql-programming-guide.html 7/35
5/28/2019 Spark SQL and DataFrames - Spark 2.2.0 Documentation
// or by field name
teenagersDF.map(teenager => "Name: " + teenager.getAs[String]("name")).show()
// +------------+
// | value|
// +------------+
// |Name: Justin|
// +------------+
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.
For example:
import org.apache.spark.sql.types._
// Create an RDD
val peopleRDD = spark.sparkContext.textFile("examples/src/main/resources/people.txt")
https://spark.apache.org/docs/2.2.0/sql-programming-guide.html 8/35
5/28/2019 Spark SQL and DataFrames - Spark 2.2.0 Documentation
.map(fieldName => StructField(fieldName, StringType, nullable = true))
val schema = StructType(fields)
// 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 name
results.map(attributes => "Name: " + attributes(0)).show()
// +-------------+
// | value|
// +-------------+
// |Name: Michael|
// | Name: Andy|
// | Name: Justin|
// +-------------+
Aggregations
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.
Scala Java
Users have to extend the UserDefinedAggregateFunction abstract class to implement a custom untyped aggregate
function. For example, a user-defined average can look like:
import org.apache.spark.sql.expressions.MutableAggregationBuffer
import org.apache.spark.sql.expressions.UserDefinedAggregateFunction
import org.apache.spark.sql.types._
import org.apache.spark.sql.Row
import org.apache.spark.sql.SparkSession
https://spark.apache.org/docs/2.2.0/sql-programming-guide.html 9/35
5/28/2019 Spark SQL and DataFrames - Spark 2.2.0 Documentation
// Data types of input arguments of this aggregate function
def inputSchema: StructType = StructType(StructField("inputColumn", LongType) :: Nil)
// Data types of values in the aggregation buffer
def bufferSchema: StructType = {
StructType(StructField("sum", LongType) :: StructField("count", LongType) :: Nil)
}
// The data type of the returned value
def dataType: DataType = DoubleType
// Whether this function always returns the same output on the identical input
def deterministic: 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.
def initialize(buffer: MutableAggregationBuffer): Unit = {
buffer(0) = 0L
buffer(1) = 0L
}
// Updates the given aggregation buffer `buffer` with new input data from `input`
def update(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`
def merge(buffer1: MutableAggregationBuffer, buffer2: Row): Unit = {
buffer1(0) = buffer1.getLong(0) + buffer2.getLong(0)
buffer1(1) = buffer1.getLong(1) + buffer2.getLong(1)
}
// Calculates the final result
def evaluate(buffer: Row): Double = buffer.getLong(0).toDouble / buffer.getLong(1)
}
val 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|
// +-------+------+
Scala Java
import org.apache.spark.sql.expressions.Aggregator
import org.apache.spark.sql.Encoder
import org.apache.spark.sql.Encoders
import org.apache.spark.sql.SparkSession
val ds = spark.read.json("examples/src/main/resources/employees.json").as[Employee]
ds.show()
// +-------+------+
// | name|salary|
// +-------+------+
https://spark.apache.org/docs/2.2.0/sql-programming-guide.html 11/35
5/28/2019 Spark SQL and DataFrames - Spark 2.2.0 Documentation
// |Michael| 3000|
// | Andy| 4500|
// | Justin| 3500|
// | Berta| 4000|
// +-------+------+
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.
https://spark.apache.org/docs/2.2.0/sql-programming-guide.html 12/35
5/28/2019 Spark SQL and DataFrames - Spark 2.2.0 Documentation
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.
SaveMode.ErrorIfExists "error" When saving a DataFrame to a data source, if data already exists, an
(default) (default) 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.
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.
https://spark.apache.org/docs/2.2.0/sql-programming-guide.html 13/35
5/28/2019 Spark SQL and DataFrames - Spark 2.2.0 Documentation
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.
peopleDF.write.bucketBy(42, "name").sortBy("age").saveAsTable("people_bucketed")
usersDF.write.partitionBy("favorite_color").format("parquet").save("namesPartByColor.parquet")
peopleDF
.write
.partitionBy("favorite_color")
.bucketBy(42, "name")
.saveAsTable("people_partitioned_bucketed")
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.
https://spark.apache.org/docs/2.2.0/sql-programming-guide.html 14/35
5/28/2019 Spark SQL and DataFrames - Spark 2.2.0 Documentation
// Encoders for most common types are automatically provided by importing spark.implicits._
import spark.implicits._
// Parquet files can also be used to create a temporary view and then used in SQL statements
parquetFileDF.createOrReplaceTempView("parquetFile")
val namesDF = spark.sql("SELECT name FROM parquetFile WHERE age BETWEEN 13 AND 19")
namesDF.map(attributes => "Name: " + attributes(0)).show()
// +------------+
// | value|
// +------------+
// |Name: Justin|
// +------------+
Partition Discovery
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. The
Parquet data source is now 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:
path
└── to
└── table
├── gender=male
│ ├── ...
│ │
│ ├── country=US
│ │ └── data.parquet
│ ├── country=CN
│ │ └── data.parquet
│ └── ...
https://spark.apache.org/docs/2.2.0/sql-programming-guide.html 15/35
5/28/2019 Spark SQL and DataFrames - Spark 2.2.0 Documentation
└── gender=female
├── ...
│
├── country=US
│ └── data.parquet
├── country=CN
│ └── data.parquet
└── ...
root
|-- name: string (nullable = true)
|-- age: long (nullable = true)
|-- gender: string (nullable = true)
|-- country: string (nullable = true)
Notice that the data types of the partitioning columns are automatically inferred. Currently, numeric data types 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
1. setting data source option mergeSchema to true when reading Parquet files (as shown in the examples below), or
2. setting the global SQL option spark.sql.parquet.mergeSchema to true.
https://spark.apache.org/docs/2.2.0/sql-programming-guide.html 16/35
5/28/2019 Spark SQL and DataFrames - Spark 2.2.0 Documentation
// 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)
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:
1. 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.
2. 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.
https://spark.apache.org/docs/2.2.0/sql-programming-guide.html 17/35
5/28/2019 Spark SQL and DataFrames - Spark 2.2.0 Documentation
Configuration
Configuration of Parquet can be done using the setConf method on SparkSession or by running SET key=value
commands using SQL.
spark.sql.parquet.compression.codec snappy Sets the compression codec use when writing Parquet files.
Acceptable values include: uncompressed, snappy, gzip,
lzo.
spark.sql.hive.convertMetastoreParquet true 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.
JSON Datasets
Scala Java Python R Sql
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.
https://spark.apache.org/docs/2.2.0/sql-programming-guide.html 18/35
5/28/2019 Spark SQL and DataFrames - Spark 2.2.0 Documentation
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.
import spark.implicits._
// SQL statements can be run by using the sql methods provided by spark
val teenagerNamesDF = spark.sql("SELECT name FROM people WHERE age BETWEEN 13 AND 19")
teenagerNamesDF.show()
// +------+
// | name|
// +------+
// |Justin|
// +------+
Hive Tables
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
https://spark.apache.org/docs/2.2.0/sql-programming-guide.html 19/35
5/28/2019 Spark SQL and DataFrames - Spark 2.2.0 Documentation
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.
import java.io.File
import org.apache.spark.sql.Row
import org.apache.spark.sql.SparkSession
// warehouseLocation points to the default location for managed databases and tables
val warehouseLocation = new File("spark-warehouse").getAbsolutePath
import spark.implicits._
import spark.sql
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")
https://spark.apache.org/docs/2.2.0/sql-programming-guide.html 20/35
5/28/2019 Spark SQL and DataFrames - Spark 2.2.0 Documentation
sql("SELECT COUNT(*) FROM src").show()
// +--------+
// |count(1)|
// +--------+
// | 500 |
// +--------+
// The results of SQL queries are themselves DataFrames and support all normal functions.
val sqlDF = 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.
val stringsDS = sqlDF.map {
case Row(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.
val recordsDF = spark.createDataFrame((1 to 100).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|
// ...
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',
https://spark.apache.org/docs/2.2.0/sql-programming-guide.html 21/35
5/28/2019 Spark SQL and DataFrames - Spark 2.2.0 Documentation
inputFormat, These 2 options specify the name of a corresponding `InputFormat` and `OutputFormat` class
outputFormat 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.
fieldDelim, These options can only be used with "textfile" fileFormat. They define how to read delimited
escapeDelim, files into rows.
collectionDelim,
mapkeyDelim,
lineDelim
All other properties defined with OPTIONS will be regarded as Hive serde properties.
The following options can be used to configure the version of Hive that is used to retrieve metadata:
https://spark.apache.org/docs/2.2.0/sql-programming-guide.html 22/35
5/28/2019 Spark SQL and DataFrames - Spark 2.2.0 Documentation
To get started you will need to include the JDBC driver for you 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:
https://spark.apache.org/docs/2.2.0/sql-programming-guide.html 23/35
5/28/2019 Spark SQL and DataFrames - Spark 2.2.0 Documentation
url 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=secret
dbtable 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.
driver The class name of the JDBC driver to use to connect to this URL.
partitionColumn, These options must all be specified if any of them is specified. In addition,
lowerBound, upperBound 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.
fetchsize The JDBC fetch size, which determines how many rows to fetch per round trip. This can
help performance on JDBC drivers which default to low fetch size (eg. Oracle with 10
rows). This option applies only to reading.
batchsize The JDBC batch size, which determines how many rows to insert per round trip. This can
help performance on JDBC drivers. This option applies only to writing. It defaults to
1000.
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.
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.
createTableOptions This is a JDBC writer related option. If specified, this option allows setting of database-
specific table and partition options when creating a table (e.g., CREATE TABLE t (name
string) ENGINE=InnoDB.). 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.
https://spark.apache.org/docs/2.2.0/sql-programming-guide.html 24/35
5/28/2019 Spark SQL and DataFrames - Spark 2.2.0 Documentation
// Note: JDBC loading and saving can be achieved via either the load/save or jdbc methods
// Loading data from a JDBC source
val jdbcDF = spark.read
.format("jdbc")
.option("url", "jdbc:postgresql:dbserver")
.option("dbtable", "schema.tablename")
.option("user", "username")
.option("password", "password")
.load()
jdbcDF2.write
.jdbc("jdbc:postgresql:dbserver", "schema.tablename", connectionProperties)
Troubleshooting
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.
https://spark.apache.org/docs/2.2.0/sql-programming-guide.html 25/35
5/28/2019 Spark SQL and DataFrames - Spark 2.2.0 Documentation
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.
spark.sql.inMemoryColumnarStorage.compressed true When set to true Spark SQL will automatically select
a compression codec for each column based on
statistics of the data.
spark.sql.autoBroadcastJoinThreshold 10485760 Configures the maximum size in bytes for a table that will
(10 MB) 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.
https://spark.apache.org/docs/2.2.0/sql-programming-guide.html 26/35
5/28/2019 Spark SQL and DataFrames - Spark 2.2.0 Documentation
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.
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.:
export HIVE_SERVER2_THRIFT_PORT=<listening-port>
export HIVE_SERVER2_THRIFT_BIND_HOST=<listening-host>
./sbin/start-thriftserver.sh \
--master <master-uri> \
...
or system properties:
./sbin/start-thriftserver.sh \
--hiveconf hive.server2.thrift.port=<listening-port> \
--hiveconf hive.server2.thrift.bind.host=<listening-host> \
--master <master-uri>
...
Now you can use beeline to test the Thrift JDBC/ODBC server:
./bin/beeline
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/:
https://spark.apache.org/docs/2.2.0/sql-programming-guide.html 27/35
5/28/2019 Spark SQL and DataFrames - Spark 2.2.0 Documentation
To test, use beeline to connect to the JDBC/ODBC server in http mode with:
To start the Spark SQL CLI, run the following in the Spark directory:
./bin/spark-sql
Configuration of Hive is done by placing your hive-site.xml, core-site.xml and hdfs-site.xml files in conf/. You
may run ./bin/spark-sql --help for a complete list of all available options.
Migration Guide
Upgrading From Spark SQL 2.1 to 2.2
Spark 2.1.1 introduced a new configuration key: spark.sql.hive.caseSensitiveInferenceMode. It had a default
setting of NEVER_INFER, which kept behavior identical to 2.1.0. However, Spark 2.2.0 changes this setting’s default
value to INFER_AND_SAVE to restore compatibility with reading Hive metastore tables whose underlying file schema
have mixed-case column names. With the INFER_AND_SAVE configuration value, on first access Spark will perform
schema inference on any Hive metastore table for which it has not already saved an inferred schema. Note that
schema inference can be a very time consuming operation for tables with thousands of partitions. If compatibility
with mixed-case column names is not a concern, you can safely set
spark.sql.hive.caseSensitiveInferenceMode to NEVER_INFER to avoid the initial overhead of schema inference.
Note that with the new default INFER_AND_SAVE setting, the results of the schema inference are saved as a
metastore key for future use. Therefore, the initial schema inference occurs only at a table’s first access.
SparkSession - existing API on databases and tables access such as listTables, createExternalTable,
dropTempView, cacheTable are moved here.
Dataset API and DataFrame API are unified. In Scala, DataFrame becomes a type alias for Dataset[Row], while Java
API users must replace DataFrame with Dataset<Row>. Both the typed transformations (e.g., map, filter, and
groupByKey) and untyped transformations (e.g., select and groupBy) are available on the Dataset class. Since
compile-time type-safety in Python and R is not a language feature, the concept of Dataset does not apply to these
languages’ APIs. Instead, DataFrame remains the primary programing abstraction, which is analogous to the single-
node data frame notion in these languages.
Dataset and DataFrame API unionAll has been deprecated and replaced by union
Dataset and DataFrame API explode has been deprecated, alternatively, use functions.explode() with select or
flatMap
Dataset and DataFrame API registerTempTable has been deprecated and replaced by createOrReplaceTempView
./sbin/start-thriftserver.sh \
--conf spark.sql.hive.thriftServer.singleSession=true \
...
Since 1.6.1, withColumn method in sparkR supports adding a new column to or replacing existing columns of the
same name of a DataFrame.
From Spark 1.6, LongType casts to TimestampType expect seconds instead of microseconds. This change was
made to match the behavior of Hive 1.2 for more consistent type casting to TimestampType from numeric types.
See SPARK-11724 for details.
https://spark.apache.org/docs/2.2.0/sql-programming-guide.html 29/35
5/28/2019 Spark SQL and DataFrames - Spark 2.2.0 Documentation
See the API docs for SQLContext.read ( Scala, Java, Python ) and DataFrame.write ( Scala, Java, Python ) more
information.
Note that this change is only for Scala API, not for PySpark and SparkR.
https://spark.apache.org/docs/2.2.0/sql-programming-guide.html 30/35
5/28/2019 Spark SQL and DataFrames - Spark 2.2.0 Documentation
In Scala there is a type alias from SchemaRDD to DataFrame to provide source compatibility for some use cases. It is still
recommended that users update their code to use DataFrame instead. Java and Python users will need to update their
code.
Additionally the Java specific types API has been removed. Users of both Scala and Java should use the classes
present in org.apache.spark.sql.types to describe schema programmatically.
Additionally, the implicit conversions now only augment RDDs that are composed of Products (i.e., case classes or
tuples) with a method toDF, instead of applying automatically.
When using function inside of the DSL (now replaced with the DataFrame API) users used to import
org.apache.spark.sql.catalyst.dsl. Instead the public dataframe functions API should be used: import
org.apache.spark.sql.functions._.
Scala Java
https://spark.apache.org/docs/2.2.0/sql-programming-guide.html 31/35
5/28/2019 Spark SQL and DataFrames - Spark 2.2.0 Documentation
https://spark.apache.org/docs/2.2.0/sql-programming-guide.html 32/35
5/28/2019 Spark SQL and DataFrames - Spark 2.2.0 Documentation
ALTER TABLE
Most Hive Data types, including:
TINYINT
SMALLINT
INT
BIGINT
BOOLEAN
FLOAT
DOUBLE
STRING
BINARY
TIMESTAMP
DATE
ARRAY<>
MAP<>
STRUCT<>
Tables with buckets: bucket is the hash partitioning within a Hive table partition. Spark SQL doesn’t support
buckets yet.
UNION type
Unique join
Column statistics collecting: Spark SQL does not piggyback scans to collect column statistics at the moment and
only supports populating the sizeInBytes field of the hive metastore.
File format for CLI: For results showing back to the CLI, Spark SQL only supports TextOutputFormat.
Hadoop archive
Hive Optimizations
A handful of Hive optimizations are not yet included in Spark. Some of these (such as indexes) are less important due to
Spark SQL’s in-memory computational model. Others are slotted for future releases of Spark SQL.
Block level bitmap indexes and virtual columns (used to build indexes)
Automatically determine the number of reducers for joins and groupbys: Currently in Spark SQL, you need to
control the degree of parallelism post-shuffle using “SET spark.sql.shuffle.partitions=[num_tasks];”.
Meta-data only query: For queries that can be answered by using only meta data, Spark SQL still launches tasks to
compute the result.
Skew data flag: Spark SQL does not follow the skew data flags in Hive.
STREAMTABLE hint in join: Spark SQL does not follow the STREAMTABLE hint.
Merge multiple small files for query results: if the result output contains multiple small files, Hive can optionally
merge the small files into fewer large files to avoid overflowing the HDFS metadata. Spark SQL does not support
that.
Reference
https://spark.apache.org/docs/2.2.0/sql-programming-guide.html 33/35
5/28/2019 Spark SQL and DataFrames - Spark 2.2.0 Documentation
Data Types
Spark SQL and DataFrames support the following data types:
Numeric types
ByteType: Represents 1-byte signed integer numbers. The range of numbers is from -128 to 127.
ShortType: Represents 2-byte signed integer numbers. The range of numbers is from -32768 to 32767.
IntegerType: Represents 4-byte signed integer numbers. The range of numbers is from -2147483648 to
2147483647.
LongType: Represents 8-byte signed integer numbers. The range of numbers is from -9223372036854775808 to
9223372036854775807.
FloatType: Represents 4-byte single-precision floating point numbers.
DoubleType: Represents 8-byte double-precision floating point numbers.
DecimalType: Represents arbitrary-precision signed decimal numbers. Backed internally by
java.math.BigDecimal. A BigDecimal consists of an arbitrary precision integer unscaled value and a 32-bit
integer scale.
String type
StringType: Represents character string values.
Binary type
BinaryType: Represents byte sequence values.
Boolean type
BooleanType: Represents boolean values.
Datetime type
TimestampType: Represents values comprising values of fields year, month, day, hour, minute, and second.
DateType: Represents values comprising values of fields year, month, day.
Complex types
ArrayType(elementType, containsNull): Represents values comprising a sequence of elements with the type
of elementType. containsNull is used to indicate if elements in a ArrayType value can have null values.
MapType(keyType, valueType, valueContainsNull): Represents values comprising a set of key-value pairs.
The data type of keys are described by keyType and the data type of values are described by valueType. For a
MapType value, keys are not allowed to have null values. valueContainsNull is used to indicate if values of a
MapType value can have null values.
StructType(fields): Represents values with the structure described by a sequence of StructFields (fields).
StructField(name, dataType, nullable): Represents a field in a StructType. The name of a field is
indicated by name. The data type of a field is indicated by dataType. nullable is used to indicate if values of
this fields can have null values.
All data types of Spark SQL are located in the package org.apache.spark.sql.types. You can access them by doing
import org.apache.spark.sql.types._
Data type Value type in Scala API to access or create a data type
StructField The value type in Scala of the data type of StructField(name, dataType, [nullable])
this field (For example, Int for a StructField Note: The default value of nullable is true.
with the data type IntegerType)
NaN Semantics
There is specially handling for not-a-number (NaN) when dealing with float or double types that does not exactly
match standard floating point semantics. Specifically:
https://spark.apache.org/docs/2.2.0/sql-programming-guide.html 35/35