In the previous lesson you learnt to select, filter and aggregate over a single table. But the questions NovaMarket really cares about rarely fit in one: how much does each province sell? (orders and customers), which are the three star products in each category? (sales and catalogue), what percentage of the sessions that view a product end up buying? (events compared with one another).
This lesson brings together the three techniques that make Spark a complete analysis tool: joins, which combine tables; advanced aggregations, which summarise from several angles at once; and window functions, which compute over groups of rows without losing the detail. With them you will settle the debt outstanding since lesson 02-04, rebuilding the 200 amounts missing from the orders, and you will build NovaMarket's conversion funnel, one of its four use cases.
Joins: combining tables
A join combines the rows of two DataFrames that match on one or more columns, called the join key. The syntax is:
The how parameter decides what happens to the rows that find no match. To see it with real data we will use the 1,000 customers and the 3,226 orders from June; it so happens that 42 customers placed no order that month.
Type (how) |
What it returns | Customers ⟕ June orders |
|---|---|---|
inner (default) |
Only the rows with a match on both sides | 3,226 rows |
left |
All the rows on the left; if there is no match, the right-hand columns are null | 3,268 (3,226 + 42 customers with no order) |
right |
The same, keeping all the rows on the right | 3,226 (every order has a customer) |
full |
All the rows on both sides | 3,268 |
left_semi |
Rows on the left that have a match; left-hand columns only, without duplicates | 958 customers |
left_anti |
Rows on the left that have no match | 42 customers |
The first four add columns: the result has those of both tables. Notice that the inner join returns 3,226 rows, not 958: a customer with five orders appears five times. The last two only filter: left_semi answers "which customers bought in June?" and left_anti "which did not?", without multiplying rows or bringing in columns from the orders.
Create ~/novamarket/advanced_analysis.py with the base you will use throughout the lesson (you will create the orders_complete table in the next section; until then, leave that line commented out):
from pathlib import Path
from pyspark.sql import SparkSession, Window
from pyspark.sql import functions as F
LAKE = Path.home() / "novamarket" / "lake"
SILVER = LAKE / "silver"
GOLD = LAKE / "gold"
spark = SparkSession.builder.master("local[*]").appName("advanced_analysis").getOrCreate()
spark.sparkContext.setLogLevel("ERROR")
customers = spark.read.parquet(str(SILVER / "customers"))
events = spark.read.parquet(str(SILVER / "web_events"))
orders = spark.read.parquet(str(SILVER / "orders_complete"))
# ... snippets from the lesson ...
spark.stop()The case of the inactive customers, with an anti join:
june = orders.where("order_date >= '2026-06-01'")
inactive = customers.join(june, on="customer_id", how="left_anti")
print(inactive.count())
inactive.orderBy("customer_id").show(3)42 +-----------+------------+--------+-----------+ |customer_id| name|province|signup_date| +-----------+------------+--------+-----------+ | 24|Elena Ortega|Valencia| 2022-08-05| | 109| Elena Vidal| Madrid| 2022-04-18| | 123| Elena Gomez|Alicante| 2023-04-13| +-----------+------------+--------+-----------+ only showing top 3 rows
Three precautions with joins
- Nulls never match. A null key is not equal to anything, not even to another null. When joining
eventswithcustomersoncustomer_id, an inner join returns 139,316 of the 200,000 rows: the 60,684 events from anonymous visitors disappear without warning. If they must be kept, you have to useleft. - Joins can multiply rows. If the key is repeated on both sides, each row is paired with all those on the other side. Always check the
count()before and after a join when you expect a one-to-one or many-to-one relationship. - Columns with the same name become ambiguous. With
on="customer_id"(a name or a list of names), Spark leaves a single key column. If the keys have different names, you use a condition,a.join(b, a["id"] == b["customer_id"]), and the result keeps both. For any other repeated column (for example,namein customers and in products), rename it beforehand withwithColumnRenamed.
Hands-on: rebuilding the missing amounts
Since lesson 02-04, silver/orders has been carrying 200 orders with a null total_amount. Lesson 01-05 gave the key to repairing them: the amount of an order is the sum of quantity × unit_price over its lines. What is needed, therefore, is an aggregation (summing the lines of each order), a join (bringing that sum into the orders table) and a coalesce (using the sum only where the value is missing). Create rebuild_amounts.py:
from pathlib import Path
from pyspark.sql import SparkSession
from pyspark.sql import functions as F
SILVER = Path.home() / "novamarket" / "lake" / "silver"
spark = (
SparkSession.builder
.master("local[*]")
.appName("rebuild_amounts")
.getOrCreate()
)
spark.sparkContext.setLogLevel("ERROR")
orders = spark.read.parquet(str(SILVER / "orders"))
lines = spark.read.parquet(str(SILVER / "order_lines"))
# 1. Amount of each order computed from its lines
amounts = (
lines
.groupBy("order_id")
.agg(F.round(F.sum(F.col("quantity") * F.col("unit_price")), 2)
.alias("computed_amount"))
)
# 2. Join: each order gets its computed amount
joined = orders.join(amounts, on="order_id", how="left")
# 3. Quality check: does the computation match where there was an amount?
discrepancies = joined.where(
F.col("total_amount").isNotNull()
& (F.abs(F.col("total_amount") - F.col("computed_amount")) > 0.01)
).count()
print("Orders whose amount differs from the computed one:", discrepancies)
# 4. coalesce: the original amount if it exists; otherwise, the computed one
orders_complete = (
joined
.withColumn("amount_rebuilt", F.col("total_amount").isNull())
.withColumn("total_amount",
F.coalesce(F.col("total_amount"), F.col("computed_amount")))
.drop("computed_amount")
)
# 5. Saved as a new silver table and verified
target = str(SILVER / "orders_complete")
orders_complete.coalesce(1).write.mode("overwrite").parquet(target)
result = spark.read.parquet(target)
result.select(
F.count("*").alias("rows"),
F.count("total_amount").alias("with_amount"),
F.sum(F.col("amount_rebuilt").cast("int")).alias("rebuilt"),
).show()
result.where("amount_rebuilt").orderBy("order_id").show(3)
spark.stop()Step by step:
- Step 1.
groupBy("order_id")reduces the 50,107 lines to one row per order with its amount. - Step 2. The join is
leftas a precaution: if some order had no lines, aninnerjoin would remove it from the table. Withleftit is kept, with a null computed amount. - Step 3. Before trusting a computation to fill gaps, you check it where the answer is known: on the 19,800 orders that do have an amount. The comparison uses a tolerance of one cent, because floating-point decimals should not be compared for exact equality.
- Step 4.
F.coalesce(a, b)returns the first non-null value. Theamount_rebuiltcolumn is created before overwritingtotal_amount(afterwards there would be no nulls left to detect) and records which amounts are original and which are computed. - Step 5.
coalesce(1)writes a single file, which is appropriate for a small table (do not confuse this DataFrame method, which reduces partitions, with theF.coalescefunction from the previous step; they only share a name).
Orders whose amount differs from the computed one: 0 +-----+-----------+-------+ | rows|with_amount|rebuilt| +-----+-----------+-------+ |20000| 20000| 200| +-----+-----------+-------+ +--------+-----------+-------------------+------------+---------+-------+--------------+ |order_id|customer_id| order_date|total_amount| status|channel|amount_rebuilt| +--------+-----------+-------------------+------------+---------+-------+--------------+ | 6| 808|2026-01-01 00:51:32| 588.16|delivered| web| true| | 53| 418|2026-01-01 14:20:03| 1458.0|delivered| app| true| | 142| 120|2026-01-02 09:38:17| 202.04|delivered| web| true| +--------+-----------+-------------------+------------+---------+-------+--------------+ only showing top 3 rows
Zero discrepancies, 20,000 rows and not a single null. The sum of all the amounts goes from €33,216,763.43 to €33,550,768.43: the 200 orders with no amount were hiding €334,005 of sales.
Why a new table
The result is saved in silver/orders_complete and not on top of silver/orders, for two reasons:
- Overwriting a table while reading from it destroys it. Because of lazy evaluation, the source data has not yet been read when the write begins, and the first thing
mode("overwrite")does is delete the target. Depending on the version and the shape of the query, Spark either detects the situation and refuses to start, or fails to detect it: when this lesson was prepared with a recent version, the test ended with a "file not found" error and the source folder empty. Do not try it with data you cannot regenerate. The rule is simple: never write to the path you are reading from. - Traceability.
silver/ordersremains the direct cleaning of bronze, andorders_completea derived table with a business rule added. In a lakehouse with a table format (lesson 02-05), the same table would be updated with aMERGE, and the version history would provide that traceability.
From now on, all the order analyses in the course start from silver/orders_complete.
Advanced aggregations
Several metrics and counting distinct values
agg accepts as many measures as you need, even without groupBy, to summarise the whole table. Add to advanced_analysis.py:
events.agg(
F.countDistinct("session_id").alias("sessions"),
F.approx_count_distinct("session_id").alias("approx_sessions"),
F.countDistinct("customer_id").alias("customers"),
F.max("event_time").alias("last_event"),
).show()+--------+---------------+---------+-------------------+ |sessions|approx_sessions|customers| last_event| +--------+---------------+---------+-------------------+ | 30759| 30824| 1000|2026-07-01 00:16:37| +--------+---------------+---------+-------------------+
countDistinct gives the exact number of distinct values, but it is an expensive operation: it forces all the values to be brought together to compare them. approx_count_distinct estimates it with an algorithm (HyperLogLog) that uses a small, fixed amount of memory. Here it is off by 0.2% (30,824 versus 30,759). With 40 million events a day, and for a dashboard where it makes no difference whether it shows 4.81 or 4.82 million sessions, the approximate version is the sensible choice.
Pivot: from rows to columns
pivot turns the values of a column into columns, like a spreadsheet pivot table. Sales by category (rows) and channel (columns), on the star schema from lesson 02-05:
facts = spark.read.parquet(str(GOLD / "fact_sales"))
dim_product = spark.read.parquet(str(GOLD / "dim_product"))
sales = facts.where("status <> 'returned'").join(dim_product, "product_id")
(
sales.groupBy("category")
.pivot("channel", ["app", "web"])
.agg(F.round(F.sum("line_amount"), 2))
.orderBy("category")
.show()
)+----------+----------+----------+ | category| app| web| +----------+----------+----------+ |appliances|1673655.76| 2498276.0| | audio|1733482.12|2622809.45| | computing|2324824.64|3327385.62| | home|1044718.92|1553408.97| | phones|2087297.66|3128696.88| |television|3885028.17|6018673.34| +----------+----------+----------+
Giving the list of values (["app", "web"]) is optional, but advisable: without it, Spark first has to go through the data just to find out which columns to create.
Rollup and cube: subtotals
rollup works like groupBy, but adds the subtotals for each level and the grand total:
(
sales.rollup("category", "channel")
.agg(F.round(F.sum("line_amount"), 2).alias("sales"))
.orderBy(F.col("category").asc_nulls_last(), F.col("channel").asc_nulls_last())
.show(4)
)+----------+-------+----------+ | category|channel| sales| +----------+-------+----------+ |appliances| app|1673655.76| |appliances| web| 2498276.0| |appliances| NULL|4171931.76| | audio| app|1733482.12| +----------+-------+----------+ only showing top 4 rows
The row with a null channel is the category subtotal; the last row of the full result, with both columns null, is the grand total (€31,898,257.53). rollup follows the hierarchy from left to right; cube computes all the combinations (it would add the subtotals by channel). They are useful for feeding reports with totals; for everything else, groupBy is enough.
Window functions
groupBy has a limitation: it collapses each group into one row. Many questions need to compute something over a group while keeping every row: a product's position within its category, the cumulative sales up to each day, the time elapsed since the previous event. That is what window functions are for.
A window is defined with up to three elements:
| Element | Method | What it defines |
|---|---|---|
| Partition | Window.partitionBy(...) |
Which groups the rows are divided into (like a groupBy that does not collapse) |
| Order | .orderBy(...) |
The order of the rows within each group |
| Frame | .rowsBetween(start, end) |
Which rows in the group, relative to the current one, take part in the computation |
And it is applied with function.over(window) inside a withColumn.
| Family | Functions | Use |
|---|---|---|
| Numbering | row_number, rank, dense_rank |
Position within the group |
| Offset | lag, lead |
Value of the previous or the next row |
| Aggregation | sum, avg, min, max, count |
Running totals and moving averages |
Top 3 products by category
by_product = (
sales.groupBy("category", "product_id", "name")
.agg(F.round(F.sum("line_amount"), 2).alias("sales"))
)
w_category = Window.partitionBy("category").orderBy(F.desc("sales"))
top3 = (
by_product
.withColumn("position", F.row_number().over(w_category))
.where("position <= 3")
.orderBy("category", "position")
)
top3.show(6, truncate=False)+----------+----------+------------------------+---------+--------+ |category |product_id|name |sales |position| +----------+----------+------------------------+---------+--------+ |appliances|197 |Vacuum Cleaner Turia 851|237777.94|1 | |appliances|30 |Coffee Maker Nova 623 |230273.28|2 | |appliances|5 |Blender Nova 505 |230043.24|3 | |audio |124 |Soundbar Lumen 528 |199315.05|1 | |audio |136 |Soundbar Turia 249 |164812.56|2 | |audio |169 |Soundbar Nova 688 |159920.53|3 | +----------+----------+------------------------+---------+--------+ only showing top 6 rows
First you aggregate (one row per product) and then you number: the window separates the rows by category, sorts them from highest to lowest sales and row_number assigns them 1, 2, 3… The position <= 3 filter goes in a later step: a window function cannot be used inside the same where that computes it. An orderBy(...).limit(3) would not do: it would give the three best in the whole shop, not in each category.
The three numbering functions differ only in how they handle ties. With the units sold per product, where the third and fourth tie on 371:
| units | row_number |
rank |
dense_rank |
|---|---|---|---|
| 403 | 1 | 1 | 1 |
| 374 | 2 | 2 | 2 |
| 371 | 3 | 3 | 3 |
| 371 | 4 | 3 | 3 |
| 370 | 5 | 5 | 4 |
row_number breaks ties arbitrarily; rank repeats the position and leaves a gap; dense_rank repeats it without leaving a gap.
Cumulative sales, moving average and daily change
daily = (
orders.where("status <> 'returned'")
.groupBy(F.to_date("order_date").alias("date"))
.agg(F.round(F.sum("total_amount"), 2).alias("sales"))
)
w_month = Window.partitionBy(F.month("date")).orderBy("date")
w_days = Window.orderBy("date")
w_7d = Window.orderBy("date").rowsBetween(-6, 0)
trend = (
daily
.withColumn("month_to_date", F.round(F.sum("sales").over(w_month), 2))
.withColumn("avg_7d", F.round(F.avg("sales").over(w_7d), 2))
.withColumn("prev_day_sales", F.lag("sales").over(w_days))
)
trend.where("date >= '2026-05-30'").orderBy("date").show(5)+----------+---------+-------------+---------+--------------+ | date| sales|month_to_date| avg_7d|prev_day_sales| +----------+---------+-------------+---------+--------------+ |2026-05-30|203224.65| 5462528.72|190744.01| 222736.16| |2026-05-31|127701.09| 5590229.81|184744.62| 203224.65| |2026-06-01|161917.03| 161917.03|180676.47| 127701.09| |2026-06-02| 179343.0| 341260.03|179730.23| 161917.03| |2026-06-03|187331.16| 528591.19|179830.44| 179343.0| +----------+---------+-------------+---------+--------------+ only showing top 5 rows
month_to_date. An aggregation over a window with an order and no explicit frame sums from the first row of the partition up to the current one: it is a running total. Because the partition is by month, it restarts on day 1 (notice the jump between 31 May and 1 June).avg_7d. The framerowsBetween(-6, 0)covers from six rows before up to the current one: the seven-day moving average, which smooths out the daily ups and downs.prev_day_sales.lag("sales")brings in the value from the previous row;leadwould bring in the next one. With it you compute the change:(sales - prev_day_sales) / prev_day_sales.
The windows w_days and w_7d have no partitionBy, which forces Spark to take all the rows to a single partition to sort them (it warns you with a WARN-level message, which you do not see because the course scripts only show ERROR-level ones). With 181 days it is irrelevant; with millions of rows it would be a bottleneck, which is why you should partition whenever the question allows it.
Time between events in a session
w_session = Window.partitionBy("session_id").orderBy("event_time")
with_times = (
events
.withColumn("seq", F.row_number().over(w_session))
.withColumn("previous", F.lag("event_time").over(w_session))
.withColumn("seconds",
F.col("event_time").cast("long") - F.col("previous").cast("long"))
)
(
with_times.where("session_id = 's-017684'")
.select("session_id", "seq", "event_type", "event_time", "seconds")
.orderBy("seq").show()
)+----------+---+------------+-------------------+-------+ |session_id|seq| event_type| event_time|seconds| +----------+---+------------+-------------------+-------+ | s-017684| 1| purchase|2026-06-01 00:01:27| NULL| | s-017684| 2|product_view|2026-06-01 00:04:08| 161| | s-017684| 3|product_view|2026-06-01 00:06:56| 168| | s-017684| 4| add_to_cart|2026-06-01 00:09:33| 157| +----------+---+------------+-------------------+-------+
Casting a timestamp to long gives the seconds since 1970; subtracting two of them gives the difference in seconds. The first event of each session has no previous one, and its lag is null. Across the whole dataset, the average time between events in a session is 92.6 seconds.
The example also gives away a limitation of the practice data: this session starts with a purchase. The generator from lesson 01-05 assigns event types at random within each session, without respecting the logical order. Bear this in mind in the next section.
Integrating case: the conversion funnel
The conversion funnel measures how many sessions move through each step towards a purchase: viewing a product → adding it to the cart → buying. It is NovaMarket's first use case (lesson 01-02), and Marc's daily question.
The strategy has two steps: first, each session is summarised in one row with three flags (did it view?, did it add?, did it buy?), and then you count the sessions that meet each step and all the previous ones.
def has(event_type):
"""1 if the session contains some event of that type; 0 otherwise."""
return F.max((F.col("event_type") == event_type).cast("int"))
by_session = events.groupBy("session_id").agg(
F.max("device").alias("device"),
has("product_view").alias("viewed"),
has("add_to_cart").alias("added"),
has("purchase").alias("bought"),
)
funnel = by_session.agg(
F.count("*").alias("sessions"),
F.sum("viewed").alias("with_view"),
F.sum(F.col("viewed") * F.col("added")).alias("with_cart"),
F.sum(F.col("viewed") * F.col("added") * F.col("bought")).alias("with_purchase"),
)
funnel.show()+--------+---------+---------+-------------+ |sessions|with_view|with_cart|with_purchase| +--------+---------+---------+-------------+ | 30759| 29663| 14657| 3753| +--------+---------+---------+-------------+
- The
hasfunction compares each event with the type being looked for (true or false), turns it into 1 or 0 and keeps the session's maximum: 1 if there was at least one. It is an ordinary Python function that returns a Spark expression; it is not a UDF, and it carries no performance penalty. F.max("device")assigns the session its device, ignoring stray nulls.- Multiplying the flags is equivalent to a logical "and":
viewed * addedis 1 only if both are 1. That way, each step requires the previous ones.
Reading the funnel: of 30,759 sessions, 96.4% viewed some product; of these, 49.4% added something to the cart; and of the latter, 25.6% bought. The overall conversion is 12.2% (3,753 of 30,759), a figure far higher than that of a real shop, which usually sits in single-digit percentages: the practice data is generous.
To compare segments, just replace the global aggregation with a groupBy: by_session.groupBy("device").agg(...) gives a funnel by device.
Two honest caveats. First: this funnel checks that the session contains the three event types, not that they happened in order; with real data you would also require the first view to come before the first add to cart, and that before the purchase, by comparing minimum timestamps with the
F.min(F.when(...))technique. With the generated data, which does not respect that order, the result would not be meaningful. Second: as lesson 01-05 warned, thepurchaseevents do not correspond to rows inorders; they are two independent sources.
UDFs: user-defined functions
When no function in pyspark.sql.functions does what you need, you can register a Python function as a UDF (User Defined Function) and apply it to a column:
from pyspark.sql.types import StringType
def band(amount):
if amount is None:
return None
if amount >= 2000:
return "high"
return "medium" if amount >= 500 else "low"
band_udf = F.udf(band, StringType())
orders.withColumn("band", band_udf("total_amount")).groupBy("band").count().show()It works (6,384 high orders, 10,540 medium and 3,076 low), but it has a cost that explains why UDFs are the last resort:
- Every row makes a round trip. Spark runs in the Java virtual machine; a Python UDF, in a separate Python process. The data is serialised, sent, processed and returned.
- Catalyst cannot see inside. To the optimiser, the UDF is a black box: it cannot push filters forward or simplify anything that depends on it.
- Nulls are your problem. Without the
if amount is Nonecheck, the comparison would fail on the first null row.
The same logic, with native functions:
band_native = (
F.when(F.col("total_amount") >= 2000, "high")
.when(F.col("total_amount") >= 500, "medium")
.otherwise("low")
)
orders.withColumn("band", band_native).groupBy("band").count().show()In a test with the orders table repeated up to 1.28 million rows, the UDF version took roughly twice as long as the native one on the machine where this lesson was prepared; the difference grows with the volume and with the complexity of the query.
| Situation | Recommendation |
|---|---|
| There is a native function or a combination of them | Always use it |
| Conditional logic | when / otherwise |
| A computation that only exists in a Python library | pandas UDF |
| Very particular logic over little data | Ordinary UDF, accepting the cost |
pandas UDFs (or vectorised UDFs) receive and return batches of rows as pandas series, using the Apache Arrow format for the exchange. They greatly reduce the cost of the round trip and let you apply Python's scientific libraries; they require pyarrow to be installed. Recent versions of Spark also apply Arrow to ordinary UDFs, which has narrowed the gap, but the rule does not change: native functions first.
Common Mistakes and Tips
- Using
innerout of habit. It is the default type and silently removes rows with no match. Always ask yourself what should happen to them. - Not checking the number of rows after a join. If it grows unexpectedly, the key is duplicated in the table you thought was the "one" side.
- Forgetting that nulls do not match, and so losing the anonymous visitors or the customers with no province.
- Filtering on a window in the same step that creates it. Compute the column with
withColumnand filter afterwards. - Windows without
partitionByover large data. Everything ends up in a single partition. If you need a global running total, aggregate first to reduce the rows, as was done withdaily. - Ordering a window by a column with ties and expecting stable results.
row_numberbreaks ties arbitrarily, and may give different results on each run. Add a second tie-breaking column to theorderBy. - Overwriting the table you are reading. You may lose the source. Always write to another path.
- Reaching for a UDF for convenience. Look in
pyspark.sql.functionsfirst: what you need almost always exists. - Tip: build complex queries in named steps (
by_product,top3) and check each one withshow(). Because evaluation is lazy, the intermediate steps cost nothing until you run them.
Exercises
Exercise 1: daily sales, now correct
The gold/daily_sales table from the exercise in lesson 02-04 was undervalued because of the null amounts. Regenerate it from silver/orders_complete and work out how much total sales excluding returns increase compared with silver/orders.
Exercise 2: the two best customers in each province
Obtain, for Valencia and Madrid, the two customers with the highest total spend (excluding returned orders), with their position within the province.
Exercise 3: abandoned carts
How many sessions added some product to the cart and did not buy? Solve it with a join, without using the by_session table.
Solutions
Exercise 1
It is enough to change the read path in build_gold.py:
The rest of the script does not change, and the table still has 362 rows. To measure the difference:
for table in ["orders", "orders_complete"]:
df = spark.read.parquet(str(SILVER / table)).where("status <> 'returned'")
df.agg(F.round(F.sum("total_amount"), 2).alias(table)).show()The sum goes from €31,578,584.01 to €31,898,257.53: €319,673.52 more. The new figure is exactly the grand total given by the rollup over fact_sales: two independent routes (the order amounts and the lines of the star schema) arrive at the same figure. That match, which did not happen before, is the best proof that the rebuild is correct.
Exercise 2
spend = (
orders.where("status <> 'returned'")
.groupBy("customer_id")
.agg(F.round(F.sum("total_amount"), 2).alias("spend"))
.join(customers, "customer_id")
)
w_province = Window.partitionBy("province").orderBy(F.desc("spend"))
(
spend.withColumn("position", F.rank().over(w_province))
.where("position <= 2 AND province IN ('Valencia', 'Madrid')")
.select("province", "position", "customer_id", "name", "spend")
.orderBy("province", "position")
.show()
)+--------+--------+-----------+----------------+--------+ |province|position|customer_id| name| spend| +--------+--------+-----------+----------------+--------+ | Madrid| 1| 712| Carlos Ruiz|56220.08| | Madrid| 2| 888|Alejandro Romero|54624.22| |Valencia| 1| 4| Lucia Lopez|65535.16| |Valencia| 2| 319| Hugo Ferrer|59682.06| +--------+--------+-----------+----------------+--------+
You aggregate by customer first, join with customers to find out the province and number the customers within each one. Here the inner join is safe, because every order has an existing customer. rank is used so that, in the event of a tie, both customers appear.
Exercise 3
cart_sessions = events.where("event_type = 'add_to_cart'").select("session_id").distinct()
purchase_sessions = events.where("event_type = 'purchase'").select("session_id").distinct()
abandoned = cart_sessions.join(purchase_sessions, "session_id", "left_anti")
print(abandoned.count())The result is 11,353 sessions, out of the 15,156 that used the cart. The anti join expresses the question literally: sessions with a cart that are not among the sessions with a purchase. The distinct() avoids counting a session with several add-to-cart events more than once. This list is the basis of a classic commercial action: the abandoned-cart reminder.
Conclusion
You have completed Spark's transformation toolbox. Joins combine tables, and their type (inner, left, right, full, left_semi, left_anti) decides the fate of the rows with no match; remember that nulls never match and that a join can multiply rows. Advanced aggregations summarise with several metrics at once, count distinct values exactly or approximately, turn rows into columns with pivot and add subtotals with rollup. Window functions compute over groups of related rows without collapsing them: rankings, running totals, moving averages and comparisons with the previous row. And UDFs remain the last resort, behind native functions. With all this you have created silver/orders_complete, with the 200 amounts rebuilt and verified, and you have computed NovaMarket's conversion funnel.
All these operations have something in common that we have overlooked until now: joins, aggregations and windows need to bring together rows that are in different partitions, which means they trigger shuffles. With 38 MB you do not notice. With NovaMarket's 7.6 GB a day, the difference between a well-designed query and a careless one is measured in hours and in money. In the next lesson, Optimisation and Performance in Spark, you will learn to read execution plans, to understand what makes a query expensive and to put it right.
