What's new in Apache Spark 4.2
Spark 4.2 new features: geospatial types, NEAREST BY, vector functions, QUALIFY, metric views, the CHANGES clause, Auto CDC, Arrow Python UDFs and real-time mode in PySpark. Each feature has its area, a source ticket, the code before and with 4.2, and a plain note on what needs a flag or a connector.
- Key takeaways
- Before you start
- 1. Geospatial types: GEOMETRY and GEOGRAPHY
- 2. NEAREST BY top-K join
- 3. Vector functions
- 4. QUALIFY
- 5. SET PATH
- 6. Metric views
- 7. time_bucket and IGNORE NULLS
- 8. Change data capture: the CHANGES clause
- 9. Auto CDC with SCD Type 1
- 10. Cursors in SQL scripts
- 11. Arrow-optimized Python UDFs by default
- 12. Real-time mode in PySpark
- Smaller additions worth knowing
- Version lineage
- Settings and costs
- When these features bite
- Upgrade checklist: what can break
- Known limitations in this release
- Cheat sheet
- Frequently Asked Questions
- What is new in Apache Spark 4.2?
- Which features work without a flag?
- Does Spark 4.2 have geospatial distance functions?
- Why is my
NEAREST BYjoin slow? - Why does
SET PATHfail withSET_PATH_WHEN_DISABLED? - Can I run
CHANGESon a Parquet table? - Does Auto CDC support SCD Type 2 in 4.2?
- Why did my Python UDF return different values after upgrading?
- Why does the Arrow default not apply on the official Docker image?
- Is real-time mode in PySpark stateful?
- Which Spark 4.2 release should I use?
- Why does
pip install pyspark==4.2.1fail?
- Summary
- Further reading
- Trademarks
Spark 4.2.0 came out on 14 July 2026, 210 days after 4.1.0. The release notes count over 1,700 Jira tickets from more than 250 people, and it’s the third release of the 4.x line.
A good chunk of it is Spark absorbing things people used to hand-roll. Spatial types. Vector distance functions. A join that returns the K best matches. There’s SQL for clauses everyone kept rewriting: filter on a window function, choose where unqualified names resolve, define a metric once. Change data capture becomes a real feature. And Python UDFs now go through Arrow by default, which is great for speed and will change the results of a few UDFs out there.
Below are twelve features. Each one shows the code you’d have written before 4.2, the code you write now, and what it needs before it works: nothing, a flag, or a connector. If you’re new to Spark 4, the glossary is a good place to start, and the install steps come right after the overview images. Spark 4.1 is the release before this one and Spark 4.3 the one after. The features-by-release post puts them side by side.

Image 1: Spark 4.2.0 in numbers, and the gaps between the 4.0, 4.1 and 4.2 releases.

Image 2: Spark 4.2 by area, with what each feature replaces and what you write now.
Key takeaways
- Spark can now store spatial values as real types, and it can do top-K similarity search in SQL with
NEAREST BYand the vector functions. Both are brute force today, so filter the candidate side first. QUALIFYandtime_buckettake a subquery and some arithmetic out of queries you already write.SET PATHand metric views move names and definitions into the engine.- The
CHANGESclause reads a change feed as a query and Auto CDC applies one to a table as SCD Type 1. Both need a connector that supports the capability. - Arrow is now the default for Python UDFs. It’s faster, and it can change what an odd UDF returns, so test yours.
- PySpark can run a stateless streaming query in real-time mode by changing only the trigger.
Features at a glance
| Feature | Area | On by default? | How to turn it on |
|---|---|---|---|
| Geospatial types | Types | Yes | Nothing |
NEAREST BY join, vector functions, QUALIFY, time_bucket |
SQL | Yes | Nothing |
| Metric views | SQL | Yes | Nothing; CREATE VIEW ... WITH METRICS |
SET PATH |
SQL | No | spark.sql.path.enabled=true |
CHANGES clause |
Change data | Yes, syntax | A connector that implements change data capture |
| Auto CDC, SCD Type 1 | Declarative Pipelines | Yes, Python API | A connector with row-level operations |
| SQL cursors | SQL scripting | No, internal flags | spark.sql.scripting.cursorEnabled and spark.sql.scripting.continueHandlerEnabled |
| Arrow-optimized Python UDFs | Python | Yes | spark.sql.execution.pythonUDF.arrow.enabled, needs PyArrow and pandas |
| Real-time mode in PySpark | Streaming | Yes, with the trigger | trigger(realTime="5 seconds"), Kafka source, update mode, stateless query |
DataFrame.zipWithIndex, pipe | and AGGREGATE, top-K max_by |
DataFrame API, SQL | Yes | Nothing |
Before you start
What you need
| Need | Detail |
|---|---|
| Java | 17, 21 or 25, per the Spark 4.2.1 overview. The apache/spark:4.2.1-python3 image ships Java 21 |
| Python, for PySpark | 3.10 or newer |
| PyArrow and pandas | pip install "pyspark[sql]" brings them, and the Arrow-optimized default uses them |
| Spark | pip install pyspark==4.2.1, the apache/spark:4.2.1-python3 image, or the 4.2.1 release tarball |
| Kafka | A broker, for feature 12 only |
| A catalog with change data capture and row-level operations | For features 8 and 9 |
Install Spark 4.2
You’ve got two ways in. 4.2.1 is the latest 4.2 release (4.2.0 shipped on 14 July 2026 and 4.2.1 on 27 October 2026).
Option 1: pip. The wheel bundles Spark, so you need Java (17, 21 or 25) and Python 3.10 or newer. The sql extra
adds PyArrow and pandas.
python3 -m venv .venv && source .venv/bin/activate
pip install "pyspark[sql]==4.2.1"
python -c "import pyspark; print(pyspark.__version__)"
The last command prints 4.2.1. Point PYSPARK_PYTHON at the same interpreter if your shell’s python3
is older, because the workers use it.
Option 2: the release tarball in a common path. Download it, check the checksum, unpack it under /opt
and point SPARK_HOME at a stable link.
curl -LO https://archive.apache.org/dist/spark/spark-4.2.1/spark-4.2.1-bin-hadoop3.tgz
curl -s https://archive.apache.org/dist/spark/spark-4.2.1/spark-4.2.1-bin-hadoop3.tgz.sha512
shasum -a 512 spark-4.2.1-bin-hadoop3.tgz # compare with the line above
sudo tar -xzf spark-4.2.1-bin-hadoop3.tgz -C /opt
sudo ln -sfn /opt/spark-4.2.1-bin-hadoop3 /opt/spark
export SPARK_HOME=/opt/spark PATH=/opt/spark/bin:$PATH
spark-submit --version
The file is 555,086,267 bytes (about 529 MiB). Add the two export lines to ~/.zshrc or ~/.bashrc to
keep them. If the version printed isn’t 4.2.1, an older SPARK_HOME in your shell is winning; start
with env -u SPARK_HOME.
Glossary
| Term | Meaning |
|---|---|
| SRID | Spatial reference identifier: the number that names a coordinate system, such as 4326 |
| WKB | Well-known binary: the standard byte encoding of a geometry |
| Embedding | A list of numbers that represents text, an image or a user, so similar things have similar lists |
| Window function | A function such as row_number() computed across a group of rows without collapsing them |
| SQL path | The ordered list of schemas Spark searches to resolve an unqualified name |
| Metric view | A view that defines dimensions and measures once, in YAML |
| CDC | Change data capture: a feed of inserts, updates and deletes from a table |
| SCD | Slowly changing dimension. Type 1 overwrites old values, so only the latest row per key survives |
| Cursor | A way for a SQL script to walk a query result one row at a time |
| Arrow | A columnar in-memory format Spark uses to move batches between the JVM and Python |
1. Geospatial types: GEOMETRY and GEOGRAPHY
Since: 4.2.0 · Area: Types · Source:
SPARK-51658,SPARK-55261,SPARK-55260,SPARK-55790,SPARK-56771Lineage: new in 4.2. The types are disabled in 4.1 (
GEOSPATIAL_DISABLED).
Until 4.2, a point on a map in Spark was just bytes. You stored it as BINARY, and every reader had to know it was WKB, which coordinate system it used and what to do with it. Spark 4.2 adds two real column types: GEOMETRY for flat coordinates and GEOGRAPHY for positions on the Earth (SPARK-51658). Each one carries an SRID, the number that names its coordinate system, so a value knows where it lives. You build them from WKB, and they read and write Parquet (SPARK-55261, SPARK-55260).
They’re on by default. On 4.1 the same call fails with GEOSPATIAL_DISABLED (SPARK-56771). A GEOMETRY starts at SRID 0, which means unknown, and a GEOGRAPHY at 4326. The SRID registry is built from PROJ 9.7.1 data (SPARK-55790).
Don’t get too excited yet, though. SHOW FUNCTIONS lists exactly five spatial functions: st_asbinary, st_geogfromwkb, st_geomfromwkb, st_setsrid and st_srid. There’s no distance and no containment. For now this is a proper way to store and exchange spatial data, not a spatial query engine.
Before Spark 4.2
A spatial value was a BINARY column. Nothing in the type says it’s a point, or which coordinate
system it uses.
Runnable file: 13_geospatial_before_and_parquet.sql.
-- setup: one point as WKB, x = 1.0 and y = 2.0
CREATE OR REPLACE TEMP VIEW pt AS SELECT X'0101000000000000000000F03F0000000000000040' AS wkb;
SELECT typeof(wkb) FROM pt; -- binary

