SparkSession & SparkContext

Apache Spark · Spark Architecture

Theory

SparkSession is the single entry point for modern Spark code. You get one with SparkSession.builder...getOrCreate(), and through it you read data (spark.read), run SQL (spark.sql), create DataFrames, set runtime configuration (spark.conf) and reach the catalog of tables and views. In notebooks and the pyspark shell a session named spark already exists.

SparkContext is the older, lower-level entry point from the RDD era. It represents the connection to the cluster and is still there underneath as spark.sparkContext, used for RDDs, broadcast variables, accumulators and job groups. There is one SparkContext per application, but you can create several SparkSessions on it with spark.newSession(); they share the cluster and cached data but have their own temp views and SQL settings. For example, a notebook can call spark.sparkContext.parallelize([...]) for an RDD demo while all DataFrame work goes through spark. With Spark Connect, only the SparkSession is available on the client.

Why we use it

Before Spark 2.0 you juggled SparkContext, SQLContext and HiveContext. SparkSession unifies them so one object gives you DataFrames, SQL, configuration and the catalog, which keeps code short and consistent.

When to use it

Use SparkSession for everything new: reading, SQL, DataFrames, config. Reach for spark.sparkContext only for RDD APIs, broadcast variables, accumulators or job groups, and remember that Spark Connect clients cannot use it.

How it works

  1. Program starts
  2. Is a session already running (notebook, shell)? Yes: getOrCreate() returns it. No: Builder creates SparkContext and SparkSession.
  3. Read data and run SQL through spark
  4. Use spark.sparkContext only for RDD-level APIs
  5. spark.stop() ends the application

Syntax

spark = (SparkSession.builder.appName("app")
         .config("key", "value").getOrCreate())
sc = spark.sparkContext
spark.conf.set("spark.sql.shuffle.partitions", "64")
other = spark.newSession()

Example

from pyspark.sql import SparkSession, functions as F

spark = (SparkSession.builder.master("local[1]")
         .config("spark.ui.enabled", "false")
         .getOrCreate())

orders = spark.createDataFrame([
    (101, 1, "North", "Laptop", 1, 55000.0, "2026-01-05"),
    (102, 2, "West",  "Phone",  2, 30000.0, "2026-01-06"),
    (103, 1, "North", "Mouse",  3,  1500.0, "2026-01-06"),
    (104, 3, "South", "Laptop", 1, 52000.0, "2026-01-07"),
    (105, 4, "West",  "Tablet", 1, 25000.0, "2026-01-08"),
    (106, 2, "East",  "Phone",  1, 15000.0, "2026-01-08"),
    (107, 5, "North", "Tablet", 2, 48000.0, "2026-01-09"),
    (108, 3, "South", "Mouse",  4,  2000.0, "2026-01-10"),
], "order_id INT, customer_id INT, region STRING, product STRING, "
   "qty INT, amount DOUBLE, order_date STRING"
).withColumn("order_date", F.to_date("order_date"))

sc = spark.sparkContext                     # the lower-level context underneath
rdd = sc.parallelize([1, 2, 3, 4])
print("RDD sum:", rdd.sum())

spark.conf.set("spark.sql.shuffle.partitions", "8")
print("shuffle partitions:", spark.conf.get("spark.sql.shuffle.partitions"))

orders.createOrReplaceTempView("orders")
other = spark.newSession()                  # same SparkContext, separate SQL state
print("same SparkContext:", other.sparkContext is sc)
print("view visible in spark:", spark.catalog.tableExists("orders"))
print("view visible in other:", other.catalog.tableExists("orders"))
print("other shuffle partitions:", other.conf.get("spark.sql.shuffle.partitions"))

# Output:
# RDD sum: 10
# shuffle partitions: 8
# same SparkContext: True
# view visible in spark: True
# view visible in other: False
# other shuffle partitions: 200

Key points

Apache Spark topics

Spark Fundamentals

Spark Architecture

RDDs

DataFrames

Aggregations & Joins

Spark SQL

Window Functions

Cleaning & Complex Types

UDFs

Performance Tuning

Structured Streaming

MLlib & Ecosystem

Interview Prep

T
Tech Town
Log InSign Up Free
Home SQL Python DSA Power BI Snowflake Databricks Spark Gen AI Practice Problems Contest Blog

Master Apache Spark

PySpark and Spark SQL from the ground up: DataFrames, joins, window functions, partitions and performance tuning, Structured Streaming and more. Click any topic in the sidebar to open it right here.

{{ sectionCount }}
Sections
{{ topicCount }}
Topics
Free
Forever
Hands-on practice Practice PySpark Write real PySpark — DataFrames, joins, window functions and Spark SQL — in a live editor with hidden tests and instant checking. Start practising →
Section {{ sec.num }}

{{ sec.label }}

Spark  /  {{ current.sectionLabel }}  /  {{ current.name }}

{{ current.name }}

Theory

{{ current.def }}

Why we use it

{{ rich.why }}

When to use it

{{ rich.when }}

{{ sec.h }}

{{ sec.body }}

{{ sec.body }}

Diagram

{{ rich.dg.caption }}

{{ tb.title }}
{{ c.v }}
{{ rich.dg.op }}
➜
{{ rich.dg.output.title }}
{{ c.v }}
{{ nd.label }}
{{ nd.sub }}
{{ nd.label }}
{{ nd.sub }}
{{ rich.dg.left.title }}
{{ it }}
{{ rich.dg.right.title }}
{{ it }}
On screen — where to click

{{ rich.ui.title }}

{{ u.text }}
  1. {{ st.n }}{{ st.text }}
{{ rich.ui.title }}
{{ u.text }}
Flowchart — how it works
{{ nd.text }}
{{ nd.text }}
◇ {{ nd.text }}
Yes → {{ nd.yes }}
No → {{ nd.no }}
Syntax
{{ current.syntax }}
Example
{{ current.example }}
Want to run this yourself? Try the same API on Practice PySpark Online right in your browser, or run it locally after pip install pyspark (needs Java 17+), or paste it into a Databricks Free Edition notebook.
Key Points — click to check off as you learn
  • {{ pt.mark }} {{ pt.text }}

Share this topic