readStream and writeStream

Concepts covered: Structured Streaming

Take a batch job you could write today. It reads the JSON files in a landing directory, keeps the requested rides, and writes them out as Parquet.

ride_schema = "ride_id LONG, zone STRING, status STRING"

rides = spark.read.schema(ride_schema).json("/landing/rides/")

requested = rides.where("status = 'requested'").select("ride_id", "zone")

requested.write.parquet("/tables/requested_rides/")

The streaming version keeps the middle line untouched and changes the 2 ends.

rides = spark.readStream.schema(ride_schema).json("/landing/rides/")

requested = rides.where("status = 'requested'").select("ride_id", "zone")

query = (
    requested.writeStream
    .format("parquet")
    .option("path", "/tables/requested_rides/")
    .option("checkpointLocation", "/progress/requested_rides/")
    .start()
)
PartBatchStreaming
Readspark.readspark.readStream
SchemaOptional, can be inferredRequired for a file source
Transformationswhere, selectThe same lines, unchanged
Writerequested.writerequested.writeStream
What starts the workAn action such as a writestart()
What the call returnsNothing, after the job endsA query handle, at once
When it endsWhen the files are readWhen it is stopped or fails

start() is the action

Lazy evaluation still holds. Calls like readStream and where build a plan and run nothing, and so does select. start() plays the role an action plays in batch code: it hands the plan to the driver, which begins the micro-batch loop. The difference is that start() returns immediately with a handle while the loop keeps running in the background.

That handle, query above, is how you talk to a running stream. query.status reports what the loop is doing now. query.lastProgress describes the most recent batch; it includes the batch number and how many rows that batch read. query.stop() ends the loop. query.awaitTermination() blocks the calling program until the stream stops, and a script needs it as its last line: without it the script reaches its end and the application exits, taking the stream with it.

One line in the write has no batch counterpart. A file sink requires a checkpointLocation, a directory where the query keeps notes on its own progress, and Spark refuses to start without one. Treat it as a required line for now; what goes into that directory is the subject of a later lesson.

Batch actions fail on a streaming DataFrame

rides in the streaming version is still a DataFrame, and rides.isStreaming returns True. The usual actions don't apply to it. Calling rides.count() or rides.show() raises an AnalysisException saying that queries with streaming sources must be executed with writeStream.start(), and so does rides.collect(). The reason follows from the growing-table model: count() promises one final number, and a table with no last row has none to give.

The middle runs anywhere

Because the transformations are identical, you can write and test them as a batch job over a table that has stopped growing. Swapping the ends comes after. The cell below runs a filter-and-select middle against the practice orders table, where 'Completed' plays the part of 'requested'.

Run it, then read the where and select lines again and ask what would change if orders came from spark.readStream. Neither line would need an edit, because the same filter would apply to each micro-batch's new rows. The only edit is replacing show() with a writeStream that ends in start().

To watch a real stream on a laptop, pair the 2 testing ends from the previous section. The rate source invents 5 rows a second, and the console sink prints each batch with its number.

ticks = spark.readStream.format("rate").option("rowsPerSecond", 5).load()

query = ticks.writeStream.format("console").start()
query.awaitTermination()

What happens when the second line of this program runs?

rides = spark.readStream.schema(ride_schema).json("/landing/rides/")
n = rides.where("status = 'requested'").count()

The translation, then, is short. On the read side read becomes readStream and a file source needs its schema declared. On the write side write becomes writeStream, with start() in place of the action. One choice is still open. Nothing in the code above says how often a batch should run.

About this lesson

This section is part of the Structured Streaming: Beginner lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.