What you will be able to do
- Place each Spark module in the stack: Spark Core and RDDs at the bottom, the Spark SQL engine above it, and the pandas API, Structured Streaming and MLlib built on that engine
- Explain why a SQL query and the equivalent DataFrame code run on the same engine and perform alike
- Convert a PySpark DataFrame to a pandas-on-Spark DataFrame with pandas_api(), and say why toPandas() and ps.from_pandas() don't do that job
- Pick the right module for a batch, SQL, pandas-style, streaming or machine learning task
Key concept
The Spark SQL engine as the shared layer — Spark Core supplies scheduling, fault recovery and the low-level RDD API. Spark SQL builds one optimized execution engine on top of Core, and SQL, DataFrames, the pandas API on Spark, Structured Streaming and the DataFrame-based MLlib all hand their work to that engine. They differ in the syntax you write, not in the engine that runs it.
1.How the Spark modules stack up
Spark ships as one engine with several modules, and each module is a different way into the same cluster. The idea of one engine for many workloads is covered in Spark as one unified engine for many workloads. This page is about which module handles which workload. The modules are layered. Spark Core sits at the bottom with the RDD API and the machinery that runs tasks. Spark SQL sits on Core and processes structured data through SQL and DataFrames. The pandas API on Spark, Structured Streaming and MLlib are built on top of Spark SQL.
In PySpark you meet these modules as packages and entry points. You write relational work with spark.sql() or DataFrame methods. Pandas-style code goes through pyspark.pandas, streams through readStream/writeStream, and machine learning through pyspark.ml. Spark SQL lets you mix SQL queries with Spark programs in the same script, so one job can use several modules without leaving its SparkSession.
MLlib, which is often misspelled MLib, is the module for machine learning. It is a scalable machine learning library built on Spark, so training runs across the cluster instead of on one machine. In PySpark it is the pyspark.ml package, and it works on DataFrames, which means a Spark SQL feature query can feed training directly. Reach for MLlib when a model must be trained on data too large for a single node; keep a single-machine library for data that fits comfortably in memory.
| Module | Workload it covers | What you write |
|---|---|---|
| Spark Core (RDDs) | Low-level parallel operations on partitioned collections | RDD transformations such as map and reduce |
| Spark SQL and DataFrames | Structured data processing with relational queries | SQL text or DataFrame methods (select, filter, join, aggregate) |
| Pandas API on Spark | pandas workloads that have outgrown one machine | pandas syntax via import pyspark.pandas as ps |
| Structured Streaming | Scalable processing of streams | The same DataFrame code as batch, run incrementally |
| MLlib | Machine learning algorithms and pipelines | pyspark.ml pipelines on DataFrames |
Checkpoint 1 of 9· Match them up
A team's PySpark job uses several Spark modules. Match each module to the code you would write to use it.
Tap a term, then the definition that fits it.
Each module is a different way into the same engine. Core exposes the RDD API. Spark SQL takes SQL or DataFrame code. pyspark.pandas scales pandas syntax. Structured Streaming runs batch-style DataFrame code incrementally. MLlib builds pyspark.ml pipelines on DataFrames.
“the Spark SQL engine runs it incrementally and continuously as streaming data continues to arrive”Source: docs.databricks.com
2.Spark Core and RDDs: the layer everything runs on
Spark Core is the runtime that every other module eventually turns into. Each Spark application has a driver program that runs your main function and launches parallel operations on the cluster. The driver schedules tasks onto executors. If an executor is lost, for example because it ran out of memory, Spark reruns its unfinished tasks somewhere else. Scheduling and recovery happen in Core, whether the work began as SQL, a DataFrame or a stream.
The API Core exposes is the resilient distributed dataset (RDD): a collection of elements partitioned across the cluster's nodes and processed in parallel. You can create an RDD from a file in a Hadoop-supported file system or from a collection in the driver program, and then transform it. RDDs recover automatically from node failures. You can also ask Spark to persist an RDD in memory so that later operations reuse it.
Core also manages memory for cached data. Spark tracks cache usage on every node and drops old partitions in least-recently-used order, so a cache that outgrows memory evicts data rather than failing. Core is also where the two shared-variable types live: broadcast variables, which cache a read-only value on every node, and accumulators, which tasks can only add to.
Checkpoint 2 of 9· Check yourself
A developer rewrites a working DataFrame aggregation as RDD map and reduce calls. Their reasoning is that both versions run on the same cluster, so the result will be just as efficient. What actually happens to the RDD version?
Core schedules and recovers tasks for both versions. Only the Spark SQL interfaces give Spark information about the structure of the data and the computation, and Spark uses that information to optimize the work. Plain RDD code doesn't get those optimizations, and RDDs still recover from node failures on their own.
“Unlike the basic Spark RDD API, the interfaces provided by Spark SQL provide Spark with more information about the structure of both the data”Source: spark.apache.org
3.Spark SQL and DataFrames: one engine, two ways in
Spark SQL is the module for structured data, and it exists because structure gives the engine something to optimize. A plain RDD is opaque to Spark. Spark SQL's interfaces tell Spark the shape of the data and of the computation, and Spark SQL uses that extra information to perform extra optimizations. That optimization is described in Catalyst whole-plan optimization, and it is what DataFrames and SQL give you that plain RDDs don't.
DataFrames are the structured API of the Spark SQL module, and they run on Spark Core underneath. Their concepts are covered in DataFrames and Datasets. The language split is a common exam point. The typed Dataset API exists only in Scala and Java, and Python has no Dataset API. In Scala, DataFrame is simply a type alias of Dataset[Row], so each Dataset has an untyped view as a DataFrame. In PySpark you always work with DataFrames.
SQL and DataFrames are two ways into one engine, not two engines. Spark computes every result with the same execution engine, whichever API or language expressed the query. A GROUP BY in SQL text and a groupBy().agg() in Python therefore produce equivalent results and perform alike. Neither has a lighter or faster path. You can move between them in one program, and a SQL query run from Python returns a DataFrame. Choose the one that states the transformation most clearly: SQL for an analyst's aggregate query, DataFrame methods when the logic is built up in code with variables and functions.
Checkpoint 3 of 9· Check yourself
You are porting a Scala job built on a typed Dataset[Customer] to PySpark. What does the Python version work with?
The typed Dataset API exists only in Scala and Java, so the PySpark version uses DataFrames. The DataFrame = Dataset[Row] type alias is a Scala detail. Python has no Dataset type for it to point to.
“The Dataset API is available in Scala and Java. Python does not have the support for the Dataset API.”Source: spark.apache.org
Checkpoint 4 of 9· Exam question
A developer creates a temp view from a DataFrame and runs an aggregation two different ways:
df.createOrReplaceTempView("orders")
sql_result = spark.sql("SELECT customer_id, SUM(amount) AS total FROM orders GROUP BY customer_id")
df_result = df.groupBy("customer_id").agg(sum("amount").alias("total"))
What is true about sql_result and df_result?
Correct answer: A — They produce equivalent output and comparable performance, because Spark SQL and the DataFrame API both compile down to the same Catalyst-optimized logical and physical plan before execution.
- A. Spark SQL and the DataFrame API share the same Catalyst optimizer and the same underlying execution engine, so a SQL string and an equivalent DataFrame chain resolve to the same plan and the same result set with comparable performance.
- B. There is no separate, lighter engine for SQL text; SQL queries are parsed into the same logical plan that DataFrame operations build, so writing the aggregation as SQL does not skip any optimization or execution layer.
- C.
.agg()after.groupBy()implements the same grouping semantics as a SQLGROUP BYclause, since both paths produce the identical grouped logical plan; there is no divergence in how rows are grouped. - D. A temp view created with
createOrReplaceTempViewis a live reference to the DataFrame's query plan, not a snapshot of its data, so queries against the view reflect the same source data asdfat query time. - E. Temp views support the full range of Spark SQL, including aggregate functions like
SUM, immediately after registration; there is no requirement to persist the view as a permanent table first.
4.Pandas API on Spark: pandas syntax over the Spark SQL engine
The pandas API on Spark exists because pandas doesn't scale out to big data. It provides pandas-equivalent APIs that run on Spark, and it's available from Apache Spark 3.2 as import pyspark.pandas as ps. Its advantages are covered in Pandas API on Spark (pyspark.pandas). As a module, it is a pandas-syntax layer over the Spark SQL engine. The same codebase can run on pandas for tests and small datasets and on Spark for distributed production data. It also covers things that are awkward in plain PySpark, such as plotting data straight from a PySpark DataFrame.
The layer changes how the code runs, not only how it reads. A plain pandas DataFrame executes eagerly, step by step, in one process. A pandas-on-Spark DataFrame keeps Spark's lazy evaluation: it stores a logical query against the data source rather than an in-memory result.
There are three conversion calls, and each crosses the boundary in a different direction. DataFrame.pandas_api() turns an existing Spark DataFrame into a pandas-on-Spark DataFrame, so pandas methods work while Spark still runs the computation. DataFrame.toPandas() returns the contents as a plain pandas.DataFrame. That pulls the dataset out of the cluster and runs into the scaling limit the module was built to remove. ps.from_pandas(pdf) goes the other way: it takes a local pandas DataFrame and produces a pandas-on-Spark one, so it isn't the call to use when you start from a Spark DataFrame.
df = spark.createDataFrame(
[(14, "Tom"), (23, "Alice"), (16, "Bob")], ["age", "name"])
df.pandas_api()PySpark also offers pandas at the function level, in the form of the pandas UDF, also called a vectorized UDF. It uses Apache Arrow to move data and pandas to process it. Spark splits the data into batches of rows, calls your function once per batch on a pandas.Series, and concatenates the results. A standard Python UDF works one row at a time. Batched, vectorized processing can make pandas UDFs up to 100x faster than row-at-a-time Python UDFs. The fix for a slow per-value Python function is therefore to rewrite it with the @pandas_udf decorator so it takes and returns a Series.
Checkpoint 5 of 9· Check yourself
Your data-science group has a pandas script that now fails because the data no longer fits on one machine. The group still wants to unit-test it on small local samples. Which approach fits the Spark module built for this case?
The pandas API on Spark gives you pandas-equivalent APIs that run distributed on the Spark SQL engine. The same codebase works with pandas for tests and small datasets and with Spark for production data. toPandas() pulls the data into one local pandas DataFrame, and pandas-on-Spark keeps Spark's lazy evaluation instead of running eagerly.
“with a single codebase that works with pandas (tests, smaller datasets) and with Spark (production, distributed datasets)”Source: docs.databricks.com
Checkpoint 6 of 9· Exam question
A data science team has an existing pandas-based exploratory notebook that relies heavily on DataFrame.plot() for visualizing distributions. The dataset has grown too large to fit in a single machine's memory, so the team wants to keep writing pandas-style code while Spark executes it across the cluster, starting from a PySpark DataFrame named sales_df. Which line correctly converts sales_df into a pyspark.pandas DataFrame so plotting and other pandas methods can be used directly?
Correct answer: A — sales_ps = sales_df.pandas_api(), which wraps the existing distributed DataFrame in a pandas-compatible interface without collecting any data to the driver.
- A.
pandas_api()is the current, documented way to view a native PySpark DataFrame through the pandas-on-Spark interface, and it keeps execution distributed across the cluster. This lets the team reuse pandas-style calls like.plot()without losing scale. - B.
toPandas()materializes every row on the driver as a localpandas.DataFrame, which is exactly the memory bottleneck the team is trying to avoid. It produces a pandas object, but not a distributed one. - C.
ps.from_pandas()is designed to convert an in-memory pandas object into a pandas-on-Spark object, not to wrap an already-distributed Spark DataFrame. Calling it onsales_dfdoes not perform the intended conversion. - D.
toDF()on a DataFrame simply returns an equivalent DataFrame and adds nothing useful here, and PySpark'sDataFrameclass has no.pandas()method to chain afterward. This line would fail before any conversion occurred. - E. Spark's DataFrameWriter supports formats like Parquet, JSON, CSV, and Delta, but "pandas" is not a registered output format. This line writes nothing useful and does not produce a pandas-on-Spark object.
Checkpoint 7 of 9· Exam question
A PySpark job registers a standard Python UDF that multiplies every value in a numeric column by a tax rate, but profiling shows the row-by-row Python UDF is the bottleneck on a 200-million-row DataFrame. The team wants to keep the same per-value logic while cutting the serialization overhead between the JVM and the Python worker. Which change achieves that?
Correct answer: A — Rewrite the function with the @pandas_udf decorator so it receives and returns a pandas.Series, letting Spark batch rows and transfer them through Arrow rather than pickling row by row.
- A.
pandas_udfuses Apache Arrow to move data between the JVM and Python in vectorized, columnar batches rather than one row at a time, which directly reduces the serialization overhead the team is chasing. The per-value logic stays the same, just expressed over apandas.Series. - B. Registering a Python function with
spark.udf.register()still executes it as a Python UDF; it exposes the function to SQL text but does not move execution into the JVM or change the row-by-row serialization pattern. - C. Calling
.map()with a Python function on an RDD still runs that function inside a Python worker process for every element; it does not become a compiled Scala closure just because the DataFrame was converted to an RDD. - D. Adding more shuffle partitions changes how data is distributed across tasks but does not change how each row is serialized to and from the Python worker, so the per-row pickling overhead remains.
- E. Persisting the DataFrame avoids recomputing earlier stages, but it has no effect on how a Python UDF serializes rows to its worker process each time the UDF actually executes.
5.Structured Streaming: the streaming engine on top of Spark SQL
Structured Streaming is Spark's near real-time engine. It offers end-to-end fault tolerance with exactly-once processing guarantees, using the Spark APIs you already know. Its incremental programming model is taught in Structured Streaming incremental programming model. Among the modules, its place is easy to state: it isn't a separate streaming system. You write streaming computation the same way as a batch computation on static data, and the Spark SQL engine runs it incrementally, updating the result as new data arrives.
In practice, a streaming job uses the same DataFrame operations as a batch job. Only the entry and exit points change: DataStreamReader loads a streaming DataFrame from external storage, and DataStreamWriter writes one out. Because the Spark SQL engine runs both batch and streaming queries, a team can turn a nightly batch aggregation into a continuously updated one without learning a second API. Choose Structured Streaming when results must keep up with arriving data. Choose a batch DataFrame job when a periodic snapshot is enough.
Checkpoint 8 of 9· Check yourself
Finance wants its nightly batch revenue aggregation replaced with totals that update as new transactions arrive. How does the PySpark job need to change?
Structured Streaming is built on Spark SQL. You write a streaming computation the same way as a batch computation, and the Spark SQL engine runs it incrementally. Only the entry and exit points change, to DataStreamReader and DataStreamWriter.
“express your streaming computation the same way you would express a batch computation on static data and the Spark SQL engine runs it incrementally”Source: docs.databricks.com
6.MLlib: DataFrame-based machine learning
MLlib is Spark's machine learning library, built on Spark so that training scales across the cluster. It includes common learning algorithms and utilities: classification, regression, clustering, collaborative filtering, dimensionality reduction, and the optimization primitives underneath them. In Python it is the pyspark.ml package, and its current API is DataFrame-based. Models therefore train on the same DataFrames that Spark SQL produces, so a feature-engineering query feeds straight into training.
MLlib is organized around pipelines. It provides a uniform set of APIs for creating and tuning machine learning pipelines, and the Pipelines API chains the steps of a workflow. For example, one pipeline can build a binary classifier, and another can predict hourly bike rentals with gradient-boosted trees. Each step is a stage such as a transformer, and you can write a custom transformer when the built-in ones don't cover a step. Training a pipeline produces a fitted PipelineModel, which you then apply to new data to generate predictions.
Checkpoint 9 of 9· Check yourself
After a Spark SQL query builds a feature DataFrame, a data scientist wants to train a gradient-boosted trees regressor that scales across the cluster. What is the right way to feed those features into MLlib?
MLlib's pyspark.ml API is DataFrame-based. Models train on the same DataFrames that Spark SQL produces, so you don't need to convert to an RDD or a local pandas DataFrame. Training stays distributed across the cluster.
“DataFrame - A distributed collection of data grouped into named columns. See DataFrames and DataFrame-based MLlib.”Source: docs.databricks.com
Sources
(15)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.https://docs.databricks.com/aws/en/pysparkOfficial docs
“Spark SQL allows you to mix SQL queries with Spark programs.”
↩︎ How the Spark modules stack up“MLlib is a scalable machine learning library built on Spark”
↩︎ How the Spark modules stack up“Spark SQL allows you to mix SQL queries with Spark programs.”
↩︎ Spark SQL and DataFrames: one engine, two ways in“with a single codebase that works with pandas (tests, smaller datasets) and with Spark (production, distributed datasets)”
↩︎ Pandas API on Spark: pandas syntax over the Spark SQL engine“This varies drastically from eager execution, which is the model used by pandas DataFrames.”
↩︎ Pandas API on Spark: pandas syntax over the Spark SQL engine“the Spark SQL engine runs it incrementally and continuously as streaming data continues to arrive”
↩︎ Structured Streaming: the streaming engine on top of Spark SQL“provides a uniform set of APIs that help users create and tune practical machine learning pipelines”
↩︎ MLlib: DataFrame-based machine learning“the Spark SQL engine runs it incrementally and continuously as streaming data continues to arrive”
↩︎ Checkpoint“express your streaming computation the same way you would express a batch computation on static data and the Spark SQL engine runs it incrementally”
↩︎ Checkpoint - 2.https://spark.apache.org/docs/latest/sql-programming-guide.htmlSecondary source
“Spark SQL is a Spark module for structured data processing.”
↩︎ How the Spark modules stack up“the interfaces provided by Spark SQL provide Spark with more information about the structure of both the data and the computation being performed”
↩︎ Spark SQL and DataFrames: one engine, two ways in“In the Scala API, DataFrame is simply a type alias of Dataset[Row].”
↩︎ Spark SQL and DataFrames: one engine, two ways in“When computing a result, the same execution engine is used, independent of which API/language you are using to express the computation.”
↩︎ Key concept“When computing a result, the same execution engine is used, independent of which API/language you are using to express the computation.”
↩︎ Exam trap 1“The Dataset API is available in Scala and Java. Python does not have the support for the Dataset API.”
↩︎ Exam trap 2“Internally, Spark SQL uses this extra information to perform extra optimizations.”
↩︎ Exam trap 4“Unlike the basic Spark RDD API, the interfaces provided by Spark SQL provide Spark with more information about the structure of both the data”
↩︎ Checkpoint“When computing a result, the same execution engine is used, independent of which API/language you are using to express the computation.”
↩︎ Prediction“The Dataset API is available in Scala and Java. Python does not have the support for the Dataset API.”
↩︎ Checkpoint - 3.
“When an executor is removed, Spark reruns its unfinished tasks.”
↩︎ Spark Core and RDDs: the layer everything runs on - 4.https://spark.apache.org/docs/latest/cluster-overview.htmlSecondary source
“Because the driver schedules tasks on the cluster”
↩︎ Spark Core and RDDs: the layer everything runs on - 5.https://spark.apache.org/docs/latest/rdd-programming-guide.htmlSecondary source
“a collection of elements partitioned across the nodes of the cluster that can be operated on in parallel”
↩︎ Spark Core and RDDs: the layer everything runs on“Finally, RDDs automatically recover from node failures.”
↩︎ Spark Core and RDDs: the layer everything runs on“Spark automatically monitors cache usage on each node and drops out old data partitions in a least-recently-used (LRU) fashion.”
↩︎ Spark Core and RDDs: the layer everything runs on - 6.https://docs.databricks.com/aws/en/reference/sparkOfficial docs
“Each Dataset also has an untyped view called a DataFrame, which is a Dataset of Row.”
↩︎ Spark SQL and DataFrames: one engine, two ways in“See DataFrames and DataFrame-based MLlib.”
↩︎ MLlib: DataFrame-based machine learning“DataFrame - A distributed collection of data grouped into named columns. See DataFrames and DataFrame-based MLlib.”
↩︎ Checkpoint - 7.
“Pandas API on Spark fills this gap by providing pandas equivalent APIs that work on Apache Spark.”
↩︎ Pandas API on Spark: pandas syntax over the Spark SQL engine“for example plotting data directly from a PySpark DataFrame”
↩︎ Pandas API on Spark: pandas syntax over the Spark SQL engine - 8.
“Converts the existing DataFrame into a pandas-on-Spark DataFrame.”
↩︎ Pandas API on Spark: pandas syntax over the Spark SQL engine - 9.
“Returns the contents of this DataFrame as Pandas pandas.DataFrame.”
↩︎ Pandas API on Spark: pandas syntax over the Spark SQL engine“Returns the contents of this DataFrame as Pandas pandas.DataFrame.”
↩︎ Exam trap 3 - 10.
“psdf = ps.from_pandas(pdf)”
↩︎ Pandas API on Spark: pandas syntax over the Spark SQL engine - 11.https://docs.databricks.com/aws/en/udf/pandasOfficial docs
“uses Apache Arrow to transfer data and pandas to work with the data”
↩︎ Pandas API on Spark: pandas syntax over the Spark SQL engine“Spark runs a pandas UDF by splitting the data into batches of rows, calling the function for each batch, and then concatenating the results.”
↩︎ Pandas API on Spark: pandas syntax over the Spark SQL engine“pandas UDFs allow vectorized operations that can increase performance up to 100x compared to row-at-a-time Python UDFs.”
↩︎ Pandas API on Spark: pandas syntax over the Spark SQL engine - 12.
“near real-time processing engine that offers end-to-end fault tolerance with exactly-once processing guarantees using familiar Spark APIs”
↩︎ Structured Streaming: the streaming engine on top of Spark SQL“Structured Streaming lets you express computation on streaming data in the same way you express a batch computation on static data.”
↩︎ Structured Streaming: the streaming engine on top of Spark SQL - 13.https://docs.databricks.com/aws/en/pyspark/referenceOfficial docs
“Interface used to load a streaming DataFrame from external storage systems.”
↩︎ Structured Streaming: the streaming engine on top of Spark SQL - 14.
“common learning algorithms and utilities, including classification, regression, clustering, collaborative filtering, dimensionality reduction, and underlying optimization primitives”
↩︎ MLlib: DataFrame-based machine learning“The pyspark.ml package from Apache Spark MLlib is supported on serverless, standard, and dedicated compute.”
↩︎ MLlib: DataFrame-based machine learning“This notebook illustrates how to create a custom transformer.”
↩︎ MLlib: DataFrame-based machine learning - 15.
“Output: MLlib PipelineModel”
↩︎ MLlib: DataFrame-based machine learning