Bird
Raised Fist0
Apache Sparkdata~20 mins

Structured Streaming basics in Apache Spark - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Structured Streaming Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of a simple streaming aggregation
What will be the output of the following Structured Streaming code snippet after processing the input data?
Apache Spark
from pyspark.sql import SparkSession
from pyspark.sql.functions import window, col

spark = SparkSession.builder.appName('Test').getOrCreate()

# Simulated streaming input
input_data = spark.readStream.format('rate').option('rowsPerSecond', 1).load()

# Aggregate count of rows per 10 second window
agg = input_data.groupBy(window(col('timestamp'), '10 seconds')).count()

query = agg.writeStream.format('console').outputMode('complete').start()

query.processAllAvailable()
query.stop()
AA syntax error due to missing import for window function.
BA runtime error because 'rate' source cannot be used with window aggregation.
CAn empty output because no data is processed in batch mode.
DA table printed to console showing counts of rows grouped by 10-second windows, with counts increasing over time.
Attempts:
2 left
💡 Hint
Think about how the 'rate' source generates data and how window aggregation works in streaming.
❓ data_output
intermediate
1:30remaining
Number of rows in streaming output with append mode
Given a streaming DataFrame reading from a socket source with the following code, how many rows will be output after processing 3 lines of input if the output mode is 'append'?
Apache Spark
from pyspark.sql import SparkSession

spark = SparkSession.builder.appName('SocketTest').getOrCreate()

lines = spark.readStream.format('socket').option('host', 'localhost').option('port', 9999).load()

query = lines.writeStream.format('console').outputMode('append').start()

# Assume 3 lines are sent to the socket
query.processAllAvailable()
query.stop()
A3 rows, one for each line received from the socket.
B0 rows, because append mode does not output any data.
C1 row, summarizing all 3 lines.
DAn error because socket source does not support append mode.
Attempts:
2 left
💡 Hint
Append mode outputs only new rows as they arrive.
🔧 Debug
advanced
2:00remaining
Identify the error in this streaming query
What error will this Structured Streaming code produce when executed?
Apache Spark
from pyspark.sql import SparkSession

spark = SparkSession.builder.appName('ErrorTest').getOrCreate()

input_stream = spark.readStream.format('jdbc').option('header', 'true').load('/path/to/folder')

query = input_stream.writeStream.format('console').outputMode('append').start()

query.processAllAvailable()
query.stop()
ANo error, the query runs successfully and outputs data.
BRuntimeException due to missing checkpoint location.
CAnalysisException because 'jdbc' format does not support streaming source.
DFileNotFoundError because the folder path does not exist.
Attempts:
2 left
💡 Hint
Check if the 'jdbc' format supports streaming input.
🧠 Conceptual
advanced
1:00remaining
Understanding output modes in Structured Streaming
Which output mode should be used to update only the rows that have changed in a streaming aggregation query?
AComplete mode
BUpdate mode
CAppend mode
DOverwrite mode
Attempts:
2 left
💡 Hint
Think about which mode outputs only changed rows without re-outputting all data.
🚀 Application
expert
2:30remaining
Predict the output schema of a streaming aggregation
Given the following streaming aggregation code, what will be the schema of the output DataFrame?
Apache Spark
from pyspark.sql import SparkSession
from pyspark.sql.functions import window, col

spark = SparkSession.builder.appName('SchemaTest').getOrCreate()

input_stream = spark.readStream.format('rate').load()

agg = input_stream.groupBy(window(col('timestamp'), '5 minutes'), (col('value') % 10).alias('mod_value')).count()

# What is the schema of 'agg'?
AStructType with fields: window (Struct with start and end timestamps), (value % 10) as long, count as long
BStructType with fields: timestamp, value, count
CStructType with fields: window (string), value (string), count (integer)
DStructType with fields: timestamp (timestamp), count (integer)
Attempts:
2 left
💡 Hint
Consider the groupBy keys and aggregation columns.

Practice

(1/5)
1. What is the main purpose of Structured Streaming in Apache Spark?
easy
A. To visualize data using charts and graphs
B. To batch process large static datasets
C. To store data permanently in a database
D. To process live data continuously as it arrives

Solution

  1. Step 1: Understand Structured Streaming concept

    Structured Streaming is designed to handle data streams, meaning data that arrives continuously over time.
  2. Step 2: Compare with other options

    Batch processing handles static data, storing data is not the main function, and visualization is separate from streaming.
  3. Final Answer:

    To process live data continuously as it arrives -> Option D
  4. Quick Check:

    Structured Streaming = continuous live data processing [OK]
