Spark SQL
Introduction
Efficient In-Memory Storage
- Simply caching Hive records as Java objects is inefficient due to high per-object overhead
- Instead, Shark employs column-oriented storage using arrays of primitive types

- Row-oriented storage is more suitable for real time searching (such as real-time transaction processing)
- Column-oriented storage is more suitable for big data systems for anlyzing, like search the frequent objects within the whole dataset that requires to scan the whole column
Approaches
- Spark SQL introduces a Tightly Integrated way to work with a new abstraction of Structured Data called SchemaRDD (a.k.a. DataFrame), which is a Distributed Collection of Rows (i.e. a Table) with Named Columns
It supports the Transformation of RDDs using SQL: In particular, DataFrames (aka SchemaRDDs) is an abstraction which supports Selecting, Filtering, Aggregating and Plotting Structured data
Spark SQL v.s. Shark
Shark modified the Hive backend to run over Spark but had two challenges:
- Limited integration with Spark programs
- Hive Optimizer not designed for Spark
Spark SQL
- reuses some parts of Shark: Hive Data Loading and In-memory Column-store
- adds the features: RDD-aware Optimizer and Richer Language Interfaces
RDDs v.s. SchemaRDDs
- Spark + RDDs: Functional transformations on Partitioned Collections of Opaque Objects
- SQL + DataFrames (aka SchemaRDDs): Declarative transformations on Partitioned Collections of Tuples
Data Model
- Nested data model
- Supports both primitive SQL types (
boolean,integer,double,decimal,string,data,timestamp) and complex types (structs,arrays,maps, andunions); also user defined types. - First class support for complex data types
Schema
Relational operations
- Relational operations include
select,where,join,groupByvia a DSL - Operators take expression objects
- Operators build up an abstract syntax tree (AST), which is then optimized by Catalyst
1
2
3
4
5
6// Spark SQL
employees
.join(dept, employees ("deptId") === dept("id"))
.where(employees("gender") === "female")
.groupBy(dept("id"), dept("name"))
.agg(count("name")) - Alternatively, register as temp SQL table and perform traditional SQL query strings
1
2
3
4
5// temp SQL table
users.where(users("age") < 21).registerTempTable("young")
// traditional SQL query strings
ctx.sql("SELECT count(*), avg(age) FROM young")
SQLContext
- Entry point for all SQL functionality
Wraps/Extend existing Spark Context
1
2
3# remind for operating Spark SQL
from pyspark.sql import SQLContext
sqlCtx = SQLContext(sc)Sample
Given a text file filled with people’s names and age:
RDDs as Relations using Scala
1
2
3
4
5
6
7
8
9
10
11val sqlContext = new org.apache.spark.sql.SQLContext(sc)
import sqlcontext._
// Define the schema using a case class.
case class Person(name: String, age: Int)
// Create an RDD of Person objects and register it as a table.
val people = sc.textFile("examples/src/main/resources/people.txt")
.map(_.split(","))
.map(p => Person(p(0), p(1).trim.toInt))
people.registerAsTable("people")RDDs as Relations using Python
1
2
3
4
5
6
7
8# Load a text file and convert each line to a dictionary.
lines = sc.textFile("examples/.../people. txt")
parts = lines.map(lambda l: l.split(","))
people = parts.map(lambda p: Row(name=p[0], age=int(p[1])))
# Infer the schema, and register the SchemaRDD as a table
peopleTable = sqlCtx.inferSchema(people)
peopleTable.registerAsTable("people")Querying using Spark SQL in Python
1
2
3
4
5# SQL can be run over SchemaRDDs that have been registered as a table
teenagers = sqlCtx.sql("""SELECT name FROM people WHERE age >= 13 AND age <= 19""")
# The results of SQL queries are RDDs and support all the normal RDD operations
teenNames = teenagers.map(lambda p: "Name: " + p.name)
HiveContext
Wraps/Extend existing Hive Context
1
2
3
4ctx = new HiveContext()
users = ctx.table("users")
young = users.where(user("age") < 21)
println(young.count())Sample: Reading data stored in Hive
1
2
3
4
5
6
7
8
9from pyspark.sql import HiveContext
hiveCtx = HiveContext(sc)
hiveCtx.hql("""CREATE TABLE IF NOT EXISTS src (key INT, value STRING)""")
hiveCtx.hql("""LOAD DATA LOCAL INPATH 'examples/.../kv1.txt' INTO TABLE src""")
# Queries can be expressed in HiveQL
results = hiveCtx.hql("FROM src SELECT key, value").collect()
Caching Tables In-Memory
SparkSQL can cache tables using an in-memory columnar format:
- Scan only required columns
- Fewer allocated objects (less Garbage Collection)
- Automatically selects best compression
1
cacheTable("people") or dataframe.cache()
JSON Support
- We can use jsonFile or jsonRDD to convert a collection of JSON objects into a DataFrame
- Infer and Union the schema of each record
- Maintain nested structures and arrays
1
2
3
4
5
6
7
8
9
10
11
12# Create a SchemaRDD from the file(s) pointed to by path
people = sqlContext.jsonFile(path)
# Visualized inferred schema with printSchema()
people.printSchema()
# root
# |-- age: integer
# |-- name: string
# Register this SchemaRDD as a table
people.registerTempTable("people")
Data Sources API
Allow easy integration with new sources of structured data:1
2
3CREATE TEMPORARY TABLE episodes
USING com.databricks.spark.avro
OPTIONS (path "./episodes.avro")
Read/Write Data
We can unify and simplify the interface to read/write data in many different formats1
2
3
4
5
6
7
8
9
10
11
12
13
14# Read and Write functions create new builders for doing the I/Os
# Builder methods are used to specify: Format, Paritioning, Handling of existing data, ...
df = sqlContext.read \
.format("json") \
.option("samplingRatio", "0.1") \
.load("/home/michael/data.json")
df.write \
.format("parquet") \
.mode("append") \
.partitionBy("year") \
.saveAsTable("fasterData")
# load, save or saveAsTable functions create new builders for doing the I/Os
Computational Operations
Computing Average:
Using RDD:
1
2
3
4
5data = sc.textFile(...).split("\t")
data.map(lambda x: (x[0], [int(x[1]), 1])) \
.reduceByKey(lambda x, y: [x[0] + y[0], x[1] + y[1]]) \
.map(lambda x: [x[0], x[1][0] / x[1][1]]) \
.collect()Using SQL:
1
2
3SELECT name, avg(age)
FROM people
GROUP BY nameUsing pig:
1
2
3P = load '/people' as (name, age);
G = group P by name;
R = foreach G generate ... AVG(G.age);Using DataFrames:
1
2
3
4sqlCtx.table("people") \
.groupBy("name") \
.agg("name", avg("age")) \
.collect()
Optimization
Plan Optimization
Optimization happens as late as possible, Spark SQL can optimize even across different functions
- Example:
1
2joined = users.join(events, users.id == events.uid)
filtered = joined.filter(events.date >= "2015-01-01")
Datasets and DataFrames
- DataFrames are collections of rows with a schema
- Datasets add static types, e.g.
Dataset[Person]- Libraries can take data of both forms
- DataFrames, Datasets, and SQL share the same optimization/execution pipeline
- Example:
1
2
3
4
5
6
7
8
9
10case class User(name: String, id: Int)
case class Message(user: User, text: String)
dataframe = sqlContext.read.json("log.json") // DataFrame, i.e. Dataset[Row]
messages = dataframe.as[Message] // Dataset[Message]
users = messages.filter(m => m.text.contains("Spark"))
.map(m => m.user) // Dataset[User]
pipeline.train(users) // MLlib takes either DataFrames or Datasets
Conclusion
- SQL is wildly popular and important for real-world customers
- Schema is very useful
- In most data pipelines, even the ones that start with unstructured data end up having some implicit structure
- Key-value abstraction (under RDD) is too limited
- Nevertheless, Support for Semi/Un-structured data is critical!
- Separation of Logical vs. Physical Plan is important for Performance Optimizations, e.g. join selection.