Image 3: The same bytes, untyped before 4.2 and a typed value with an SRID now.
With Spark 4.2: sample code
Runnable file: 01_geospatial_types.sql.
SELECT typeof(ST_GeomFromWKB(wkb)) FROM pt; -- geometry(0)
SELECT typeof(ST_GeogFromWKB(wkb)) FROM pt; -- geography(4326)
-- give the geometry a coordinate system, afterwards or when you build it
SELECT ST_SRID(ST_SetSRID(ST_GeomFromWKB(wkb), 4326)) FROM pt; -- 4326
SELECT ST_SRID(ST_GeomFromWKB(wkb, 4326)) FROM pt; -- 4326
Writing the values as Parquet files keeps the type and the SRID. A table in the Hive metastore can’t hold the
column: CREATE TABLE ... AS SELECT ST_GeomFromWKB(...) failed with
type expected at the position 4 of 'int:geometry(4326)' but 'geometry' is found. Write by path instead:
INSERT OVERWRITE DIRECTORY '/tmp/geo_pq' USING parquet
SELECT 1 AS id, ST_GeomFromWKB(wkb, 4326) AS g FROM pt;
SELECT id, typeof(g), ST_SRID(g) FROM parquet.`/tmp/geo_pq`; -- 1 geometry(4326) 4326
When it fits, and when it doesn’t
Use the types when you want spatial values to stay typed in Parquet files instead of drifting back to bytes. Store locations as GEOGRAPHY, say, and every reader sees the coordinate system instead of guessing it from a column name. If you need to measure a distance or test whether a point falls inside a polygon, 4.2 can’t do it yet, so that maths has to come from somewhere else. The two classic slips are expecting a distance function to exist and leaving the SRID at 0 when your data does have a coordinate system.

Image 4: The same bytes become a geometry with SRID 0 or a geography with SRID 4326.
2. NEAREST BY top-K join
Since: 4.2.0 · Area: SQL · Source:
SPARK-56395
Ask for the three closest stores to every customer and you end up writing the same thing each time: a cross join, a window function to rank the matches, and a filter on the rank. NEAREST BY turns that into one join clause (SPARK-56395). The syntax is { APPROX | EXACT } NEAREST [ k ] BY { DISTANCE | SIMILARITY } expr, and k defaults to 1.
The catch is cost. Evaluation is brute force today. The documentation says the implementation works through the full cross product of the two sides, so a big right side hurts, and you should filter it first. APPROX is there so the optimiser can pick something faster once one exists, but right now it buys you nothing. INNER and LEFT OUTER are the supported join types, and k can go from 1 to 100000.
Before Spark 4.2
The K nearest needed a cross join, a window to rank, and a filter. It does the same cross-product work
that NEAREST BY does today.
-- setup: two query points and four base points
CREATE OR REPLACE TEMP VIEW pts AS SELECT * FROM VALUES ('q1', 1.0D), ('q2', 9.0D) AS t(q, x);
CREATE OR REPLACE TEMP VIEW base AS
SELECT * FROM VALUES ('a', 0.0D), ('b', 2.0D), ('c', 8.0D), ('d', 20.0D) AS t(name, y);
SELECT q, x, name, y FROM (
SELECT q, x, name, y, row_number() OVER (PARTITION BY q ORDER BY abs(x - y)) AS rn
FROM pts CROSS JOIN base)
WHERE rn <= 2 ORDER BY q, abs(x - y);
-- q1 1.0 a 0.0, q1 1.0 b 2.0, q2 9.0 c 8.0, q2 9.0 b 2.0

Image 5: A cross join, a ranking and a filter become one join clause.
With Spark 4.2: sample code
Runnable file: 03_nearest_by_join.sql.
SELECT q, x, name, y
FROM pts JOIN base EXACT NEAREST 2 BY DISTANCE abs(x - y)
ORDER BY q, abs(x - y);
-- q1 1.0 a 0.0
-- q1 1.0 b 2.0
-- q2 9.0 c 8.0
-- q2 9.0 b 2.0
When it fits, and when it doesn’t
Reach for it when you want the K best matches per row and you’re tired of the cross join, window and filter. That covers retrieval inside SQL: the closest stores, or the most similar products or documents for each row, next to the data and under the table’s existing access controls. Think twice when the right side is large, because the work grows with left rows times right rows. The usual mistake is forgetting to pre-filter that side.

Image 6: Each query point keeps its two nearest base points.
3. Vector functions
Since: 4.2.0 · Area: SQL · Source:
SPARK-54713,SPARK-55030,SPARK-55031Lineage: new in 4.2.
An embedding is a list of numbers that stands for a piece of text, an image or a user, arranged so that similar things get similar lists. Spark 4.2 adds SQL functions to compare them when they’re stored as ARRAY<FLOAT>: vector_cosine_similarity, vector_l2_distance, vector_inner_product, vector_norm, vector_normalize, and the aggregates vector_avg and vector_sum (SPARK-54713, SPARK-55030, SPARK-55031). No UDF, no external service.
Two things to know. The results are exact and computed row by row. This isn’t an approximate nearest-neighbour index, so it suits moderate candidate sets. And the functions are picky about types: vector_norm(..., 2.0D) fails with DATATYPE_MISMATCH.UNEXPECTED_INPUT_TYPE, because the degree has to be a FLOAT. Write 2.0F. Put them next to the NEAREST BY join from the previous section and you have top-K similarity search in plain SQL.
Before Spark 4.2
Array arithmetic with higher-order functions. The cosine needs the norms spelled out as well.
Runnable file: 14_vector_functions_before.sql.
-- inner product of [1,2] and [3,4]
SELECT aggregate(zip_with(ARRAY(1.0F, 2.0F), ARRAY(3.0F, 4.0F), (x, y) -> x * y),
0.0F, (acc, v) -> acc + v) AS dot; -- 11.0
-- cosine similarity of [1,0] and [1,1]
WITH t AS (SELECT ARRAY(1.0F, 0.0F) AS a, ARRAY(1.0F, 1.0F) AS b)
SELECT aggregate(zip_with(a, b, (x, y) -> x * y), 0.0F, (acc, v) -> acc + v)
/ (sqrt(aggregate(transform(a, x -> x * x), 0.0F, (acc, v) -> acc + v))
* sqrt(aggregate(transform(b, x -> x * x), 0.0F, (acc, v) -> acc + v))) AS cosine FROM t;
-- 0.7071067811865475

Image 7: Array arithmetic becomes one function call.
With Spark 4.2: sample code
Runnable files: 08_vector_functions.sql and 11_vector_similarity_join.sql.
SELECT vector_cosine_similarity(ARRAY(1.0F, 0.0F), ARRAY(1.0F, 1.0F)); -- 0.70710677
SELECT vector_l2_distance(ARRAY(1.0F, 2.0F), ARRAY(4.0F, 6.0F)); -- 5.0
SELECT vector_inner_product(ARRAY(1.0F, 2.0F), ARRAY(3.0F, 4.0F)); -- 11.0
SELECT vector_norm(ARRAY(3.0F, 4.0F), 2.0F); -- 5.0
SELECT vector_avg(v) FROM VALUES (ARRAY(1.0F, 2.0F)), (ARRAY(3.0F, 4.0F)) AS t(v); -- [2.0,3.0]
The two closest documents to each query, ranked by cosine similarity, in plain SQL:
CREATE OR REPLACE TEMP VIEW queries AS
SELECT * FROM VALUES ('q1', ARRAY(1.0F, 0.0F)), ('q2', ARRAY(0.0F, 1.0F)) AS queries(q, qe);
CREATE OR REPLACE TEMP VIEW docs AS
SELECT * FROM VALUES ('d1', ARRAY(0.9F, 0.1F)), ('d2', ARRAY(0.1F, 0.9F)), ('d3', ARRAY(0.7F, 0.7F))
AS docs(doc, de);
SELECT q, doc
FROM queries JOIN docs EXACT NEAREST 2 BY SIMILARITY vector_cosine_similarity(qe, de)
ORDER BY q, doc;
-- q1 d1, q1 d3, q2 d2, q2 d3
When it fits, and when it doesn’t
They’re a good fit for ranking embeddings against a query when the candidate set is moderate: support articles against the embedding of a question, say, or a profile vector built by averaging a user’s item embeddings with vector_avg, all in one query. They’re the wrong tool for millions of candidates, where you want a proper approximate index. And watch out for the 2.0D trap.

Image 8: Each function takes ARRAY<FLOAT> arguments and returns a single number.
4. QUALIFY
Since: 4.2.0 · Area: SQL · Source:
SPARK-31561
QUALIFY filters on the result of a window function (SPARK-31561). You know the situation. You want the latest row per customer, so you compute row_number() in a subquery and filter on it in the outer query. With QUALIFY the filter sits next to the window, in a single statement.
The documentation says the clause runs after the window functions are evaluated, and you can refer to a window function from the SELECT list by alias or write one directly in the condition. Aggregates aren’t allowed there. Ties behave the way the window function says they do. With rank(), every tied row qualifies, so a “top one” can return several rows. In the sample below, rank() = 1 returns ids 2, 3 and 5, because region eu has a tie at 30.0 between ids 3 and 5.
Before Spark 4.2
The top row per group needed a subquery around the window.
-- setup: five orders
CREATE OR REPLACE TEMP VIEW orders_t AS SELECT * FROM VALUES
(1, 'eu', 10.0D), (2, 'us', 20.0D), (3, 'eu', 30.0D), (4, 'us', 5.0D), (5, 'eu', 30.0D)
AS t(id, region, amount);
SELECT id, region, amount FROM (
SELECT id, region, amount,
row_number() OVER (PARTITION BY region ORDER BY amount DESC, id) AS rn
FROM orders_t)
WHERE rn = 1 ORDER BY region;
-- 3 eu 30.0
-- 2 us 20.0

Image 9: The subquery around the window goes away.
With Spark 4.2: sample code
Runnable file: 02_qualify.sql.
-- the highest-amount order per region
SELECT id, region, amount FROM orders_t
QUALIFY row_number() OVER (PARTITION BY region ORDER BY amount DESC, id) = 1
ORDER BY region;
-- 3 eu 30.0
-- 2 us 20.0
-- an alias works; with ties, every row ranked 1 qualifies
SELECT id, region, rank() OVER (PARTITION BY region ORDER BY amount DESC) AS r
FROM orders_t QUALIFY r = 1 ORDER BY id;
-- 2 us 1, 3 eu 1, 5 eu 1
When it fits, and when it doesn’t
Use it for top-N-per-group and latest-record-per-key queries. It also makes queries from engines that already have the clause easier to port. It’s no help when the condition has no window function, since aggregates aren’t allowed there. The mistake to watch for is expecting rank() = 1 to give one row per group. Ties all qualify, so ids 3 and 5 both come back for eu.

Image 10: QUALIFY runs after the window functions, so it can filter on them directly.
5. SET PATH
Since: 4.2.0 · Area: SQL · Source:
SPARK-54806
The SQL path is the ordered list of schemas Spark searches when you write a table, view, function or variable name without qualifying it (SPARK-54806). SET PATH changes it for the session, current_path() shows it, and persistent views and SQL functions remember the path they were created with, so they resolve names the same way later. The default path is the system schemas followed by the current schema.
It’s off by default. Without spark.sql.path.enabled=true, SET PATH fails with UNSUPPORTED_FEATURE.SET_PATH_WHEN_DISABLED. If two schemas both hold a table called facts, order in the path decides which one wins. DDL ignores the path: CREATE TABLE t always creates t in the current schema. Built-in names can be qualified as well, so system.builtin.upper('spark') returns SPARK.
Before Spark 4.2
You qualified every name, or switched the current schema with USE.
Runnable file: 15_set_path_before.sql.
-- setup: two schemas that each hold a table named facts
CREATE SCHEMA IF NOT EXISTS ref;
CREATE SCHEMA IF NOT EXISTS sales;
DROP TABLE IF EXISTS ref.facts;
CREATE TABLE ref.facts USING parquet AS SELECT 2 AS id, 'ref' AS src;
DROP TABLE IF EXISTS sales.facts;
CREATE TABLE sales.facts USING parquet AS SELECT 1 AS id, 'sales' AS src;
SELECT * FROM spark_catalog.ref.facts; -- 2 ref

Image 11: One search path replaces the qualified names.
With Spark 4.2: sample code
Runnable file: 04_set_path.sql.
SET spark.sql.path.enabled = true;
SET PATH = spark_catalog.ref, DEFAULT_PATH;
SELECT current_path(); -- spark_catalog.ref,system.builtin,...
SELECT * FROM facts; -- (2, 'ref')
SET PATH = spark_catalog.sales, DEFAULT_PATH;
SELECT * FROM facts; -- (1, 'sales')
When it fits, and when it doesn’t
It’s handy when one script has to run against a reference schema in one environment and a different one in another, without touching every table name. Put the schema first in the path and leave the queries alone. If explicit names read better to whoever maintains the query, skip it. The usual slip is running SET PATH without the flag.

Image 12: The first schema in the path that holds facts wins.
6. Metric views
Since: 4.2.0 · Area: SQL · Source:
SPARK-54119,SPARK-54405,SPARK-54403
A metric view defines dimensions and measures once, in YAML, so every report computes the same number (SPARK-54119). A dimension is something you group by, like a region. A measure is an aggregation, like total amount or order count. You create the view with WITH METRICS LANGUAGE YAML, then ask for a measure with MEASURE(...) and group by a dimension.
The point is that two dashboards can’t disagree about what “revenue” means when the definition lives in one object instead of two copies of a query. The view stores the YAML, queries refer to measures by name, and it works on the built-in catalog in 4.2.
One warning: the documentation has no page for this syntax. The statement form here comes from the project’s own test suite, and the YAML layout is the form the tests use. The YAML carries version: "0.1", which tells you the format is young, so expect it to change.
Before Spark 4.2
Each report carried its own copy of the aggregation, and any difference between copies was a different number.
Runnable file: 16_metric_view_before.sql.
-- setup: five orders in sales.orders
CREATE SCHEMA IF NOT EXISTS sales;
DROP TABLE IF EXISTS sales.orders;
CREATE TABLE sales.orders USING parquet AS
SELECT * FROM VALUES (1, 'eu', 10.0D), (2, 'us', 20.0D), (3, 'eu', 30.0D), (4, 'us', 5.0D), (5, 'eu', 30.0D)
AS t(id, region, amount);
SELECT region, sum(amount) AS total, count(1) AS n
FROM sales.orders GROUP BY region ORDER BY region;
-- eu 70.0 3
-- us 25.0 2

Image 13: The definition moves out of every report and into one object.
With Spark 4.2: sample code
Runnable file: 05_metric_views.sql.
CREATE OR REPLACE VIEW sales.revenue_mv WITH METRICS LANGUAGE YAML AS $$
version: "0.1"
source: spark_catalog.sales.orders
dimensions:
- name: region
expr: region
measures:
- name: total_amount
expr: sum(amount)
- name: order_count
expr: count(1)
$$;
SELECT region, MEASURE(total_amount) AS total, MEASURE(order_count) AS n
FROM sales.revenue_mv GROUP BY region ORDER BY region;
-- eu 70.0 3
-- us 25.0 2
When it fits, and when it doesn’t
It’s worth it when one definition of a measure has to serve many reports, for example a dashboard and an application that must report the same revenue figure. It’s overkill for a one-off query. And don’t write the YAML from memory. Copy the layout shown, because the documentation won’t help you here.

