Jump to content

Python data source API (Spark)

From Open Lakehouse Wiki
Revision as of 00:52, 25 November 2026 by Open Lakehouse Wiki sync (talk | contribs) (Sync from open-lakehouse/wiki@7c9abaa)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Python data source API (Spark)
Also known as Python Data Source API, PySpark data source, pyspark.sql.datasource
Field Data integration, distributed data processing
Introduced Apache Spark 4.0.0 (SPIP SPARK-44076)
Key parts DataSource, DataSourceReader, DataSourceWriter, DataSourceStreamReader, SimpleDataSourceStreamReader, DataSourceStreamWriter, InputPartition
Open source implementations Apache Spark (PySpark)
Related Structured Streaming, Predicate pushdown, Apache Arrow, Python UDTF
Last verified 23 November 2026 against the v4.3.0 tag of apache/spark (the PySpark Python Data Source tutorial, python/pyspark/sql/datasource.py, SQLConf.scala, the PySpark migration guide) and the Spark 4.0.0, 4.1.0 and 4.2.0 release notes.

The Python data source API of Apache Spark is a set of PySpark base classes, in the module pyspark.sql.datasource, for writing a custom data source or sink entirely in Python and using it with spark.read, df.write, spark.readStream and writeStream.[1] The API was introduced in Spark 4.0.0 under the improvement proposal SPARK-44076.[1][2]

How does a Python data source work?

A Python data source is a subclass of DataSource. It gives a short name() used in format(...), an optional default schema(), and one factory method per capability.[1]

Source (read) Sink (write)
Batch reader() returns a DataSourceReader writer() returns a DataSourceWriter
Streaming streamReader() returns a DataSourceStreamReader, or simpleStreamReader() returns a SimpleDataSourceStreamReader streamWriter() returns a DataSourceStreamWriter

Source for the table: the PySpark 4.3.0 Python Data Source tutorial.[1]

A batch reader can implement partitions() to return a list of InputPartition objects; if it returns N partitions, Spark plans N tasks that run read(partition) in parallel, and by default there is a single partition.[3] read yields tuples or Row objects, or PyArrow RecordBatch objects.[1] The tutorial says that yielding Arrow record batches avoids row-by-row processing and can improve performance by up to an order of magnitude on large datasets.[1]

The data source, reader and writer classes and their methods must be picklable, because Spark ships them to executors. Libraries used inside a method must be imported inside that method.[1]

Example: a batch reader

The following PySpark example works on Spark 4.3.0. It defines a source named simple that returns two rows.

from pyspark.sql.datasource import DataSource, DataSourceReader
from pyspark.sql.types import StructType

class SimpleDataSource(DataSource):
    @classmethod
    def name(cls):
        return "simple"

    def schema(self):
        return "name string, age int"

    def reader(self, schema: StructType):
        return SimpleReader()

class SimpleReader(DataSourceReader):
    def read(self, partition):
        yield ("Alice", 20)
        yield ("Bob", 30)

spark.dataSource.register(SimpleDataSource)
spark.read.format("simple").load().show()

Options passed with .option(...) reach the source as self.options, a dictionary whose values are all strings. A caller can override the default schema with .schema(...).[1]

How do writers commit data?

A DataSourceWriter implements write(rows), which runs in each task and returns a WriterCommitMessage. After all tasks succeed, Spark calls commit(messages) on the driver with the messages from every task; if any task fails, it calls abort(messages).[1] Batch writes support the append and overwrite modes.[1] Spark 4.0.0 also added DataSourceArrowWriter, which receives PyArrow record batches instead of rows (SPARK-50471).[3][2]

How do streaming readers work?

A Python data source can act as a Structured Streaming source. A DataSourceStreamReader tracks progress with offsets, which are dictionaries:[1]

  • initialOffset() returns the starting offset.
  • latestOffset() returns the offset that the next micro-batch reads up to.
  • partitions(start, end) splits the range between two offsets into InputPartition objects.
  • read(partition) yields the rows of one partition on an executor.
  • commit(end) is called after the query has processed data up to end, and can release resources.

SimpleDataSourceStreamReader is a lighter interface for low-throughput sources that do not need partitioning: read(start) returns both the rows and the next offset, and readBetweenOffsets(start, end) must return the same rows deterministically when Spark replays a batch after a restart or failure.[1] Since Spark 4.2, a simple reader that returns rows without advancing the offset fails with SIMPLE_STREAM_READER_OFFSET_DID_NOT_ADVANCE.[4]

Spark 4.2.0 added admission control and Trigger.AvailableNow support to Python streaming readers (SPARK-55304). A reader implements getDefaultReadLimit(), for example returning ReadMaxRows(20), and its latestOffset(start, limit) must honour the ReadLimit that Spark passes in.[1][5]

A DataSourceStreamWriter has write, commit(messages, batchId) and abort(messages, batchId), so a sink can commit each micro-batch as a unit.[1] An Arrow-based variant, DataSourceStreamArrowWriter, was added in Spark 4.1.0.[3]

Does the Python data source API support filter pushdown?

Spark 4.1.0 added a filter pushdown API (SPARK-51271).[6] A DataSourceReader can override pushFilters(filters), which Spark calls once during planning with filter objects such as EqualTo, GreaterThan, In, IsNull and StringStartsWith; the method returns the filters that Spark must still evaluate after the scan. The API documentation recommends it only for sources that filter natively, such as databases.[3] In Spark 4.3.0 the pushdown is controlled by the internal configuration spark.sql.python.filterPushdown.enabled, which defaults to false because it runs the Python worker one more time during planning.[7] See Predicate pushdown.

How is a Python data source registered?

spark.dataSource.register(MyDataSource) registers a source for the current session (SPARK-45600).[1][2] Registering a second source with the same name overwrites the first. Built-in and Scala or Java sources take precedence over a Python source with the same name.[1]

A package can register a source automatically by exporting it as DefaultSource in a top-level module whose name starts with pyspark_; the tutorial cites the pyspark_huggingface package as an example.[1] Spark 4.0.0 also added Python data sources for Spark Connect clients (SPARK-47367), creating tables with a Python data source in SQL (SPARK-45597), and Python metrics (SPARK-46424).[2]

Since Spark 4.2, a source whose returned Arrow data has column types that do not match its declared schema fails with DATA_SOURCE_RETURN_SCHEMA_MISMATCH.[4]

See also

References

  1. ↑ 1.00 1.01 1.02 1.03 1.04 1.05 1.06 1.07 1.08 1.09 1.10 1.11 1.12 1.13 1.14 1.15 1.16 Python Data Source API (PySpark 4.3.0). Apache Software Foundation.Retrieved 2026-11-23.
  2. ↑ 2.0 2.1 2.2 2.3 Spark Release 4.0.0. Apache Software Foundation.Retrieved 2026-11-23.
  3. ↑ 3.0 3.1 3.2 3.3 python/pyspark/sql/datasource.py (v4.3.0). Apache Software Foundation.Retrieved 2026-11-23.
  4. ↑ 4.0 4.1 Upgrading PySpark (PySpark 4.3.0 migration guide). Apache Software Foundation.Retrieved 2026-11-23.
  5. ↑ Spark Release 4.2.0. Apache Software Foundation.Retrieved 2026-11-23.
  6. ↑ Spark Release 4.1.0. Apache Software Foundation.Retrieved 2026-11-23.
  7. ↑ SQLConf.scala (v4.3.0). Apache Software Foundation.Retrieved 2026-11-23.