Select, filter, and where operations in Apache Spark - Time & Space Complexity
We want to understand how the time to run select, filter, and where operations changes as the data grows.
How does the work increase when we have more rows in our data?
Analyze the time complexity of the following code snippet.
from pyspark.sql import SparkSession
spark = SparkSession.builder.getOrCreate()
df = spark.read.csv('data.csv', header=True, inferSchema=True)
filtered_df = df.filter(df['age'] > 30)
selected_df = filtered_df.select('name', 'age')
result = selected_df.where(selected_df['age'] < 50)
This code reads data, filters rows where age is over 30, selects only name and age columns, then filters again where age is less than 50.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Scanning each row to apply filter conditions.
- How many times: Each row is checked once per filter operation, so twice in total here.
As the number of rows grows, the time to check each row grows too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 checks (2 filters x 10 rows) |
| 100 | About 200 checks |
| 1000 | About 2000 checks |
Pattern observation: The number of operations grows roughly in direct proportion to the number of rows.
Time Complexity: O(n)
This means the time grows linearly with the number of rows in the data.
[X] Wrong: "Filtering multiple times multiplies the time complexity exponentially."
[OK] Correct: Each filter scans the data once, so time adds up linearly, not exponentially.
Understanding how filtering and selecting scale helps you explain data processing speed clearly and confidently.
"What if we added a join operation after the filters? How would the time complexity change?"
Practice
select operation do in Apache Spark DataFrame?Solution
Step 1: Understand the purpose of
Theselectselectoperation is used to pick specific columns from a DataFrame, reducing the data to only those columns.Step 2: Differentiate from filtering rows
Filtering rows is done byfilterorwhere, not byselect.Final Answer:
It chooses specific columns from the DataFrame. -> Option AQuick Check:
Select = Choose columns [OK]
- Confusing select with filter or where
- Thinking select filters rows
- Assuming select adds columns
age is greater than 30 in a Spark DataFrame df?Solution
Step 1: Understand filter syntax options
In Spark,filtercan accept either a column expression likedf.age > 30or a string condition like'age > 30'.Step 2: Recognize where is similar to filter
whereis an alias forfilterand accepts the same arguments.Final Answer:
All of the above -> Option CQuick Check:
filter and where accept column or string conditions [OK]
- Using wrong syntax like df.filter(age > 30) without df.
- Confusing filter with select syntax
- Thinking where is different from filter
df with columns name and age, what will be the output of this code?df.select('name').filter(df.age >= 25).show()Solution
Step 1: Analyze select operation
select('name')projects only thenamecolumn, resulting in a DataFrame schema of ['name'].Step 2: Analyze filter condition
filter(df.age >= 25)tries to use theagecolumn, butageis unavailable after select, causing a column resolution error.Final Answer:
Throws an error because of wrong syntax. -> Option DQuick Check:
Filter on unselected column after select = error [OK]
- Thinking filter applies before select due to lazy evaluation
- Expecting all columns to show
- Confusing syntax causing errors
df.filter(df['age'] > 20).select('name', 'age').where('age < 18').show()Solution
Step 1: Analyze filter condition
filter(df['age'] > 20)keeps rows where age is greater than 20.Step 2: Analyze where condition
where('age < 18')keeps rows where age is less than 18.Step 3: Identify contradiction
Rows cannot satisfy both conditions simultaneously, so the result will be empty or logically inconsistent.Final Answer:
The filter and where conditions contradict each other. -> Option BQuick Check:
Contradictory filters = no matching rows [OK]
- Thinking filter and where cannot be chained
- Assuming select must come first
- Ignoring logical contradictions in conditions
df with columns city, temperature, and humidity. You want to select only city and temperature columns, but only for rows where temperature is above 30 and humidity is below 50. Which code snippet correctly does this?Solution
Step 1: Filter rows first based on both conditions
We must first keep rows where temperature > 30 and humidity < 50. This is done byfilterorwherewith both conditions combined.Step 2: Select only the desired columns after filtering
After filtering, select onlycityandtemperaturecolumns to reduce data.Step 3: Check each option
A: selects first then filters ontemperatureandhumidity-> error (humidityunavailable).
B: selects first thenwherestring with both -> error (humidityunavailable).
C: filters first then selects -> correct.
D: selects first,whereontemperaturethenfilteronhumidity-> error.Final Answer:
df.filter((df.temperature > 30) & (df.humidity < 50)).select('city', 'temperature') -> Option AQuick Check:
Filter rows first, then select columns [OK]
- Selecting columns before filtering on columns not selected
- Splitting filter conditions incorrectly
- Using string conditions inconsistently
Ready to prove it?
Pass the test and this pattern moves unknown