Image 14: One YAML definition, queried with MEASURE.
7. time_bucket and IGNORE NULLS
Since: 4.2.0 · Area: SQL · Source:
SPARK-56594,SPARK-55256,SPARK-55533Lineage: new in 4.2.
time_bucket(size, ts[, origin]) returns the start of the fixed-width bucket a timestamp falls into (SPARK-56594). It replaces the date_trunc or epoch-division arithmetic everyone has written for 15-minute or six-hour windows. The size is an interval, the optional origin aligns the buckets, and the result is a timestamp you can group by or join on.
There’s a smaller change in the same area. collect_list, array_agg and collect_set now accept IGNORE NULLS and RESPECT NULLS (SPARK-55256, SPARK-55533). Plain collect_list already skips nulls, so it returns [1,3] for 1, NULL and 3. That makes IGNORE NULLS a way of saying what already happens, and RESPECT NULLS the new capability: it returns [1,null,3].
Before Spark 4.2
date_trunc covers calendar units only, so a 15-minute bucket needed epoch arithmetic. For an hour the
two agree.
SELECT date_trunc('HOUR', TIMESTAMP_NTZ '2026-11-01 10:40:00'); -- 2026-11-01 10:00:00
SELECT time_bucket(INTERVAL '1' HOUR, TIMESTAMP_NTZ '2026-11-01 10:40:00'); -- 2026-11-01 10:00:00

Image 15: Any fixed width, in one function.
With Spark 4.2: sample code
Runnable file: 06_time_bucket_ignore_nulls.sql.
SELECT time_bucket(INTERVAL '15' MINUTE, TIMESTAMP_NTZ '2026-11-01 11:27:00');
-- 2026-11-01 11:15:00
-- hourly counts and totals
SELECT time_bucket(INTERVAL '1' HOUR, ts) AS hour, count(*) AS n, sum(v) AS total
FROM (VALUES (TIMESTAMP_NTZ '2026-11-01 10:05:00', 1),
(TIMESTAMP_NTZ '2026-11-01 10:40:00', 2),
(TIMESTAMP_NTZ '2026-11-01 11:10:00', 5)) AS t(ts, v)
GROUP BY 1 ORDER BY 1;
-- 10:00 2 3
-- 11:00 1 5
-- keep the nulls only when you ask for them
SELECT collect_list(x) IGNORE NULLS, collect_list(x) RESPECT NULLS
FROM VALUES (1), (NULL), (3) AS t(x);
-- [1,3] [1,null,3]
When it fits, and when it doesn’t
Use time_bucket for fixed-width windows like 15 minutes, for example to roll events up into 5-minute metrics and join those buckets to another table on the bucket start. If a calendar unit is enough, date_trunc still does the job. The mistake to avoid is assuming collect_list keeps nulls. Only RESPECT NULLS does.

Image 16: Each timestamp maps to the start of its hour; the group-by then needs no arithmetic.
8. Change data capture: the CHANGES clause
Since: 4.2.0 · Area: Change data · Source:
SPARK-55668,SPARK-55948,SPARK-55949,SPARK-55950Lineage: streaming reads and net changes arrive in the same release (
SPARK-56686,SPARK-56687).
Change data capture, CDC for short, answers one question: what changed in this table between two versions? It answers it as rows, one per change. Spark 4.2 adds a CHANGES clause to SQL (SPARK-55948) and matching DataFrame and PySpark APIs (SPARK-55949, SPARK-55950) under the umbrella ticket SPARK-55668. Each row carries your data columns plus _change_type, _commit_version and _commit_timestamp. For batch reads, Spark also does some post-processing in the engine, such as detecting updates and computing net changes.
Spark defines the syntax and plans the query. The catalog connector has to supply the change feed. A built-in table can’t, so the clause fails cleanly: on a Parquet table in spark_catalog you get UNSUPPORTED_FEATURE.CHANGE_DATA_CAPTURE, “Catalog spark_catalog doesn’t support Change Data Capture (CDC)”. Think of CDC as something you ask your table format for.

Image 17: Change data capture end to end: the changes of one table, read with CHANGES and applied with Auto CDC.
Before Spark 4.2
Without a change feed you compared two snapshots of the table. It finds inserted and removed rows, but it needs both snapshots and says nothing about when a change happened.
Runnable file: 17_changes_before_snapshot_diff.sql.
-- setup: the table at version 1 and at a later version
CREATE OR REPLACE TEMP VIEW snap_v1 AS SELECT * FROM VALUES (1, 'a'), (2, 'b') AS t(id, data);
CREATE OR REPLACE TEMP VIEW snap_v2 AS SELECT * FROM VALUES (1, 'a'), (3, 'c') AS t(id, data);
SELECT 'insert' AS change, * FROM (SELECT * FROM snap_v2 EXCEPT SELECT * FROM snap_v1)
UNION ALL
SELECT 'delete', * FROM (SELECT * FROM snap_v1 EXCEPT SELECT * FROM snap_v2)
ORDER BY id;
-- delete 2 b
-- insert 3 c

Image 18: A snapshot diff becomes a change feed with versions and timestamps.
With Spark 4.2: sample code
Runnable file: 10_changes_clause.sql.
On a Parquet table the clause fails, as it should:
CREATE TABLE ev (id INT, v STRING) USING parquet;
INSERT INTO ev VALUES (1, 'a');
SELECT * FROM ev CHANGES FROM VERSION 1 TO VERSION 2;
-- [UNSUPPORTED_FEATURE.CHANGE_DATA_CAPTURE] Catalog spark_catalog does not
-- support Change Data Capture (CDC).
To see it succeed you need a catalog that implements the API. Spark’s own tests use an in-memory one,
InMemoryChangelogCatalog, from the spark-catalyst tests jar, and this follows the pattern of
ChangelogEndToEndSuite. Start spark-shell --jars spark-catalyst_2.13-4.2.1-tests.jar and run the code below (Runnable file: 18_changes_clause_catalog.scala):
import java.util
import org.apache.spark.sql.catalyst.InternalRow
import org.apache.spark.sql.connector.catalog._
import org.apache.spark.sql.connector.catalog.Changelog._
import org.apache.spark.sql.types.{LongType, StringType}
import org.apache.spark.unsafe.types.UTF8String
// register the catalog and create a table with two columns
spark.conf.set("spark.sql.catalog.cdc", classOf[InMemoryChangelogCatalog].getName)
val cat = spark.sessionState.catalogManager.catalog("cdc").asInstanceOf[InMemoryChangelogCatalog]
val ident = Identifier.of(Array.empty, "orders")
cat.createTable(ident, Array(Column.create("id", LongType), Column.create("data", StringType)),
Array.empty, new util.HashMap[String, String]())
// three recorded changes: two inserts and a delete
def row(id: Long, data: String, kind: String, version: Long, ts: Long) =
InternalRow(id, UTF8String.fromString(data), UTF8String.fromString(kind), version, ts)
cat.addChangeRows(ident, Seq(
row(1L, "a", CHANGE_TYPE_INSERT, 1L, 1000000L),
row(2L, "b", CHANGE_TYPE_INSERT, 2L, 2000000L),
row(2L, "b", CHANGE_TYPE_DELETE, 3L, 3000000L)))
spark.sql("SELECT * FROM cdc.orders CHANGES FROM VERSION 1 TO VERSION 3").show(false)
// +---+----+------------+---------------+-------------------+
// |id |data|_change_type|_commit_version|_commit_timestamp |
// +---+----+------------+---------------+-------------------+
// |1 |a |insert |1 |1970-01-01 00:00:01|
// |2 |b |insert |2 |1970-01-01 00:00:02|
// |2 |b |delete |3 |1970-01-01 00:00:03|
// +---+----+------------+---------------+-------------------+
// the same feed through the DataFrame API, with an ending version
spark.read.option("startingVersion", "1").option("endingVersion", "2").changes("cdc.orders").show(false)
// the rows with _commit_version 1 and 2
When it fits, and when it doesn’t
Use CHANGES when your table format implements change data capture and you want the feed as a query. A typical case is an incremental downstream table that follows the inserts, updates and deletes of a source, without a diff you maintain yourself. Don’t expect it on a plain Parquet table. And note that it only reads the feed. Applying those changes to a target is Auto CDC’s job, which is next.

Image 19: Spark owns the syntax; the catalog owns the change feed.
9. Auto CDC with SCD Type 1
Since: 4.2.0 · Area: Declarative Pipelines · Source:
SPARK-56249,SPARK-56651,SPARK-56650,SPARK-56957Lineage: Declarative Pipelines arrived in 4.1; Auto CDC with SCD Type 1 is new in 4.2.
Auto CDC takes a change feed and applies it to a target table inside a Declarative Pipeline, the framework from 4.1 where you declare datasets and Spark works out the run order. What happens to old values depends on the slowly changing dimension type, SCD for short. Type 1 overwrites them, so only the latest row per key survives, and that’s what 4.2 offers. In 4.2 it’s a Python API, create_auto_cdc_flow, plus a Spark Connect API (SPARK-56651, SPARK-56650).
Each micro-batch is applied to the target as a MERGE (SPARK-56957), so the target has to be a table whose connector implements Data Source V2 row-level operations. Events are ordered by the sequence_by column, not by arrival, which means an event with a lower sequence can’t overwrite a higher one. The API accepts only stored_as_scd_type=1.
Before Spark 4.2
Keeping a table in sync by hand means picking the latest event per key, then a MERGE that deletes,
updates or inserts, repeated for every table. This works against Spark’s own in-memory test
catalog, InMemoryRowLevelOperationTableCatalog, from the spark-catalyst tests jar.
Runnable file: 19_auto_cdc_scd1_merge_before.sql.
spark-sql --jars spark-catalyst_2.13-4.2.1-tests.jar \
--conf spark.sql.catalog.lh=org.apache.spark.sql.connector.catalog.InMemoryRowLevelOperationTableCatalog
-- setup: the target, and a batch of events with one delete and one re-insert for key 1
CREATE TABLE lh.default.customers (id INT, name STRING, version BIGINT);
CREATE OR REPLACE TEMP VIEW cdc_events AS SELECT * FROM VALUES
(1, 'alice', 1L, 'UPSERT'),
(1, 'alice', 2L, 'DELETE'),
(1, 'alice2', 3L, 'UPSERT'),
(2, 'bob', 1L, 'UPSERT') AS e(id, name, version, op);
-- keep only the latest event per key, because one batch can carry several events for a key
CREATE OR REPLACE TEMP VIEW latest AS
SELECT id, name, version, op FROM (
SELECT *, row_number() OVER (PARTITION BY id ORDER BY version DESC) AS rn FROM cdc_events)
WHERE rn = 1;
MERGE INTO lh.default.customers t
USING latest c ON t.id = c.id
WHEN MATCHED AND c.op = 'DELETE' AND c.version > t.version THEN DELETE
WHEN MATCHED AND c.version > t.version THEN UPDATE SET t.name = c.name, t.version = c.version
WHEN NOT MATCHED AND c.op <> 'DELETE' THEN INSERT (id, name, version) VALUES (c.id, c.name, c.version);
SELECT * FROM lh.default.customers ORDER BY id;
-- 1 alice2 3
-- 2 bob 1

Image 20: The merge logic you write and test becomes one declaration.
With Spark 4.2: sample code
The Python API, from the pyspark.pipelines module (Runnable file: 20_auto_cdc_scd1_pipeline.py). The target must be created first, and the flow
reads a source declared in the same pipeline:
from pyspark import pipelines as dp
dp.create_streaming_table("customers")
dp.create_auto_cdc_flow(
target="customers",
source="cdc_events",
keys=["id"],
sequence_by="version",
apply_as_deletes="op = 'DELETE'",
except_column_list=["op"],
stored_as_scd_type=1,
)
What the Spark tests expect. In AutoCdcScd1SinglePipelineSuite, a stream carrying an upsert, a delete and a
re-upsert for one key, at sequences 1, 2 and 3, ends with the sequence 3 row, because the delete at
sequence 2 is superseded:
id name version
1 alice2 3
The suite is AutoCdcScd1SinglePipelineSuite, under sql/pipelines/src/test in the Spark 4.2.1 source.
In the same suite, pointing the flow at a table whose format has no row-level operations fails when the
flow starts.
When it fits, and when it doesn’t
Use it to replicate a change feed into a table where only the latest version of each record matters: customer profiles, product catalogues, account records. It’s the wrong tool if you need the history of old values, which Type 1 doesn’t keep, and it won’t run on a plain Parquet table. The target needs a connector with row-level operations.

Image 21: The highest sequence wins, so the delete at sequence 2 is superseded.
10. Cursors in SQL scripts
Since: 4.2.0 · Area: SQL scripting · Source:
SPARK-54759Lineage:
CONTINUE HANDLERsupport arrived in 4.1 (SPARK-53621) behind an internal flag.
A cursor lets a SQL script walk a query result one row at a time, with DECLARE ... CURSOR, OPEN, FETCH and CLOSE (SPARK-54759). SQL scripting, on by default since 4.1, lets a BEGIN ... END block declare variables, loop and handle errors. A handler is code that runs when some condition occurs. A CONTINUE handler for NOT FOUND runs when FETCH runs out of rows and lets the script carry on, which is how a cursor loop knows when to stop.
Both pieces sit behind internal flags that default to false: spark.sql.scripting.cursorEnabled (since 4.2.0) and spark.sql.scripting.continueHandlerEnabled (since 4.1.0). Each missing flag fails differently. With neither, you get UNSUPPORTED_FEATURE.SQL_CURSOR. With only the cursor flag, you get UNSUPPORTED_FEATURE.CONTINUE_EXCEPTION_HANDLER. With both, the script runs and returns 60. Because the flags are internal, treat cursors as unfinished and keep them out of production scripts.
Before Spark 4.2
Row-by-row logic left SQL and went through the DataFrame API, with the loop in Python.
Runnable file: 21_cursor_before.py.
rows = spark.sql("SELECT col1 FROM VALUES (10), (20), (30)").collect()
total = sum(r[0] for r in rows)
print(total) # 60

Image 22: The loop stays in SQL.
With Spark 4.2: sample code
Runnable file: 09_sql_cursors.sql.
-- set spark.sql.scripting.cursorEnabled and ...continueHandlerEnabled to true first
BEGIN
DECLARE total INT DEFAULT 0; DECLARE v INT; DECLARE done BOOLEAN DEFAULT false;
DECLARE c CURSOR FOR SELECT col1 FROM VALUES (10), (20), (30);
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = true;
OPEN c;
FETCH c INTO v;
WHILE NOT done DO
SET total = total + v;
FETCH c INTO v;
END WHILE;
CLOSE c;
SELECT total AS cursor_total;
END;
-- 60
Run the script through spark.sql(...) in Scala or Python. The spark-sql -f command splits a file
at each ;, so a BEGIN ... END script fails with PARSE_SYNTAX_ERROR on its first line.
When it fits, and when it doesn’t
The honest use case is porting row-by-row logic from another database’s procedural SQL. If a set-based query will do, and it nearly always will, skip cursors. The common trap is setting only the cursor flag. The CONTINUE handler needs its own.

Image 23: A loop over a cursor: the same BEGIN ... END shape as the 4.1 scripting examples, with a handler that ends it.
11. Arrow-optimized Python UDFs by default
Since: 4.2.0 · Area: Python · Source:
SPARK-54555Lineage: Arrow UDF decorators arrived in 4.1 (
SPARK-52214).
A Python UDF runs in a Python worker, so every row has to cross the boundary between the JVM and Python. The old path pickles rows one at a time. The Arrow path sends columns in Arrow batches instead. In 4.2 the Arrow path is the default for Python UDFs, along with Arrow-based exchange for PySpark in general (SPARK-54555), so existing UDFs get it without a code change.
The Arrow path is faster, but it handles types differently. The two paths can return different values for the same function, so the default can change results in edge cases. A UDF declared int that returns str(x) gave [1, null, 3] on the Arrow path and [null, null, null] on the old one. Returning float(x) / 2 gave [0, null, 1] on the Arrow path and all null on the old one. spark.sql.execution.pythonUDF.arrow.enabled and spark.sql.execution.arrow.pyspark.enabled both read true, and the plan changes from BatchEvalPython to ArrowEvalPython.
One more trap: the official apache/spark:4.2.1-python3 image has no PyArrow or pandas, so there the default quietly falls back to the old path with a RuntimeWarning: “Arrow optimization failed to enable because PyArrow or Pandas isn’t installed.”
Before Spark 4.2
The old path was the default only up to 4.1, and you can still select it with the setting.
Runnable file: 22_arrow_udf_default.py.
from pyspark.sql import SparkSession
from pyspark.sql.functions import udf
spark = SparkSession.builder.getOrCreate()
df = spark.createDataFrame([(1,), (None,), (3,)], "x int")
spark.conf.set("spark.sql.execution.pythonUDF.arrow.enabled", "false")
to_int = udf(lambda x: None if x is None else str(x), "int")
print([r[0] for r in df.select(to_int("x")).collect()]) # [None, None, None]
A UDF picks its path when it’s created, so set the option before you define the UDF. Switching it afterwards leaves a UDF that already exists on the path it was created with.