Hint: Streaming means live, continuous data processing [OK]
Common Mistakes:
  • Confusing streaming with batch processing
  • Thinking streaming stores data permanently
  • Assuming streaming is for visualization
2. Which of the following is the correct way to start reading a streaming DataFrame in Spark?
easy
A. spark.read.format("json").load("path")
B. spark.readStream.format("json").load("path")
C. spark.writeStream.format("json").load("path")
D. spark.write.format("json").load("path")

Solution

  1. Step 1: Identify streaming read syntax

    To read streaming data, use readStream with format and load.
  2. Step 2: Eliminate non-streaming options

    read is for batch, writeStream is for output, so only readStream with load is correct.
  3. Final Answer:

    spark.readStream.format("json").load("path") -> Option B
  4. Quick Check:

    Streaming read uses readStream [OK]
Hint: Use readStream to read streaming data [OK]
Common Mistakes:
  • Using read instead of readStream for streaming data
  • Confusing writeStream with readStream
  • Using writeStream with load instead of start
3. Given the code below, what will be the output schema of the streaming DataFrame?
df = spark.readStream.format("csv").option("header", "true").load("/data/clicks")
df.printSchema()
medium
A. Schema with columns inferred as integers only
B. Schema with no columns because streaming can't infer schema
C. Schema with columns inferred from CSV header as strings
D. Error because schema must be specified explicitly

Solution

  1. Step 1: Understand schema inference in streaming CSV

    When reading CSV with header option true, Spark infers schema as strings by default for streaming.
  2. Step 2: Check if explicit schema is required

    Explicit schema is recommended but not mandatory; Spark infers schema as string types if not provided.
  3. Final Answer:

    Schema with columns inferred from CSV header as strings -> Option C
  4. Quick Check:

    CSV header + streaming = inferred string schema [OK]
Hint: CSV header enables schema inference as strings [OK]
Common Mistakes:
  • Assuming streaming can't infer schema
  • Expecting integer types without schema
  • Thinking explicit schema is always required
4. Identify the error in the following Structured Streaming code:
streamDF = spark.readStream.format("json").load("/data/events")
query = streamDF.writeStream.format("console").start()
query.awaitTermination(10)
medium
A. Missing option to specify output mode in writeStream
B. awaitTermination does not take any arguments
C. Incorrect format 'console' should be 'Console'
D. start() must be called after awaitTermination()

Solution

  1. Step 1: Check writeStream requirements

    In Structured Streaming, writeStream requires outputMode() (e.g., "append") to be specified before format() for sinks like console.
  2. Step 2: Verify other parts

    awaitTermination(10) accepts a timeout argument, format 'console' is correct lowercase, and start() must be called before awaitTermination().
  3. Final Answer:

    Missing option to specify output mode in writeStream -> Option A
  4. Quick Check:

    writeStream requires outputMode [OK]
Hint: writeStream requires outputMode [OK]
Common Mistakes:
  • Missing outputMode in writeStream
  • Thinking awaitTermination does not take timeout
  • Misusing start and awaitTermination order
5. You want to count the number of words in a live stream of text lines from a socket source. Which sequence of operations correctly applies Structured Streaming to achieve this?
hard
A. Read stream from socket, split lines into words, group by word, count, write stream to console
B. Read batch from socket, split lines into words, group by word, count, write batch to file
C. Read stream from socket, count lines directly, write stream to console
D. Read stream from socket, split lines into words, filter empty words, write batch to console

Solution

  1. Step 1: Understand streaming word count steps

    Streaming word count requires reading live data, splitting lines into words, grouping by word, and counting occurrences continuously.
  2. Step 2: Check options for correctness

    Read stream from socket, split lines into words, group by word, count, write stream to console follows the correct streaming steps with writeStream to console. Read batch from socket, split lines into words, group by word, count, write batch to file uses batch, not streaming. Read stream from socket, count lines directly, write stream to console counts lines, not words. Read stream from socket, split lines into words, filter empty words, write batch to console writes batch, not stream, and misses counting.
  3. Final Answer:

    Read stream from socket, split lines into words, group by word, count, write stream to console -> Option A
  4. Quick Check:

    Streaming word count = readStream + split + groupBy + count + writeStream [OK]
Hint: For streaming word count, use readStream + groupBy + count + writeStream [OK]
Common Mistakes:
  • Using batch read instead of streaming
  • Counting lines instead of words
  • Writing batch output instead of streaming
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard