Lecture 10 - Realtime Processing with Spark II

Updated 12 Nov 2026

Roadmap

  • Part 1: Spark DataFrame & Spark SQL
    • Spark DataFrame
    • Query, Manipulate
    • Join, Windowing
    • Inspect, Write Output
    • Spark SQL
    • User-Defined Function
    • Spark with Hive Support
  • Part 2: Streaming
    • Streaming Data
    • Spark Streaming
    • Stream Processing
    • Input Stream
    • Sink (Output)
    • Windows Operation

Apache Spark Component

  • Streaming sources include Kafka, Flume, Twitter, HDFS and ZeroMQ
  • Spark Streaming uses DStreams to periodically create RDDs
  • Spark Streaming can use machine learning models to analyze streaming data
  • Spark Streaming can use GraphX features on the data it receives
  • Spark MLlib models use DataFrames to represent data; Spark ML uses RDDs. Both use features from Spark Core
  • Spark GraphX uses Spark Core features behind the scenes
  • Spark SQL transforms operations on DataFrames into operations on RDDs
  • Filesystems include HDFS, Gluster FS, Amazon S3 and others
  • Data sources include Hive, JSON, relational databases, NoSQL databases, Parquet files and others

Spark Core (RDD) is the engine of a car. Spark SQL, Streaming, MLlib and GraphX are different "driving modes" (city, sport, off-road) — they all end up turning the same engine underneath.


Execute Task on Spark: SparkContext and SparkSession

  • SparkContext: The original entry point for Spark applications
    • Manages the connection to a Spark cluster
    • Provides access to low-level RDD operations
  • SparkSession: The recommended entry point for working with DataFrames, Spark SQL, and Structured Streaming
    • Provides a unified interface while reusing the underlying SparkContext
    • For modern Spark applications, prefer the DataFrame API unless low-level RDD operations are specifically required
  • SparkSession = unified entry point since Spark 2.0, which wraps:
    • Spark Context → RDD
    • SQL Context → DataFrame / DataSet
    • Stream Context → DStream

SparkSession is like a hotel's front desk: one place to go for everything (room = RDD, restaurant = SQL, shuttle = streaming). SparkContext is the old back office that still exists behind the desk.


SparkSession Creation

  • SparkSession can be created using the builder() or newSession() methods of the SparkSession
  • For a remote host, change "local[*]" to spark://name:port
  • Master options:
    • local[*] = use all CPU cores
    • local[2] = use 2 cores
    • yarn = use YARN/Hadoop
# Import SparkSession
from pyspark.sql import SparkSession
 
For local spark server
spark = SparkSession.builder.getOrCreate()
 
Or full with master and app
spark = SparkSession.builder.master("local[*]").appName("SparkByExamples.com").getOrCreate()
 
# for remote spark on AWS
spark = SparkSession.builder.master("spark://<remote-emr-ec2-hostname>:7077")\
        .appName("parallelization on Spark")\
        .getOrCreate()
  • Note: "For local spark server" and "Or full with master and app" are comment lines on the slide (they need a # if you actually run the code)
  • getOrCreate() returns the existing session if one exists, otherwise creates a new one

Spark DataFrame

  • A DataFrame is a two-dimensional labeled data structure with columns of potentially different types
    • It is like a spreadsheet, a SQL table, or a dictionary of series objects
  • DataFrames provide a rich set of functions (select columns, filter, join, aggregate) that allow you to solve common data analysis problems efficiently
  • DataFrames are an abstraction built on top of Resilient Distributed Datasets (RDDs)
  • DataFrames and Spark SQL use a unified planning and optimization engine, allowing nearly identical performance across all supported languages (Python, SQL, Scala, and R)

A pandas DataFrame is a spreadsheet on your laptop. A Spark DataFrame is the same-looking table, but its rows are cut into pieces and stored on many servers — you still talk to it as if it were one table.


Why Spark DataFrames?

  • Distributed Data: Data is divided into partitions and processed in parallel across a cluster
  • Schema-Based: Each column has a defined name and data type
  • Lazy Evaluation: Most transformations build an execution plan without immediately processing the data
  • Query Optimization: Spark SQL uses the Catalyst Optimizer to optimize query execution
  • Fault Tolerance: Spark can recompute lost partitions when tasks or nodes fail
# Transformations: build a logical plan
df2 = df.filter(df.speed > 60)
df3 = df2.groupBy("VehicleID").count()
 
# Action: triggers computation
df3.show()
 
# Inspect the execution plan
df3.explain("formatted")
  • filter and groupBy().count() are transformations → nothing runs yet
  • show() is an action → triggers the actual computation
  • explain("formatted") prints the execution plan

Lazy evaluation is like writing a shopping list (transformations) — nothing is bought until you actually go to the store (action). Catalyst then plans the shortest route through the store.


Spark DataFrame and Spark SQL

  • Read and write data in a variety of structured formats (JSON, Hive tables, Parquet, ORC, CSV)
  • Query data using JDBC/ODBC connectors from external business intelligence (BI) data sources such as Tableau, Power BI
  • Provides a programmatic interface to interact with structured data stored as tables or views in a database from a Spark application
  • Offers an interactive shell to issue SQL queries on your structured data
  • Supports ANSI SQL commands and HiveQL


DataFrame Creation

  • There are multiple ways to create a DataFrame:
    • From a Python list of data
    • From file (local, remote) with various format (txt, csv, Json, xml)
    • From database (relational)
df = spark.createDataFrame(data) #from python list
df = spark.read.csv('test.csv').option('header', 'true')
df = spark.read.text('test.txt')
df = spark.read.json('test.json')
df = sc.textFile("s3://book-5186186/book.txt").toDF()
 
df = spark.read.format("xml").option("rootTag", "catalog").option("rowTag", "book")\
                            .load('path/to/xml/file.xml')
 
df = spark.read.format('jdbc')\
            .option('url', 'jdbc:mysql://localhost:3306/db')\
            .option('driver', 'com.mysql.jdbc.Driver')\
            .option('dbtable','new_table').option('user','root')\
            .load()

From a Python List

  • Simplest way to create a DataFrame is from a Python list of data
data = [('James','','Smith','1991-04-01','M',3000),
  ('Michael','Rose','','2000-05-19','M',4000),
  ('Robert','','Williams','1978-09-05','M',4000),
  ('Maria','Anne','Jones','1967-12-01','F',4000),
  ('Jen','Mary','Brown','1980-02-17','F',-1)
]
 
columns = ["firstname","middlename","lastname","dob","gender","salary"]
df = spark.createDataFrame(data=data, schema = columns)
df.show()
+---------+----------+--------+----------+------+------+
|firstname|middlename|lastname|       dob|gender|salary|
+---------+----------+--------+----------+------+------+
|    James|          |   Smith|1991-04-01|     M|  3000|
|  Michael|      Rose|        |2000-05-19|     M|  4000|
|   Robert|          |Williams|1978-09-05|     M|  4000|
|    Maria|      Anne|   Jones|1967-12-01|     F|  4000|
|      Jen|      Mary|   Brown|1980-02-17|     F|    -1|
+---------+----------+--------+----------+------+------+

From an RDD

  • DataFrame can also be created from an RDD and by reading files from several sources
lines = sc.textFile("s3://book-5186186/book.txt")
words = lines.flatMap(lambda line: line.split(" "))
wordCounts = words.map(lambda word: (word, 1)).reduceByKey(lambda count1,count2: count1 + count2)
df=spark.createDataFrame(data=wordCounts,schema=["word","total"])
df.show()
+----------+-----+
|      word|total|
+----------+-----+
|HAWTHORNE.|   77|
|          | 7426|
|        I.|    4|
|        It|  131|
|necessary,|    1|
|   several|   16|
|  reasons,|    1|

From a CSV File (Taxi Data)

df2=spark.read.format('csv').options(header='true', inferSchema='true').load("s3://book-5186186/taxi_header.csv")
df2.show()
df2.printSchema()

  • header='true' → first row is used as column names
  • inferSchema='true' → Spark guesses the data type of each column (int, double, timestamp, …)

DataFrame Process

  • Remember Homework? Count points for each VehicleID
df3 = df2.groupBy("VehicleID").count()
df3.show()

df3.write.csv("s3://book-5186186/VehicleID.csv") # Write data using multiple partitions
df3.coalesce(1).write.csv("s3://book-5186186/VehicleIDSingle.csv") # Write using one partition
  • Without coalesce, Spark writes one file per partition (a folder with many part-xxxxx files)
  • coalesce(1) merges into one partition → one output file

The whole MapReduce homework (mapper + reducer) collapses into one line: groupBy("VehicleID").count().


DataFrame: Query

  • The structured data stored in a DataFrame provides two manipulation methods

Sample table used:

+--------+---+-----+------+
|Category| ID|Truth| Value|
+--------+---+-----+------+
|       A|  1| true|121.44|
|       B|  2|false|300.01|
|       C|  3| null| 10.99|
|       E|  4| true| 33.87|
+--------+---+-----+------+

1. Using Domain-Specific Language

df.filter(df.Truth == True).sort(df.Value).show()
df.select("Category", "Value").show(10)
df_dropdup = df.dropDuplicates()

2. Using SQL Queries

  • Create a view with the createOrReplaceTempView built-in method and run the SQL query using the spark.sql method:
df.createOrReplaceTempView('data_table')
df2=spark.sql('SELECT * FROM data_table WHERE Truth=true ORDER BY Value ASC')
df2.show()

Same question, two languages: the DSL is like ordering in Python ("filter, then sort"), SQL is like ordering in SQL. Both go through the same Catalyst kitchen and come out the same dish.

When, isin, like Operation

from pyspark.sql.functions import *
df.select("Value",when(df.Category != 'E', 1).otherwise(0)).show(4)
+------+---------------------------------------------+
| Value|CASE WHEN (NOT (Category = E)) THEN 1 ELSE 0 END|
+------+---------------------------------------------+
|121.44|                                            1|
|300.01|                                            1|
| 10.99|                                            1|
| 33.87|                                            0|
+------+---------------------------------------------+
df[df.Category.isin("A", "E")].show()
+--------+---+-----+------+
|Category| ID|Truth| Value|
+--------+---+-----+------+
|       E|  4| true| 33.87|
|       A|  1| true|121.44|
+--------+---+-----+------+
df.select("Category", "Value", df.Category.like("%A%")).show(5)
  • when(...).otherwise(...) = SQL CASE WHEN ... THEN ... ELSE ... END
  • isin(...) = SQL IN (...)
  • like("%A%") = SQL LIKE pattern (% = any characters)

Startswith, Endswith, Substring Operation

from pyspark.sql.functions import *
 
dataframe.select("author", "title",dataframe.title.startswith("THE")).show(5) #true/false
dataframe.select("author", "title", dataframe.title.endswith("NT")).show(5) #true/false
dataframe.select(dataframe.author.substr(1, 3).alias("title")).show(5) # 1 is first char
dataframe.select(dataframe.author.substr(3, 6).alias("title")).show(5)
dataframe.select(dataframe.author.substr(1, 6).alias("title")).show(5)

  • substr(start, length) — start is 1-based (1 = first character), second argument is the length, not the end index
    • e.g. "Dean R Koontz".substr(3, 6) → starts at the 3rd char, takes 6 chars → "an R K"

DataFrame: Add, Rename & Remove Columns

  • Adding/Rename/Drop Columns
from pyspark.sql.functions import *
# Lit() is required when we are creating columns with exact values.
df2 = df.withColumn('new_column',lit('This is a new column'))
#add new column with a null value
df2 = df.withColumn("DEFAULT_COL", lit(None))
#add new column based on another column
df2 = df.withColumn("bonus_amount", df.salary*0.3)
#rename column
df2 = df.withColumnRenamed(old_column_name', new_name')
#drop column
df_remove = df.drop("column_name1", "column_name2")
  • Note: the rename line is copied as on the slide (opening quotes missing); the correct form is df.withColumnRenamed('old_column_name', 'new_name')

Sample table on the slide:

+---------+--------+------+------+
|firstname|lastname|gender|salary|
+---------+--------+------+------+
|    James|   Smith|     M|  3000|
|     Anna|    Rose|     F|  4100|
|   Robert|Williams|     M|  6200|
+---------+--------+------+------+
  • lit() = literal → wraps a constant value so it becomes a column
  • bonus_amount example: bonus_amount=0.3×salary\text{bonus\_amount} = 0.3 \times \text{salary} (e.g. James: 0.3×3000=9000.3 \times 3000 = 900)

DataFrame: Group by and Replace

Sample table used (df3):

+--------+---+-----+------+
|Category| ID|Truth| Value|
+--------+---+-----+------+
|       A|  1| true|121.44|
|       B|  2|false|300.01|
|       C|  3| null|  null|
|       E|  4| true|  null|
+--------+---+-----+------+

Group by

df3.groupBy("Category","ID").count().show(3)
+--------+---+-----+
|Category| ID|count|
+--------+---+-----+
|       A|  1|    1|
|       C|  3|    1|
|       B|  2|    1|
+--------+---+-----+

Replace

df3.na.fill(value=5,subset=["value"]).show()
+--------+---+-----+------+
|Category| ID|Truth| Value|
+--------+---+-----+------+
|       A|  1| true|121.44|
|       B|  2|false|300.01|
|       C|  3| null|   5.0|
|       E|  4| true|   5.0|
+--------+---+-----+------+
  • na.fill(value, subset) replaces null values only in the listed columns (Truth nulls stay null)

DataFrame: Join

  • Join is used to combine two DataFrames, and by chaining these you can join multiple DataFrames
  • Supports all basic join types in traditional SQL: INNER, LEFT OUTER, RIGHT OUTER, LEFT ANTI, LEFT SEMI, CROSS
#Syntax
df.join(other_df, on=None, how=None)
 
empDF.join(deptDF,empDF.emp_dept_id ==  deptDF.dept_id, how="inner")
empDF.join(deptDF, (empDF["dept_id"] == deptDF["dept_id"]) &
                  (empDF["branch_id"] == deptDF["branch_id"]),"inner")
  • LEFTANTI means everything on the left that is NOT on the right side
  • LEFTSEMI means return only columns from the left side

Example Tables

empDF:

+------+--------+---------------+-----------+-----------+------+------+
|emp_id|name    |superior_emp_id|year_joined|emp_dept_id|gender|salary|
+------+--------+---------------+-----------+-----------+------+------+
|1     |Smith   |-1             |2018       |10         |M     |3000  |
|2     |Rose    |1              |2010       |20         |M     |4000  |
|3     |Williams|1              |2010       |10         |M     |1000  |
|4     |Jones   |2              |2005       |10         |F     |2000  |
|5     |Brown   |2              |2010       |40         |      |-1    |
|6     |Brown   |2              |2010       |50         |      |-1    |
+------+--------+---------------+-----------+-----------+------+------+

deptDF:

+---------+-------+
|dept_name|dept_id|
+---------+-------+
|Finance  |10     |
|Marketing|20     |
|Sales    |30     |
|IT       |40     |
+---------+-------+

Left Join

empDF.join(deptDF,empDF.emp_dept_id ==  deptDF.dept_id,how="left").show()
+------+--------+---------------+-----------+-----------+------+------+---------+-------+
|emp_id|    name|superior_emp_id|year_joined|emp_dept_id|gender|salary|dept_name|dept_id|
+------+--------+---------------+-----------+-----------+------+------+---------+-------+
|     6|   Brown|              2|       2010|         50|      |    -1|     null|   null|
|     4|   Jones|              2|       2005|         10|     F|  2000|  Finance|     10|
|     1|   Smith|             -1|       2018|         10|     M|  3000|  Finance|     10|
|     3|Williams|              1|       2010|         10|     M|  1000|  Finance|     10|
|     2|    Rose|              1|       2010|         20|     M|  4000|Marketing|     20|
|     5|   Brown|              2|       2010|         40|      |    -1|       IT|     40|
+------+--------+---------------+-----------+-----------+------+------+---------+-------+
  • Keeps all left rows; employee 6 (dept 50) has no match → right columns are null

Full Join

empDF.join(deptDF,empDF.emp_dept_id ==  deptDF.dept_id,how="full").show()
+------+--------+---------------+-----------+-----------+------+------+---------+-------+
|emp_id|    name|superior_emp_id|year_joined|emp_dept_id|gender|salary|dept_name|dept_id|
+------+--------+---------------+-----------+-----------+------+------+---------+-------+
|     6|   Brown|              2|       2010|         50|      |    -1|     null|   null|
|     1|   Smith|             -1|       2018|         10|     M|  3000|  Finance|     10|
|     3|Williams|              1|       2010|         10|     M|  1000|  Finance|     10|
|     4|   Jones|              2|       2005|         10|     F|  2000|  Finance|     10|
|  null|    null|           null|       null|       null|  null|  null|    Sales|     30|
|     2|    Rose|              1|       2010|         20|     M|  4000|Marketing|     20|
|     5|   Brown|              2|       2010|         40|      |    -1|       IT|     40|
+------+--------+---------------+-----------+-----------+------+------+---------+-------+
  • Keeps all rows from both sides; Sales (dept 30) has no employee → left columns are null

leftsemi

empDF.join(deptDF,empDF.emp_dept_id ==  deptDF.dept_id,how="leftsemi").show()
+------+--------+---------------+-----------+-----------+------+------+
|emp_id|    name|superior_emp_id|year_joined|emp_dept_id|gender|salary|
+------+--------+---------------+-----------+-----------+------+------+
|     1|   Smith|             -1|       2018|         10|     M|  3000|
|     3|Williams|              1|       2010|         10|     M|  1000|
|     4|   Jones|              2|       2005|         10|     F|  2000|
|     2|    Rose|              1|       2010|         20|     M|  4000|
|     5|   Brown|              2|       2010|         40|      |    -1|
+------+--------+---------------+-----------+-----------+------+------+
  • (return only columns from left side)
  • Returns rows from the left DataFrame that have at least one matching row in the right DataFrame
  • Returns only columns from the left DataFrame
  • Useful for filtering records based on the existence of matching data

leftanti

empDF.join(deptDF,empDF.emp_dept_id == deptDF.dept_id,how="leftanti").show()
+------+-----+---------------+-----------+-----------+------+------+
|emp_id| name|superior_emp_id|year_joined|emp_dept_id|gender|salary|
+------+-----+---------------+-----------+-----------+------+------+
|     6|Brown|              2|       2010|         50|      |    -1|
+------+-----+---------------+-----------+-----------+------+------+
  • (everything on left that NOT on right side)
  • Returns rows from the left DataFrame that have no matching rows in the right DataFrame
  • Useful for identifying missing, unmatched, or unprocessed records

leftsemi = "Show me employees whose department exists" (like SQL WHERE dept_id IN (...)). leftanti = "Show me employees whose department does NOT exist" (like NOT IN). Neither adds any columns from the right table — the right table is only used as a checklist.


DataFrame: Windows Function

  • Window functions operate on a group of rows (like frame, partition) and return a single value for every input row
    • Same idea as the Hive Window function
  • PySpark SQL supports three kinds of window functions: ranking, analytic, aggregate
from pyspark.sql.window import *
from pyspark.sql.functions import *
windowSpec  = Window.partitionBy("department").orderBy("salary")
 
df.withColumn("row_number",row_number().over(windowSpec)).show()
df.withColumn("rank",rank().over(windowSpec)).show()
df.withColumn("ntile",ntile(2).over(windowSpec)).show()
df.withColumn("lag",lag("salary",2).over(windowSpec)).show()
df.withColumn("lead",lead("salary",2).over(windowSpec)).show()
df.withColumn("avg", avg(col("salary")).over(windowSpec)) \
  .withColumn("min", min(col("salary")).over(windowSpec)) \
  .withColumn("max", max(col("salary")).over(windowSpec)) \
  .show()
  • Ranking: row_number(), rank(), ntile(n)
    • row_number() → 1, 2, 3, … within each department
    • rank() → ties get the same rank, then a gap (1, 2, 2, 4)
    • ntile(2) → splits each partition into 2 buckets
  • Analytic: lag("salary", 2) (value 2 rows before), lead("salary", 2) (value 2 rows after)
  • Aggregate: avg, min, max computed over the window, but every row is kept (unlike groupBy, which collapses rows)

groupBy is like a class teacher reporting one average per class. A window function is like writing that class average next to every student's name — nobody disappears from the list.


DataFrame: More

Inspect Data

# Returns dataframe column names and data types
dataframe.dtypes
 
# Displays the content of dataframe
dataframe.show()
 
# Return first n rows
dataframe.head()
 
# Returns first row
dataframe.first()
 
# Return first n rows
dataframe.take(5)
 
# Computes summary statistics
dataframe.describe().show()
 
# Returns columns of dataframe
dataframe.columns
 
# Counts the number of rows in dataframe
dataframe.count()
 
# Counts the number of distinct rows in dataframe
dataframe.distinct().count()
 
# Prints plans including physical and logical
dataframe.explain(4)

Convert Structure

# Converting dataframe into an RDD
rdd_convert = dataframe.rdd
 
# Converting dataframe into a RDD of string
dataframe.toJSON().first()
 
# Obtaining contents of df as Pandas
dataFramedataframe.toPandas()
  • Note: last line copied as on the slide; it should be dataframe.toPandas()

Write & Save File

# Write & Save File in .parquet format
dataframe.select("author", "title", "rank", "description") \
.write \
.save("Rankings_Descriptions.parquet")
# Write & Save File in .json format
dataframe.select("author", "title") \
.write \
.save("Authors_Titles.json",format="json")
df3.write.csv("s3://book-5186186/VehicleID.csv")
df3.coalesce(1).write.csv("s3://book-5186186/VehicleIDSingle.csv")
  • Default save() format is Parquet

Use SQL Query

  • One of the core features of Spark is its ability to run SQL queries on structured data
  • Using SQL queries, create a view with the createOrReplaceTempView built-in method and run the SQL query using the spark.sql method:
df.createOrReplaceTempView('data_table')
df2=spark.sql('SELECT * FROM data_table WHERE Truth=true ORDER BY Value ASC') #return DataFrame
df2.show()
 
spark.sql('SELECT name,gender FROM emptb limit 5').show()
spark.sql('SELECT name,gender FROM emptb where salary>1000').show()
spark.sql('SELECT gender, count(*) as total FROM emptb group by gender').show()
spark.sql('SELECT gender,avg(salary) as avg_sal FROM emptb group by gender order by avg_sal').show()
spark.sql('SELECT * FROM emptb inner join depttb on emptb.emp_dept_id=depttb.dept_id').show()
  • spark.sql(...) returns a DataFrame, so you can keep chaining DataFrame methods on it
  • A temp view lives only as long as the SparkSession

createOrReplaceTempView is like putting a name tag on your DataFrame so SQL can call it by name.


User Defined Functions (UDF)

  • UDFs are used to extend the functions of the framework and re-use these functions on multiple DataFrames
    • Example: you want to convert every first letter of a word in a name string to a capital case; built-in features don't have it, hence you can create it as a UDF and reuse it as needed on many DataFrames
  • Once created, UDFs can be re-used on several DataFrames and SQL expressions
from pyspark.sql.functions import *
from pyspark.sql.types import *
def trim(resStr):
    return resStr.strip()
 
convertUDF = udf(lambda z: trim(z),StringType()) # Converting function to UDF
df.select(col("Seqno"), convertUDF(col("Name")).alias("Name")).show()
  • udf(function, returnType) — wrap a normal Python function; you must give the return type (e.g. StringType())

Example: Mask Some Characters

  • Create a function to mask some characters
from pyspark.sql.functions import *
from pyspark.sql.types import *
 
def masker(var1):
    return var1[-4:].rjust(len(var1),"#")
 
maskUDF = udf(lambda z: masker(z),StringType()) # Converting function to UDF
df.select(col("Seqno"), maskUDF(col("Name")).alias("MaskName")).show()
 
 
 
###########SQL##################
spark.udf.register("masker", masker,StringType())
df.createOrReplaceTempView("NAME_TABLE")
spark.sql("select Seqno, masker(Name) as Name from NAME_TABLE").show()
+-----+------------+
|Seqno|        Name|
+-----+------------+
|    1|  ######ones|
|    2|########mith|
|    3| #######ders|
+-----+------------+
  • var1[-4:] keeps the last 4 characters; .rjust(len(var1), "#") pads the left with # back to the original length
  • Two ways to use a UDF:
    • DataFrame API: udf(...) → call it inside select
    • SQL: spark.udf.register("name", func, type) → call it by name inside spark.sql

A UDF is like adding your own custom button to a calculator. Note: Python UDFs are slower than built-in functions (data has to go Python ↔ JVM), so use built-ins when they exist.


Using Hive Table from Spark

  • To read a Hive table, you need to create a SparkSession with enableHiveSupport()
    • It includes connectivity to a persistent Hive metastore, support for Hive SerDes, and Hive user-defined functions
  • Spark SQL supports reading a Hive table to DataFrame in two ways:
    • SparkSession.read.table() method
    • SparkSession.sql() statement
from os.path import abspath
from pyspark.sql import SparkSession
 
warehouse_location = abspath('spark-warehouse') #for hadoop, "/hive/warehouse/dir"
spark = SparkSession.builder.appName("SparkByExamples.com") \
    .config("spark.sql.warehouse.dir", warehouse_location) \
    .config("hive.metastore.uris", "thrift://remote-host:9083") \ #Optional
    .enableHiveSupport() \
    .getOrCreate()

Read Hive Table into DataFrame

df = spark.sql("select * from emp.employee") #emp is hive database, employee is table in hive
df.show()
 
df = spark.read.table("employee")
df.show()

Save DataFrame to Hive Table

spark.sql("CREATE DATABASE IF NOT EXISTS emp") #create hive database
sampleDF.write.mode('overwrite').saveAsTable("emp.employee") # Create Hive Internal table
 
# Create Hive External table
sampleDF.write.mode(SaveMode.Overwrite).option("path", "/path/to/external/table")
        .saveAsTable("emp.employee")
  • Internal (managed) table: Hive owns the data → dropping the table deletes the data
  • External table: data lives at the given path → dropping the table removes only the metadata

Use SQL Temporary View to Save Hive Table

#Create temporary view
sampleDF.createOrReplaceTempView("sampleView")
 
#Create a Database CT
spark.sql("CREATE DATABASE IF NOT EXISTS ct")
 
#Create a Table naming as sampleTable under CT database.
spark.sql("CREATE TABLE ct.sampleTable (id Int, name String, age Int, gender String)")
 
#Insert into sampleTable using the sampleView.
spark.sql("INSERT INTO TABLE ct.sampleTable  SELECT * FROM sampleView")
 
#Lets view the data in the table
spark.sql("SELECT * FROM ct.sampleTable").show()

A temp view is a sticky note (gone when the session ends). A Hive table is a filing cabinet (persistent in the metastore/warehouse, other apps can open it later).


What is Streaming Data

  • Refers to data which is continuously flowing from a source system to a target
  • Usually generated simultaneously and at high speed by many data sources, which can include applications, IoT sensors, log files, and servers
  • Streaming data can be:
    • Sequence of items
    • Structured (e.g., tuples)
    • Ordered (implicitly or timestamped)
    • Arriving continuously at high volumes
    • Not possible to store entirely
    • Sometimes not possible to even examine all items

Batch data is a lake you can scoop all at once. Streaming data is a river — it never stops, and you can only look at the water passing by right now.


What to do with Streaming Data

  • Online, real time processing
  • Potential objectives:
    • Event detection and reaction
    • Fast (potentially approximate) online aggregation and analytics
  • Various applications:
    • Network traffic monitoring/management
    • Sensor networks monitoring
    • Real time facilities monitoring
    • Online data mining (e.g., click stream analysis)
    • Monitoring social media streams


Batch Processing vs Stream Processing

Batch ProcessingStream Processing
Processes bounded datasetsProcesses continuously arriving data
Jobs typically have a defined endQueries may run continuously
Produces results for a fixed inputProduces incremental or updated results
Suitable for historical analysisSuitable for monitoring and event-driven analytics
  • Examples
    • Batch: Calculate daily traffic statistics from yesterday's GPS records
    • Streaming: Update traffic counts every 30 seconds as new GPS events arrive

Batch = reading yesterday's newspaper (complete, fixed). Streaming = watching a live news ticker (keeps updating).


Handle Streaming Data with Windows

  • Since streaming data is a continuous flow of data from a source system to a target, it is infinite data
  • The mechanism for extracting finite relations from an infinite stream is making windows to restrict the processing scope
    • Windows based on ordering attributes (e.g., time)
    • Windows based on item (record) counts
    • Windows based on explicit markers (e.g., punctuations)

You can't count "all the cars that will ever pass" — but you can count "cars that passed in the last 10 seconds". A window turns an endless stream into small finite chunks.


Spark Streaming

  • Spark Streaming is an extension of the core Spark that enables scalable, high throughput, fault-tolerant stream processing of live data streams
  • Data can be ingested from many sources like Kafka, Flume, Kinesis or TCP sockets
  • Processed data can be pushed out to file systems, databases, and live dashboards
  • Spark Structured Streaming is an improved Spark Streaming engine built as part of Spark 2.0 on the Spark SQL library
    • It uses the DataFrame or Dataset APIs, offering a higher abstraction level than Spark Streaming RDDs


Legacy Spark Streaming vs Structured Streaming

Legacy Spark StreamingStructured Streaming
Uses DStream and RDD APIsUses DataFrame and Dataset APIs
Uses StreamingContextUses SparkSession
Uses DStream transformationsUses SQL and DataFrame transformations
Represents streams as sequences of RDDsRepresents streams as unbounded tables
Maintained primarily for legacy systemsRecommended for new streaming applications

Structured Streaming treats the stream as a table that keeps growing at the bottom. You write a normal DataFrame/SQL query on it, and Spark keeps the answer up to date.


Legacy Spark Streaming

  • Spark Streaming receives live input data streams and divides the data into batches, which are then processed by the Spark engine to generate the final stream of results in batches
  • Spark works on Discretized Stream (DStream), representing a continuous data stream, stored as a collection of Resilient Distributed Datasets (RDDs)

  • Flow (from the diagram labels):

    1. The streamed data is ingested by Spark Streaming
    2. The stream is broken up into small micro-batches (DStream)
    3. The Spark engine processes the data, transforming as necessary
    4. Batches of processed data are sent to their designated destinations
  • DStreams are a collection of Resilient Distributed Datasets (RDDs)

  • Structuring a streaming computation as a series of deterministic batch computations on small time intervals

A DStream is like a flip-book: each page is a small RDD (one time slice). Applying flatMap to the DStream applies it to every page.


Legacy Stream Processing

  • Steps:
    1. Initialize StreamingContext or SparkSession (for Structured Streaming)
    2. Define the input sources by creating input DStreams
    3. Define the computations by applying transformation and output operations to DStreams
    4. Start receiving data and processing it using start()
    5. Wait for the processing to be stopped using awaitTermination()
    6. The processing can be manually stopped using stop()


Input Streams and Receivers

  • Spark Streaming provides two categories of built-in streaming sources:
    • Basic sources: directly available in the StreamingContext API. Examples: file systems and socket connections
    • Advanced sources: sources like Kafka, Kinesis, etc. are available through extra utility classes. These require linking against extra dependencies
  • Every input DStream (except file stream) is associated with a Receiver object which receives the data from a source and stores it in Spark's memory for processing
  • File Streams can read data from files on any file system compatible with the HDFS API (HDFS, S3, NFS)

A Receiver is like a mailroom clerk: it picks up incoming letters (data) and stacks them in the inbox (memory) so workers can process them.


Example WordCount Stream for DStream

  • Based on DStream and RDD
from pyspark import SparkContext
from pyspark.streaming import StreamingContext
 
ssc = StreamingContext(sc, 1)
# Create a DStream from a text stream on localhost:9999
lines = ssc.socketTextStream("localhost", 9999)
 
# Split each line into words and count their occurrences
words = lines.flatMap(lambda line: line.split(" "))
wordCounts = words.map(lambda word: (word, 1)).reduceByKey(lambda x, y: x + y)
# Print the word counts
wordCounts.pprint()
 
# Start the streaming context and wait for the data
ssc.start()
ssc.awaitTermination()
  • StreamingContext(sc, 1) → batch interval = 1 second (every 1 s, a new RDD is made)
  • Counts here are per batch (each 1-second batch is counted separately)

Example WordCount Stream for Structured Stream

  • Based on DataFrame and Spark SQL
from pyspark.sql import SparkSession
from pyspark.sql.functions import *
 
# Create DataFrame representing the stream of input lines from connection to localhost:9999
lines = spark.readStream.format("socket").option("host", "localhost").option("port", 9999).load()
 
# Split the lines into words
words = lines.select(explode(split(lines.value, " ")).alias("word"))
 
# Generate running word count
wordCounts = words.groupBy("word").count()
 
# Start running the query that prints the running counts to the console
query = wordCounts.writeStream.outputMode("complete").format("console").start()
 
query.awaitTermination()
  • readStream (instead of read) → creates a streaming DataFrame
  • split turns each line into an array of words; explode turns the array into one row per word
  • writeStream (instead of write) → starts a continuous query

Result Table & Trigger

  • A query on the input will generate the "Result Table"
  • Every trigger interval (say, every 1 second), new rows get appended to the Input Table, which eventually updates the Result Table
  • Whenever the result table gets updated, write the changed result rows to an external sink
  • (Mode: complete, Append, Update)
wordCounts.writeStream \
  .format("console") \
  .trigger(processingTime='60 seconds') \
  .start()

  • Note how counts are running totals across all input so far (unlike the DStream example, which counts per batch)

The Input Table is a guest book that only ever gets new lines. The Result Table is the scoreboard that Spark updates every trigger.

Running It

  • You can run using spark-submit on the cluster (master node):
spark-submit wordStream.py
  • On another session run nc -lk 9999 and try typing something
    • nc (netcat) opens a socket on port 9999 that the streaming job reads from


Sink (Output)

  • Structured Streaming writes processed results to output destinations (sinks) using DataStreamWriter through writeStream
  • Common Output Sinks:
    • Console: Prints results to the console. Mainly used for debugging and testing
    • Memory: Stores results in an in-memory table for interactive queries. Suitable for small datasets and testing
    • File: Writes results to a directory in formats such as Parquet, JSON, CSV, or ORC. Supports Append mode
    • Kafka: Publishes processed data to Kafka topics for downstream applications
    • Foreach: Executes custom processing or writing logic for each output row
    • ForeachBatch: Applies custom processing or writing logic to each micro-batch as a DataFrame. Useful for databases and external systems

Sink (Output) Example

# Console Sink
query = (
    df.writeStream
    .format("console")
    .outputMode("append")
    .start()
)
# File Sink
query = (
    df.writeStream
    .format("parquet")
    .outputMode("append")
    .option("path", "output/data")
    .option("checkpointLocation", "checkpoint/data")
    .start()
)
  • checkpointLocation → where Spark saves its progress so the query can recover after failure

Output Modes

  • Output modes determine which rows are written to the sink after each trigger:
    • Append: Only newly added rows are written to the sink
    • Update: Only rows updated since the previous trigger are written
    • Complete: The entire result table is written after each trigger

Think of a live football scoreboard:

  • Complete = reprint the whole league table every minute
  • Update = only announce the teams whose score changed
  • Append = only announce new rows (e.g. a new goal event), never change old ones

Event Time vs Processing Time

  • Event Time
    • The timestamp when an event actually occurred
    • Usually recorded by the source device or application
  • Processing Time
    • The time when the streaming engine processes the event
  • Why Does It Matter?
    • Network delays may cause events to arrive late. Events may arrive out of order
    • Event-time windows group records based on when events occurred, rather than when Spark received them
  • Example
    • A GPS device records a vehicle position at 10:00 AM, but the event reaches Spark at 10:03 AM

Delay=Processing Time−Event Time\boxed{\text{Delay} = \text{Processing Time} - \text{Event Time}}
  • e.g. 10:03−10:00=310{:}03 - 10{:}00 = 3 minutes

Event time is the date written on a letter; processing time is the date it arrived in your mailbox. If you want to know what happened on Monday, sort by the date written, not the arrival date.


Window Operations on Event Time

  • Since data is infinite, we need to perform data aggregation periodically or over an interval
  • The group-by operation needs to see all the data before executing the aggregation function, so windows create an illusion of finite data with the notion of event time
  • Spark supports three types of window: Tumbling, Sliding, and Session windows


Tumbling Window

  • A tumbling window is a fixed-sized and non-overlapping window where each element is bound to a single window
    • Example: with a window size of 10 seconds, all the incoming events during the 10-second interval fall into that window
  • We can define a tumbling window with a date-time field and a specific gap. Spark will divide the input stream into fixed-size segments after each interval
df .groupBy(window(col("VisitDate"), "10 seconds")) \
   .count()

  • Each event belongs to exactly one window

Tumbling windows are like hourly time slots on a timetable — 9:00–10:00, 10:00–11:00 — back-to-back, no overlap.


Sliding Window

  • A sliding window is similar to a tumbling window, but it is overlapping
  • Therefore, we need to provide a sliding offset and the interval for the definition of a sliding window
  • Example: with a window size of 10 seconds and a sliding offset of 5 seconds, windows will slide every 5 seconds to create a new window of 10 seconds
df .groupBy(window(col("VisitDate")\
     , "10 seconds","5 seconds") \
   .count()
  • Note: code copied as on the slide (one closing ) is missing before .count()); correct form: df.groupBy(window(col("VisitDate"), "10 seconds", "5 seconds")).count()

  • Since windows overlap, one event can belong to several windows:
windows per event=window sizeslide interval\boxed{\text{windows per event} = \frac{\text{window size}}{\text{slide interval}}}
  • e.g. 10 s5 s=2\dfrac{10\text{ s}}{5\text{ s}} = 2 → each event is counted in 2 windows
  • A tumbling window is just a sliding window where slide=window size\text{slide} = \text{window size}

A sliding window is a moving average: "traffic in the last 10 seconds", recalculated every 5 seconds.


Session Window

  • It looks for elements that have occurred continuously. Session windows can be of a dynamic size and depend on the incoming data
  • Session window boundaries are inactivity periods when there is no incoming data
  • They start when an input has been received and continue as long as we keep receiving data within the time interval equivalent to the window size (the gap)
df .groupBy(session_window(\
     col("VisitDate"), "5 seconds")) \
   .count()

A session window is like a website visit: it keeps going while you keep clicking, and ends once you've been idle for 5 seconds. Busy users get long sessions, quick visitors get short ones.


Window Operations on Event Time — Example

  • Group the data by window (2 mins) and compute the count of each group
# Create DataFrame representing the stream of input lines from connection to localhost:9999
lines = spark.readStream.format("socket").option("host", "localhost").option("port", 9999).load()
 
# Split the lines into words
words = lines.select(explode(split(lines.value, " ")).alias("word"))
 
# Group the data by window and compute the count of each group
windowedCounts = words.groupBy(window(words.timestamp, "2 minutes"), words.word).count()
 
# Start running the query that prints the running counts to the console
query = wordCounts.writeStream.outputMode("complete").format("console").start()
 
query.awaitTermination()
  • Groups by (2-minute window, word) → count of each word per 2-minute window
  • Notes on the slide code:
    • words.timestamp requires a timestamp column (for the socket source, use .option("includeTimestamp", True) and keep the timestamp in words)
    • The query writes wordCounts; to output the windowed result it should be windowedCounts.writeStream...

Summary

  • Spark DataFrame
  • Query, Manipulate
  • Join, Windowing
  • Inspect, Write Output
  • Spark SQL
  • User-Defined Function
  • Spark with Hive Support
  • Spark Streaming
    • DStream, Dataframe
  • Stream Processing
  • Input Stream
    • File, Socket, Kafka
  • Sink (Output)
    • Console, DB, File, HDFS, S3
  • Windows Operation