Image 24: Same function, different result: the default path changed.
With Spark 4.2: sample code
from pyspark.sql import SparkSession
from pyspark.sql.functions import udf
spark = SparkSession.builder.getOrCreate()
df = spark.createDataFrame([(1,), (None,), (3,)], "x int")
print(spark.conf.get("spark.sql.execution.pythonUDF.arrow.enabled")) # true, the default
to_int = udf(lambda x: None if x is None else str(x), "int")
df.select(to_int("x")).explain()
# ArrowEvalPython [<lambda>(x)], [pythonUDF0], 101
print([r[0] for r in df.select(to_int("x")).collect()]) # [1, None, 3]
When it fits, and when it doesn’t
You get the faster path without changing code. Test your UDFs before you upgrade, especially the ones that return a type different from the one they declare. A UDF-heavy PySpark job is where this matters most. If one depends on how the old path coerced types, set spark.sql.execution.pythonUDF.arrow.enabled=false while you fix it. And on an image without PyArrow, don’t expect the Arrow plan.

Image 25: The default flips to Arrow, and edge-case results can change with it.
12. Real-time mode in PySpark
Since: 4.2.0 · Area: Streaming · Source:
SPARK-54660Lineage: stateless real-time mode in Scala in 4.1 (
SPARK-53736); the PySpark trigger is new in 4.2.
Structured Streaming normally cuts a stream into micro-batches and runs one job per batch. Real-time mode swaps that for long-lived tasks that process records as they arrive. 4.1 shipped it for Scala. 4.2 adds the trigger to PySpark (SPARK-54660), so a Python query can use it too.
The limits are real. In 4.2 the query is stateless: no aggregation, no dropDuplicates, no Python UDF. The output mode has to be update, Kafka is the only source, and the trigger duration is a checkpoint interval, not a latency target. The cluster needs a free task slot for every task, so set spark.sql.shuffle.partitions to what it can run at once.
Before Spark 4.2
The same query used the micro-batch trigger, and rows appeared when each batch ended.
Runnable file: 23_realtime_mode_pyspark.py.
from pyspark.sql import SparkSession, functions as F
spark = SparkSession.builder.config("spark.sql.shuffle.partitions", "2").getOrCreate()
events = (spark.readStream.format("kafka")
.option("kafka.bootstrap.servers", "localhost:9092")
.option("subscribe", "events").option("startingOffsets", "latest").load()
.select(F.col("value").cast("string").alias("event"))
.where(F.col("event").startswith("ERROR")))
(events.writeStream.format("console")
.outputMode("update")
.option("checkpointLocation", "/tmp/ckpt_micro")
.trigger(processingTime="5 seconds") # micro-batch
.start())

Image 26: Only the trigger changes: micro-batches before 4.2, the real-time trigger with 4.2.
With Spark 4.2: sample code
# needs a Kafka broker; `events` is the same source and filter as above
(events.writeStream.format("console")
.outputMode("update") # required by real-time mode
.option("checkpointLocation", "/tmp/ckpt_rtm")
.trigger(realTime="5 seconds") # the whole change
.start())
Sending INFO ok, ERROR disk full, ERROR timeout and INFO done printed one batch with the two
ERROR records (the row order can vary):
ERROR timeout
ERROR disk full
Run it with --packages org.apache.spark:spark-sql-kafka-0-10_2.13:4.2.1.
When it fits, and when it doesn’t
It’s good for a stateless Kafka filter or projection that should deliver each record as it lands, such as pulling error events out of a log topic and sending them on without waiting for a micro-batch. It’s not for anything that needs state or a Python UDF, and it’s a poor fit for a small cluster. The classic mistake is adding an aggregation, which real-time mode in 4.2 doesn’t support.

