The Spark ecosystem (SQL, Structured Streaming, MLlib, GraphX/GraphFrames, Spark Connect)

Apache Spark · Spark Fundamentals

Theory

Spark is one core engine with several libraries on top. Spark Core schedules tasks, manages memory and recovers from failures. Spark SQL adds DataFrames, SQL queries and the Catalyst optimizer, and almost everything else is built on it. Structured Streaming runs the same DataFrame code on data that keeps arriving (Kafka, files) as a series of small incremental batches. MLlib (pyspark.ml) provides distributed feature engineering and models such as linear regression, random forests and ALS recommendations.

For graphs, GraphX is Spark's built-in graph library for Scala and Java, while GraphFrames is a separate package that offers DataFrame-based graphs with a Python API. Spark Connect is a client-server protocol: your Python app becomes a thin client that sends DataFrame plans over the network to a remote Spark server. For example, one team can clean orders with Spark SQL, score them with an MLlib model and update a live dashboard with Structured Streaming, all on the same engine.

Why we use it

Before Spark, teams glued together separate systems for batch, streaming, SQL and ML, each with its own API and cluster. Spark gives one engine and one DataFrame API for all of them, so skills and code carry over between workloads.

When to use it

Use Spark SQL/DataFrames for ETL and analytics, Structured Streaming for near real-time pipelines, MLlib for ML on data too big for scikit-learn, and Spark Connect when the client should run apart from the cluster. Pure graph databases or deep learning frameworks fit some needs better.

How it works

  1. Pick the workload
  2. Batch ETL or analytics? Yes: Spark SQL / DataFrames. No: Check the next option.
  3. Data arrives continuously? Yes: Structured Streaming. No: Check the next option.
  4. Training or scoring a model? Yes: MLlib (pyspark.ml). No: GraphFrames or GraphX for graph problems.
  5. All run on the same Spark Core engine

Syntax

spark.sql("SELECT ...")                     # Spark SQL
spark.readStream.format("kafka")...         # Structured Streaming
from pyspark.ml.regression import LinearRegression   # MLlib
SparkSession.builder.remote("sc://host:15002")      # Spark Connect

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"))

from pyspark.ml.feature import VectorAssembler
from pyspark.ml.regression import LinearRegression

# Spark SQL on a DataFrame
orders.createOrReplaceTempView("orders")
spark.sql("SELECT product, SUM(qty) AS units FROM orders "
          "GROUP BY product ORDER BY units DESC, product").show()

# MLlib: predict amount from qty for one product (toy example)
mice = orders.filter("product = 'Mouse'")
features = VectorAssembler(inputCols=["qty"], outputCol="features").transform(mice)
model = LinearRegression(featuresCol="features", labelCol="amount").fit(features)
print("price per mouse:", round(model.coefficients[0], 2))

# Structured Streaming: the same DataFrame API on data that keeps arriving
import os, tempfile
inbox = tempfile.mkdtemp()
orders.select("region", "amount").write.mode("overwrite").json(os.path.join(inbox, "batch1"))
stream = (spark.readStream.schema("region STRING, amount DOUBLE")
          .json(os.path.join(inbox, "batch1")))
query = (stream.groupBy("region").agg(F.sum("amount").alias("sales"))
         .writeStream.format("memory").queryName("live_sales")
         .outputMode("complete").trigger(availableNow=True).start())
query.awaitTermination()
spark.sql("SELECT * FROM live_sales ORDER BY sales DESC").show()

# GraphX has no Python API; in PySpark graphs use the separate GraphFrames package

# Output:
# +-------+-----+
# |product|units|
# +-------+-----+
# |  Mouse|    7|
# |  Phone|    3|
# | Tablet|    3|
# | Laptop|    2|
# +-------+-----+
#
# price per mouse: 500.0
# +------+--------+
# |region|   sales|
# +------+--------+
# | North|104500.0|
# |  West| 55000.0|
# | South| 54000.0|
# |  East| 15000.0|
# +------+--------+

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