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
- Pick the workload
- Batch ETL or analytics? Yes: Spark SQL / DataFrames. No: Check the next option.
- Data arrives continuously? Yes: Structured Streaming. No: Check the next option.
- Training or scoring a model? Yes: MLlib (pyspark.ml). No: GraphFrames or GraphX for graph problems.
- 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 ConnectExample
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
- Spark SQL and DataFrames are the foundation; streaming and ML reuse them
- Structured Streaming treats a stream as an unbounded table processed in micro-batches
- Use pyspark.ml (DataFrame-based); the older RDD-based pyspark.mllib is in maintenance mode
- GraphX is Scala/Java only; from Python use the separate GraphFrames package
- Spark Connect separates client and server, so thin clients can talk to a remote cluster