Image 27: Records on the left, filtered records on the right, with no batch boundary in between.
Smaller additions worth knowing
| Feature | What it does | Needs |
|---|---|---|
Pipe \| and aggregates in pipe (SPARK-51518, SPARK-54292) |
\| works as well as \|>, and AGGREGATE or SELECT ... GROUP BY work inside a pipe |
Nothing |
SYSTEM.BUILTIN qualification (SPARK-54807) |
system.builtin.upper('spark') returned SPARK |
Nothing |
Top-K max_by and min_by (SPARK-55322) |
Return the K best values instead of one | Nothing |
PIVOT alias and DROP TABLE on a view (SPARK-55356, SPARK-55019) |
Name a pivot result; drop a view with DROP TABLE |
Nothing |
DataFrame.zipWithIndex (SPARK-55229, SPARK-55228) |
Add a row index column | Nothing |
TABLESAMPLE SYSTEM (SPARK-55978) |
Block sampling that a source can push down | A source that supports it |
Tuple sketches (SPARK-54179, SPARK-55558) |
Native Apache Tuple sketches, with set operations | Nothing |
Schema-evolving INSERT and REPLACE ON (SPARK-54971, SPARK-56001) |
Engine syntax that a connector must implement | A connector |
Data Source V2 transactions (SPARK-55855) |
Commit several operations atomically | A connector |
Stable streaming source names (SPARK-54909) |
DataStreamReader.name() and IDENTIFIED BY let sources be added, removed and reordered without a new checkpoint |
Nothing |
State store repair and checksums (SPARK-54121, SPARK-54106) |
Automatic snapshot repair and row checksums that detect corruption | Nothing |
Spark Connect (SPARK-55606, SPARK-55887) |
The GetStatus API, RDD API compatibility, and head, take and tail without a full scan |
Nothing |
Web UI rebuilt on Bootstrap 5 (SPARK-55760) |
Dark mode, searchable and zoomable SQL plans, side-by-side initial and final plans | Nothing |
Kubernetes (SPARK-55555, SPARK-56603) |
Heterogeneous executors with resize plugins, and a stable resource manager API | Nothing |
Java 25 and security hardening (SPARK-51167, SPARK-57066) |
Build and run on Java 25; constant-time comparison of authentication secrets | Nothing |
Smaller additions in code
Pipe syntax. The | token and AGGREGATE work. Runnable file: 24_pipe_and_small_additions.sql, which also holds the PIVOT alias, DROP TABLE and max_by examples.
SELECT * FROM VALUES (1, 'eu', 10.0D), (2, 'us', 20.0D), (3, 'eu', 30.0D) AS t(id, region, amount)
| WHERE amount > 5
| AGGREGATE sum(amount) AS total GROUP BY region
| ORDER BY region;
-- eu 40.0
-- us 20.0
PIVOT alias and DROP TABLE on a view. A pivot result can be named, and a view can be dropped with DROP TABLE:
SELECT * FROM (SELECT * FROM VALUES ('a', 'x', 1), ('a', 'y', 2), ('b', 'x', 3) AS t(k, c, v))
PIVOT (sum(v) FOR c IN ('x', 'y')) AS p ORDER BY k;
-- a 1 2
-- b 3 NULL
CREATE VIEW v1 AS SELECT 1 AS a;
DROP TABLE v1;
Top-K max_by. The third argument is K:
SELECT max_by(name, score, 2) FROM VALUES ('a', 1), ('b', 3), ('c', 2) AS t(name, score);
-- ["b","c"]
DataFrame.zipWithIndex. The new column is named index. Runnable file: 25_zip_with_index.py.
df = spark.createDataFrame([("a",), ("b",), ("c",)], "v string")
df.zipWithIndex().show()
# +---+-----+
# | v|index|
# +---+-----+
# | a| 0|
# | b| 1|
# | c| 2|
# +---+-----+
Version lineage
Several 4.2 features build on earlier releases. Read the 4.2 column as what this release added.
| Feature | 4.0 | 4.1 | 4.2 |
|---|---|---|---|
| Geospatial types | none | none (GEOSPATIAL_DISABLED on 4.1.3) |
Introduced, on by default (SPARK-51658, SPARK-56771) |
| Top-K and vector search | none | none | NEAREST BY, vector functions (SPARK-56395, SPARK-54713) |
| Procedural SQL | Session variables, SQL UDFs (SPARK-42849, SPARK-46057) |
SQL scripting generally available (SPARK-54499) |
Cursors, behind flags (SPARK-54759) |
| Window and time-series SQL | none | none | QUALIFY, time_bucket (SPARK-31561, SPARK-56594) |
| Names and views | none | none | SET PATH, metric views (SPARK-54806, SPARK-54119) |
| Change data and history | none | Declarative Pipelines (SPARK-51727) |
CHANGES clause, Auto CDC SCD Type 1 (SPARK-55668, SPARK-56249) |
| Real-time mode | none | Stateless, Scala, Kafka (SPARK-53736) |
PySpark trigger (SPARK-54660) |
| Python UDFs | Polymorphic Python UDTFs | Arrow UDF decorators (SPARK-52214) |
Arrow-optimized UDFs on by default (SPARK-54555) |
Settings and costs
| Setting | Default | What it does |
|---|---|---|
spark.sql.path.enabled |
false |
The SET PATH statement |
spark.sql.scripting.cursorEnabled |
false, internal, since 4.2.0 |
DECLARE CURSOR, OPEN, FETCH, CLOSE |
spark.sql.scripting.continueHandlerEnabled |
false, internal, since 4.1.0 |
The handler a cursor loop needs |
spark.sql.execution.pythonUDF.arrow.enabled |
true |
Python UDFs exchange data through Arrow |
spark.sql.execution.arrow.pyspark.enabled |
true |
Arrow-based exchange between the JVM and PySpark |
spark.sql.shuffle.partitions |
200 |
For real-time mode, the number of task slots the cluster can run at once |
| Feature | Cost to plan for |
|---|---|
NEAREST BY |
The current implementation evaluates the full cross product of the two sides, so its work grows with left rows times right rows times the log of k. Pre-filter the right side |
| Vector functions | Exact results row by row. They are not an approximate-nearest-neighbour index |
| Arrow-optimized Python UDFs | Types, nulls and timestamps are where the new exchange path can differ from the old. Test your own UDFs |
| Metric views | The documentation has no page for the syntax, so you depend on the project’s tests and release notes |
| Change data capture and Auto CDC | The connector decides whether the feature exists for your table |
| Real-time mode in PySpark | One free task slot per task across all stages, held for the life of the query |
| Cursors | Internal flags, so the behaviour can change without notice |
When these features bite
These are the errors you’re most likely to hit, with the text Spark prints so you can search for it. Each one has its own anchor, so you can link straight to it.
[UNSUPPORTED_FEATURE.GEOSPATIAL_DISABLED] on 4.1.3. Geospatial types are off before 4.2. Fix: On by default from 4.2.
type expected at the position 4 of 'int:geometry(4326)' but 'geometry' is found. A table in the Hive metastore can’t hold a geometry column. Fix: Write Parquet files by path with INSERT OVERWRITE DIRECTORY ... USING parquet.
[UNSUPPORTED_FEATURE.SET_PATH_WHEN_DISABLED]. SET PATH is behind a flag. Fix: spark.sql.path.enabled=true.
[UNSUPPORTED_FEATURE.CHANGE_DATA_CAPTURE]. The engine defines CHANGES, but the catalog, here spark_catalog, doesn’t implement change data capture. The same shape applies to schema-evolving INSERT and Data Source V2 transactions. Fix: Check that your connector implements the feature before you plan around it.
[UNSUPPORTED_FEATURE.SQL_CURSOR], then [UNSUPPORTED_FEATURE.CONTINUE_EXCEPTION_HANDLER]. Cursors and CONTINUE handlers each have an internal flag in 4.2. Fix: Set spark.sql.scripting.cursorEnabled and spark.sql.scripting.continueHandlerEnabled, and keep cursors out of production.
[PARSE_SYNTAX_ERROR] on the first line of a BEGIN ... END script run with spark-sql -f. The spark-sql -f command splits the file at each ;, so a script is cut into pieces. Fix: Run the script through spark.sql(...) in Scala or Python. The 4.3.0 CLI ran the same file.
[DATATYPE_MISMATCH.UNEXPECTED_INPUT_TYPE] on vector_norm(..., 2.0D). The degree must be a FLOAT. Fix: Write 2.0F.
[UNSUPPORTED_FEATURE.TABLESAMPLE_SYSTEM_NO_SCAN]. TABLESAMPLE SYSTEM needs a direct reference to a source that supports block-level sampling. It fails on a view and on a Parquet table. Fix: Use a source that supports it.
RuntimeWarning: Arrow optimization failed to enable because PyArrow or Pandas is not installed. The official image has no PyArrow or pandas, so Python UDFs use the old path. Fix: Install pyspark[sql], or add PyArrow and pandas to the image.
TypeError: unsupported operand type(s) ... 'type' and 'type' from a Python worker. The 4.2 tarball declares Python 3.10 or newer, and the workers started with Python 3.9. Fix: Use a newer interpreter, and point PYSPARK_PYTHON at it.
Upgrade checklist: what can break
Most upgrades are a version bump, but check Python, connector jars and the behaviour changes below first, and run the list on a staging copy of your heaviest job.
1. Runtime and dependencies
| Requirement | 4.2 value | Source |
|---|---|---|
| Python | 3.10 or newer | requires_python of pyspark==4.2.1 on PyPI |
pandas, PyArrow, NumPy (pyspark[sql]) |
2.2.0, 18.0.0 and 1.21 or newer | requires_dist on PyPI |
pyspark[connect] extras |
grpcio and grpcio-status 1.76.0 or newer, zstandard 0.25.0 or newer | requires_dist on PyPI |
| Scala | 2.13 only, as for all of 4.x | Maven Central |
| Java | 17, 21 or 25 | Spark 4.2.1 overview, and the release notes (SPARK-51167) for 25 |
| R | 3.x is dropped | the release notes (SPARK-57767) |
| Kafka connector | spark-sql-kafka-0-10_2.13:4.2.1 is published |
Maven Central |
2. Check every connector jar before you upgrade
Connector runtimes are built per Spark minor version, so a jar built for 4.1 doesn’t mean there is one for
4.2. List the artifacts from your spark.jars.packages and ask Maven Central whether each has a 4.2.1
build, so you learn about a missing one before the cluster does.
import urllib.request
# group, artifact: edit to match your spark.jars.packages
ARTIFACTS = [
("org.apache.spark", "spark-sql-kafka-0-10_2.13"),
("org.apache.spark", "spark-avro_2.13"),
]
SPARK = "4.2.1"
for group, artifact in ARTIFACTS:
base = f"https://repo1.maven.org/maven2/{group.replace('.', '/')}/{artifact}"
try:
urllib.request.urlopen(f"{base}/{SPARK}/{artifact}-{SPARK}.pom", timeout=10)
print(f"OK {artifact}:{SPARK}")
except Exception:
print(f"MISSING {artifact} -> no {SPARK} build published")
Runnable file: 26_check_maven_artifacts.py. The output:
OK spark-sql-kafka-0-10_2.13:4.2.1
OK spark-avro_2.13:4.2.1
For third-party connectors, the artifact name carries the Spark line, so use the name the project documents
for 4.2. A MISSING line means keep those jobs on their current Spark version.
3. Behaviour changes to test
The first rows come from the 4.2 release notes; the rest come from the official SQL and PySpark migration guides, which list more.
| Change | What to do | Source |
|---|---|---|
Python UDFs and UDTFs use Arrow by default, and spark.sql.execution.arrow.pyspark.enabled is true |
Run your UDFs. spark.sql.execution.pythonUDF.arrow.enabled=false and pythonUDTF.arrow.enabled=false restore the old path |
SPARK-54555 |
| The minimum PyArrow is 18.0.0, and PyPy is no longer officially supported | Check the Python environment | PySpark migration guide |
| Order-independent shuffle checksums are on, and a mismatch rolls back and re-runs dependent stages | spark.sql.shuffle.orderIndependentChecksum.enabled=false and ...enableFullRetryOnMismatch=false restore |
SQL migration guide |
Pandas UDFs receive nullable integer columns as Int8 to Int64, not float64 |
Retest UDFs that handle nulls | PySpark migration guide |
option(None) is treated as unset, and Python data sources whose Arrow types miss the declared schema fail with DATA_SOURCE_RETURN_SCHEMA_MISMATCH |
Pass "" to set an empty string; fix the schema |
PySpark migration guide |
NOT NULL is enforced on inserts into the built-in file sources |
A pipeline that wrote nulls into a NOT NULL column can now fail |
SPARK-55716 |
DROP TABLE can drop a view |
A script that relied on DROP TABLE failing for a view behaves differently |
SPARK-55019 |
collect_set dedupes NaN and -0.0 by Spark equality, and array set operations normalise them |
Recheck results that contain floating-point edge values | SPARK-57298, SPARK-54918 |
| Per-write options take precedence over session configuration in file source writes, and dynamic partition overwrite replaces partitions | Recheck write options and overwrite jobs | SPARK-56414, SPARK-56588 |
The Postgres JDBC source has a default fetchSize |
Recheck large reads | SPARK-56251 |
NATURAL JOIN honours spark.sql.caseSensitive; duplicate CTE names are rejected case-insensitively with DUPLICATED_CTE_NAMES |
Recheck join keys; rename CTEs | SQL migration guide |
A SQL UDF parameter no longer shadows a parameterless built-in such as current_date; SET CATALOG name resolves a session variable first |
spark.sql.legacy.allowUdfParameterToShadowParameterlessFunction=true, or rename; use SET CATALOG 'name' |
SQL migration guide |
Observation.get raises the underlying error instead of returning an empty result |
Add error handling | SQL migration guide |
builtin.func() and session.func() try the system namespace first |
spark.sql.legacy.persistentCatalogFirst=true restores |
SQL migration guide |
4. Roll out in this order
- Python first. Move to Python 3.10 or newer, with PyArrow 18.0.0 or newer, on your current Spark version. The change is independent and easy to reverse.
- Python UDFs. Run them with the Arrow setting on and compare outputs and null handling.
- Connectors. Run the script above. Leave any job whose connector is missing on its current Spark version.
- Batch jobs. Move stateless batch jobs to 4.2 and compare outputs and runtimes.
- Streaming jobs last. Restart a copy of each job from a copy of its existing checkpoint in staging first, and keep the old checkpoint and the old Spark version until that run passes.
5. Common mistakes
- Assuming the Arrow default applies on every image. Without PyArrow and pandas, Spark falls back and warns.
- Expecting a distance function on
GEOMETRY. Only five spatial functions exist. - Running
NEAREST BYagainst a large right side. It evaluates the full cross product, so filter first. - Running
CHANGESor Auto CDC against a Parquet table. The connector has to implement the capability. - Forgetting a flag.
SET PATHis off by default, and cursors need two internal flags. - Planning for a short maintenance window. The versioning policy keeps the 18-month maintenance window for 4.2.x.
Known limitations in this release
- Change data capture.
CHANGESand Auto CDC need a connector with the capability. On a built-in Parquet tableCHANGESfails withUNSUPPORTED_FEATURE.CHANGE_DATA_CAPTURE, and Auto CDC needs row-level operations. - Auto CDC. The API accepts SCD Type 1 only, and it’s a Python and Spark Connect API with no SQL syntax.
- Geospatial. Five functions exist, and none measures distance or containment, so the types are for storing and exchanging spatial data. A metastore table can’t hold the column, so write Parquet files by path.
- Search.
NEAREST BYevaluates the full cross product and the vector functions are exact, not approximate, so neither replaces a vector index. - Metric views and cursors. The metric-view syntax comes from the project’s tests, not the documentation, and its YAML is version
0.1. Cursors need two internal flags and can’t be run throughspark-sql -f. - Real-time mode in PySpark. Stateless queries only, with no Python UDF, over a Kafka source in
updatemode. - Connector features. Schema-evolving
INSERT, Data Source V2 transactions andTABLESAMPLE SYSTEMare engine syntax that depends on the source.
Cheat sheet

Image 28: The syntax of each feature and what has to be on first.
Download the cheat sheet as a PNG.
Frequently Asked Questions
What is new in Apache Spark 4.2?
Spark 4.2.0, released on 14 July 2026, adds geospatial types, the NEAREST BY join, vector functions, QUALIFY, SET PATH, metric views, time_bucket, the CHANGES clause, Auto CDC with SCD Type 1, SQL cursors, Arrow as the default for Python UDFs, and the real-time trigger in PySpark.
Which features work without a flag?
Geospatial types, NEAREST BY, the vector functions, QUALIFY, metric views, time_bucket and DataFrame.zipWithIndex run as they are. SET PATH needs spark.sql.path.enabled, and cursors need two internal flags. CHANGES and Auto CDC run only on a connector that supports them.
Does Spark 4.2 have geospatial distance functions?
No. It has the GEOMETRY and GEOGRAPHY types, an SRID registry and Parquet support, with five functions: st_asbinary, st_geogfromwkb, st_geomfromwkb, st_setsrid and st_srid.
Why is my NEAREST BY join slow?
Evaluation is brute force: it computes the full cross product of the two sides. Filter the right side before the join, and treat APPROX as a hint for a faster strategy once one exists.
Why does SET PATH fail with SET_PATH_WHEN_DISABLED?
The feature is off by default. Set spark.sql.path.enabled=true first.
Can I run CHANGES on a Parquet table?
No. Spark defines the syntax, and the catalog has to implement the change feed. On a built-in Parquet table the clause fails with UNSUPPORTED_FEATURE.CHANGE_DATA_CAPTURE.
Does Auto CDC support SCD Type 2 in 4.2?
No. create_auto_cdc_flow accepts only SCD Type 1, and there’s no SQL syntax for it.
Why did my Python UDF return different values after upgrading?
Arrow is the default path in 4.2, and the two paths coerce types differently. A UDF declared int that returned str(x) gave NULL on the old path and the number on the Arrow path. Set spark.sql.execution.pythonUDF.arrow.enabled=false while you fix the function.
Why does the Arrow default not apply on the official Docker image?
The apache/spark:4.2.1-python3 image has no PyArrow or pandas, so Spark falls back to the old path and warns. Install pyspark[sql], or add both packages.
Is real-time mode in PySpark stateful?
No. In 4.2 it runs stateless queries over a Kafka source in update mode, without Python UDFs, and it keeps no state.
Which Spark 4.2 release should I use?
4.2.1 is the latest 4.2 release. The versioning policy keeps the 18-month maintenance window for 4.2.x.
Why does pip install pyspark==4.2.1 fail?
The wheel requires Python 3.10 or newer. Check python3 --version.
Summary
Spark 4.2 is mostly about the engine taking over work you used to do by hand. Spatial values finally have types, similarity search and top-K matching work in plain SQL, and QUALIFY, time_bucket, SET PATH and metric views tidy up everyday queries. Most of these need nothing from you. A few need a flag, and the change data capture features need a connector, so check your table format before you plan around them.
If you only test one thing before upgrading, make it your Python UDFs. The Arrow default is the change most likely to surprise a pipeline.
Further reading
- Spark 4.2.0 release notes, the source of every ticket number above
- JOIN syntax, including
NEAREST BYin the SQL reference QUALIFYin the SQL referenceSPARK-51658, the geospatial types, andSPARK-55668, change data capture- The versioning policy, for the 4.2.x maintenance window
ChangelogEndToEndSuiteandAutoCdcScd1SinglePipelineSuitein the Spark 4.2.1 source tree, the tests the change data capture examples follow- What’s new in Apache Spark 4.3 for the release after this one
- Spark 4.x features by release for all four releases side by side
Trademarks
Apache Spark, Apache Kafka, Apache Parquet, Apache Arrow and Apache are either registered trademarks or trademarks of The Apache Software Foundation in the United States and other countries. The Apache Software Foundation doesn’t endorse this post.
Found this useful?
These posts and tools are free. If one saved you an afternoon, you can buy me a coffee.
Comments
Questions, corrections and reviews are welcome. Sign in with GitHub to post; comments are stored in this site's public GitHub Discussions.