Until now each lesson has told you which script to create and what result to expect. In real work nobody does that: a two-paragraph brief arrives, often ambiguous, and the rest is up to you. This lesson recreates that situation with three projects of increasing difficulty. They do not introduce new concepts; they ask you to combine the ones you already have.

The first is a brief from Irene that travels through the lake from end to end and finishes with a gold table, a quality check and two charts. The second brings in a type of data you had not touched, free text, with a sentiment analysis of product reviews. The third is an open proposal for a near-real-time dashboard, with no closed solution. Attempt each project on your own before looking at the reference solution: the learning is in the journey, mistakes included.

How to approach the projects

The three projects share a way of working, which is that of Module 5 put into practice:

  1. Read the brief and write down what you have understood: which decision it supports, which deliverables it asks for, what is taken for granted. Doubts are resolved before programming.
  2. Explore before building. Five minutes with printSchema(), count() and show() on the input tables save an hour later on.
  3. Build in small steps and check each one.
  4. Validate the result against a figure you already know. It is the most rewarding habit in this profession.
  5. Go through the checklist from lesson 05-01 before considering it finished.

Work in ~/novamarket/, with the virtual environment activated. The projects need the lake as it was at the end of Module 4, plus the quality.py script from lesson 05-02.

Project 1: sales analysis for an online shop

The brief

From: Irene · To: data team

The sales committee meets on the first Monday of every month and so far we have been bringing it loose figures. I need a monthly sales report that can be generated for any month with a single command. I want to see how much we have sold by category and by province, and the three best-selling products in each category. The figures must be net sales, excluding returns, and they have to tally with the ones we already use. The data must end up in a table that Marc can query afterwards from his tools, and I need two charts for the presentation. We'll start with June 2026.

Project card

Objectives Chain a complete pipeline; build a new gold table, parameterised and idempotent; validate it; communicate the result
Data gold/fact_sales, gold/dim_product, gold/dim_customer, gold/dim_date; silver/orders_complete for validation
Tools PySpark, matplotlib, and the scripts rebuild_amounts.py, star_schema.py and quality.py
Estimated time 2-3 hours

Deliverables

  1. A script monthly_report.py that takes the month (YYYY-MM) as a parameter.
  2. A new table, gold/monthly_sales, partitioned by month, with the columns category, province, orders, units and sales.
  3. The ranking of the three products with the highest sales in each category, on screen.
  4. Two charts in ~/novamarket/charts/: sales by category and the ten provinces with the highest sales.
  5. An automatic validation that stops the script if the table does not tally with silver.

Step-by-step guide

Step 1. Refresh the lake and run the quality check. The report is only as good as its input data. Chain the scripts you already have; the shell operator && runs each command only if the previous one finished successfully:

cd ~/novamarket
source .venv/bin/activate
python rebuild_amounts.py && python star_schema.py && python quality.py 2026-07-01

If quality.py ended with an error, the chain would stop: that is how an orchestrator would behave. It should finish with 1 warnings, 0 errors.

Step 2. Decide the grain and the definitions. Before writing any code, answer in writing:

  • Which fact table has the necessary detail? (Sales by category require going down to the order line.)
  • What are "net sales"? (The definition in the business glossary from lesson 05-02.)
  • What do you do with customers without a province? (They cannot disappear from the report: their sales exist.)
  • How are orders counted, if an order has several lines?

Step 3. Build the query for the month. Start from fact_sales, discard returns, join with dim_date to obtain the month and with the product and customer dimensions. Hint: both dimensions have a name column.

Step 4. Aggregate and write the gold table with dynamic overwriting of the month's partition, as in daily_load.py.

Step 5. Validate. Read the partition you have just written and check, at the very least, that the sum of sales matches the sum of total_amount for the non-returned orders of that month in silver/orders_complete.

Step 6. Calculate the ranking with a window function (lesson 03-03).

Step 7. Draw the two charts following the pattern from lesson 04-04: aggregate in Spark, move the small result to pandas, draw.

Step 8. Test idempotency: run the script twice for the same month, and once for a month with no data.

Acceptance criteria

Use this rubric to assess your solution before comparing it with the reference one:

Criterion How to check it Met?
The month is a parameter, and a badly written value stops the script python monthly_report.py june fails without writing anything
The table is partitioned by month and can be reprocessed Two runs leave the same number of rows
June's sales add up to €5,121,698.84 Matches silver/orders_complete
Returns are excluded With them, the total would be higher
Customers without a province appear with an explicit label There is an unknown province
Each combination of category and province appears only once 90 rows in June
An order with three lines in the same category counts as one order A distinct count is used
The script fails, with a non-zero exit code, if the validation does not pass It can be triggered by changing the tolerance
The charts have a title, units and an axis starting at zero Visual review
A month with no data does not write an empty partition python monthly_report.py 2026-07

Reference solution

Create ~/novamarket/monthly_report.py:

"""NovaMarket monthly sales report.

Usage:  python monthly_report.py MONTH        (MONTH in YYYY-MM format)
Updates gold/monthly_sales/month=MONTH, validates the result, shows the product
ranking and saves two charts. Exits with code 1 if the validation fails.
"""
import sys
from datetime import datetime
from pathlib import Path

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from pyspark.sql import SparkSession, Window
from pyspark.sql import functions as F

BASE = Path.home() / "novamarket"
SILVER, GOLD = BASE / "lake" / "silver", BASE / "lake" / "gold"
CHARTS = BASE / "charts"
BLUE, GREY = "#1f77b4", "#b0b0b0"

if len(sys.argv) != 2:
    sys.exit(__doc__)
month = sys.argv[1]
datetime.strptime(month, "%Y-%m")          # validates the format before touching anything

spark = (
    SparkSession.builder.master("local[*]").appName(f"monthly_report_{month}")
    .config("spark.sql.sources.partitionOverwriteMode", "dynamic")
    .getOrCreate()
)
spark.sparkContext.setLogLevel("ERROR")

# --- 1. Net sales for the month, at order-line grain ----------------------
# From each dimension, only the columns needed (the customer's name is not required)
products = spark.read.parquet(str(GOLD / "dim_product")).select(
    "product_id", F.col("name").alias("product"), "category")
customers = spark.read.parquet(str(GOLD / "dim_customer")).select("customer_id", "province")

sales = (
    spark.read.parquet(str(GOLD / "fact_sales"))
    .where(F.col("status") != "returned")
    .join(spark.read.parquet(str(GOLD / "dim_date")), "date_id")
    .withColumn("month", F.date_format("date", "yyyy-MM"))
    .where(F.col("month") == month)
    .join(F.broadcast(products), "product_id")
    .join(F.broadcast(customers), "customer_id")
    .withColumn("province", F.coalesce("province", F.lit("unknown")))
    .cache()
)
if sales.count() == 0:
    sys.exit(f"There are no sales for the month {month}")

# --- 2. Gold table: sales by category and province ------------------------
summary = sales.groupBy("month", "category", "province").agg(
    F.countDistinct("order_id").alias("orders"),
    F.sum("quantity").alias("units"),
    F.round(F.sum("line_amount"), 2).alias("sales"),
)
target = str(GOLD / "monthly_sales")
summary.coalesce(1).write.mode("overwrite").partitionBy("month").parquet(target)

# --- 3. Validation: the table must tally with silver/orders_complete ------
table = spark.read.parquet(target).where(F.col("month") == month)
table_total = table.agg(F.sum("sales")).first()[0]
silver_total = (
    spark.read.parquet(str(SILVER / "orders_complete"))
    .where((F.col("status") != "returned")
           & (F.date_format("order_date", "yyyy-MM") == month))
    .agg(F.sum("total_amount")).first()[0]
)
errors = []
if abs(table_total - silver_total) > 1:
    errors.append(f"does not tally with silver: {table_total:.2f} versus {silver_total:.2f}")
if table.where("sales <= 0 OR units <= 0 OR orders <= 0").count() > 0:
    errors.append("there are rows with non-positive amounts or quantities")
if table.count() != table.select("category", "province").distinct().count():
    errors.append("there are repeated combinations of category and province")
if errors:
    sys.exit(f"VALIDATION FAILED for {month}: " + "; ".join(errors))
print(f"Month {month}: {table.count()} rows in gold/monthly_sales; "
      f"net sales {table_total:.2f} EUR (tallies with silver)")

# --- 4. Ranking: the 3 best-selling products in each category -------------
by_product = sales.groupBy("category", "product_id", "product").agg(
    F.sum("quantity").alias("units"),
    F.round(F.sum("line_amount"), 2).alias("sales"),
)
position = F.row_number().over(Window.partitionBy("category").orderBy(F.desc("sales")))
ranking = by_product.withColumn("position", position).where("position <= 3")
ranking.orderBy("category", "position").select(
    "category", "position", "product", "units", "sales").show(18, truncate=False)

# --- 5. Charts: aggregate in Spark and draw the small result --------------
CHARTS.mkdir(exist_ok=True)
by_category = (table.groupBy("category").agg(F.sum("sales").alias("sales"))
               .orderBy("sales").toPandas())
by_province = (table.groupBy("province").agg(F.sum("sales").alias("sales"))
               .orderBy(F.desc("sales")).limit(10).toPandas().iloc[::-1])

for data, column, title, filename in [
    (by_category, "category", f"Net sales by category, {month}", f"report_{month}_categories.png"),
    (by_province, "province", f"The 10 provinces with the highest sales, {month}", f"report_{month}_provinces.png"),
]:
    fig, ax = plt.subplots(figsize=(8, 4))
    colours = [GREY] * (len(data) - 1) + [BLUE]           # the top one is highlighted
    ax.barh(data[column], data["sales"] / 1000, color=colours)
    ax.set_xlabel("Thousands of euros")
    ax.set_title(title, loc="left")
    ax.spines[["top", "right"]].set_visible(False)
    fig.tight_layout()
    fig.savefig(CHARTS / filename, dpi=150)
    plt.close(fig)
    print("Saved:", CHARTS / filename)

spark.stop()

The decisions worth understanding:

  • datetime.strptime(month, "%Y-%m") validates the parameter. If you type june, it raises an error before the Spark session is created.
  • From each dimension, only the necessary columns are selected. This avoids the clash between the two name columns and, incidentally, applies minimisation: the report does not need any customer's name.
  • F.coalesce("province", F.lit("unknown")) turns the null into a visible category. A groupBy keeps nulls as a group, but a null in a chart or a filter is easily lost.
  • F.broadcast indicates that the dimensions are small and can be copied to every task (lesson 03-04).
  • .cache() on sales: it is used for the table, for the ranking and for the count.
  • countDistinct("order_id") counts orders, not lines.
  • The validation reads the table once written, not the variable in memory, and compares it with an independent source. The €1 tolerance absorbs the rounding differences that come from adding up decimals by two different routes.
  • sys.exit("message") prints the message and exits with code 1.
  • row_number() guarantees exactly three products per category; with rank(), a tie could return four.
  • .iloc[::-1] reverses the order in pandas, because barh draws from the bottom up and we want the largest at the top.

The result

python monthly_report.py 2026-06
Month 2026-06: 90 rows in gold/monthly_sales; net sales 5121698.84 EUR (tallies with silver)
+----------+--------+------------------------+-----+---------+
|category  |position|product                 |units|sales    |
+----------+--------+------------------------+-----+---------+
|appliances|1       |Vacuum Cleaner Turia 851|74   |52681.34 |
|appliances|2       |Blender Nova 505        |72   |51438.24 |
|appliances|3       |Coffee Maker Nova 623   |47   |37579.32 |
|audio     |1       |Soundbar Lumen 528      |54   |31749.3  |
...
|television|1       |TV Mount Lumen 907      |57   |111271.41|
|television|2       |Media Player Lumen 750  |58   |107166.02|
|television|3       |TV Mount Altea 438      |53   |102867.17|
+----------+--------+------------------------+-----+---------+

Saved: /home/your_user/novamarket/charts/report_2026-06_categories.png
Saved: /home/your_user/novamarket/charts/report_2026-06_provinces.png

The 90 rows are 6 categories by 15 provinces (14 with a name, plus unknown). In June, television leads with €1.60 million, followed by computing (0.90) and phones (0.81); by province, Valencia (€1.13 million), Madrid (1.03) and Barcelona (0.81). Customers without a province add up to almost €100,000 in the month: 2% of sales that would have vanished from a "by province" report built with a careless join, and one more argument for fixing the defect at source. The product names are randomly generated, so don't look for any logic in a mouse bringing in more than a monitor.

What you would hand over to Irene is not the console output, but two charts, three sentences with the essentials and the limitations: six months of history, no seasonality, and 2% of sales without a province.

Common mistakes in this project

  • Calculating from orders_complete. It has no category: an order mixes products from several. You have to go down to the line.
  • Forgetting returns, or excluding them in the table but not in the validation: the check would fail, which is exactly what it is for.
  • Joining with the full dimensions and running into the AMBIGUOUS_REFERENCE error because of the two name columns.
  • Using an inner join with a separate provinces table or filtering out the nulls: sales disappear without any warning.
  • Writing with overwrite without dynamic mode: the June report would wipe out May's.
  • Validating by comparing the table with itself. A useful validation compares with a source calculated by another route.

Extensions

  • Generate the report for the six months and check the half-year total (solved in the exercises).
  • Calculate each category's change from the previous month with lag.
  • Register rules for the new table in quality.py, and its entry in the data dictionary.
  • Generate the report as a Markdown file with the figures and the charts linked.
  • Add the task to the novamarket_daily DAG, or create a monthly DAG.

Project 2: sentiment analysis of product reviews

The brief

From: Irene · To: data team

Customer service says there are products that pile up complaints, but we only have the stars, and many three-star reviews say very different things. The website is going to start sending us the text of the reviews. Can we tell, from the text, which products and which categories generate the most negative opinions? A simple first version will do; I also want to know how far we can trust it.

This is a sentiment analysis problem: classifying a text according to whether it expresses a positive, negative or neutral opinion. It is the typical case of unstructured data mentioned in lesson 01-01, and the same one applied to brand mentions on social media.

Project card

Objectives Process text with Spark; apply the bronze → silver → gold pattern to a new source; evaluate a method honestly and know its limits
Data Fictitious reviews, which you will generate yourself; gold/dim_product
Tools Standard Python to generate the data; PySpark for the analysis
Estimated time 2 hours

The data: a review generator

NovaMarket has no reviews, so they have to be manufactured. The generator builds them from templates whose polarity is known, and stores it in the true_polarity column. In a real project that column would not exist (or a sample would have to be labelled by hand); here it lets you measure how accurate the analysis is. Create ~/novamarket/generate_reviews.py:

"""Generates fictitious NovaMarket product reviews with a known polarity.

Usage:  python generate_reviews.py
Creates data/reviews.json (JSON Lines). Fixed seed: it always generates the same output.
"""
import csv
import json
import random
from datetime import date, timedelta
from pathlib import Path

DATA_DIR = Path.home() / "novamarket" / "data"
NUM_REVIEWS = 6000
random.seed(7)

POSITIVE = [
    "Excellent purchase, works perfectly.",
    "Very happy with the product, highly recommended.",
    "Fantastic quality and fast delivery.",
    "I love it, it's comfortable and sturdy.",
    "Nice product, easy to use and very useful.",
    "Great, it exceeded my expectations. I'm satisfied.",
]
NEGATIVE = [
    "Very disappointed, it arrived broken.",
    "Poor quality, it broke down within a week.",
    "Terrible service and slow delivery. A scam.",
    "Faulty product, I'm going to return it.",
    "Horrible, it's fragile and uncomfortable.",
    "Expensive and bad. I regret buying it.",
]
NEUTRAL = [
    "Does the job, nothing more.",
    "It's what I expected for the price.",
    "Average: it neither stands out nor disappoints.",
]
# Hard cases: negations and irony. True polarity in brackets.
HARD = [
    ("I have no complaints, nothing bad to say.", "positive"),
    ("I was afraid it would be fragile or faulty, but not at all.", "positive"),
    ("Not good and not recommended.", "negative"),
    ("It does not work well and is not comfortable at all.", "negative"),
    ("Great, another gadget that stops working after a month.", "negative"),
]
TAILS = ["", "", " I bought it as a gift.", " Second time I have ordered here.",
         " The courier was on time.", " I use it every day."]

with open(DATA_DIR / "products.csv", encoding="utf-8") as f:
    products = [int(row["product_id"]) for row in csv.DictReader(f)]

# Each product has a hidden "quality": the probability of receiving a good review
quality = {p: random.uniform(0.35, 0.92) for p in products}

with open(DATA_DIR / "reviews.json", "w", encoding="utf-8") as out:
    for i in range(1, NUM_REVIEWS + 1):
        product = random.choice(products)
        draw = random.random()
        if draw < 0.10:                                   # 10% neutral reviews
            text, polarity = random.choice(NEUTRAL), "neutral"
        elif draw < 0.22:                                 # 12% hard cases
            text, polarity = random.choice(HARD)
        elif random.random() < quality[product]:
            text, polarity = random.choice(POSITIVE), "positive"
        else:
            text, polarity = random.choice(NEGATIVE), "negative"
        stars = {"positive": random.choice([4, 5, 5]), "neutral": 3,
                 "negative": random.choice([1, 1, 2])}[polarity]
        review = {
            "review_id": i,
            "product_id": product,
            "customer_id": random.randint(1, 1000),
            "date": (date(2026, 6, 1) + timedelta(days=random.randrange(30))).isoformat(),
            "stars": stars,
            "text": text + random.choice(TAILS),
            "true_polarity": polarity,
        }
        out.write(json.dumps(review, ensure_ascii=False) + "\n")

print(f"Generated {NUM_REVIEWS} reviews in {DATA_DIR / 'reviews.json'}")
  • random.seed(7) fixes the seed: the file is identical on every run and on every computer, which is why your figures will match the lesson's.
  • quality assigns each product a hidden probability of receiving good reviews. It is what the analysis should be able to uncover.
  • HARD includes negations ("not good") and irony ("great, another gadget that stops working"). They are there on purpose so that the method fails where it would fail with real text.
  • ensure_ascii=False writes any non-ASCII character (an accent in a name, a curly apostrophe) as it is, in UTF-8, instead of as a \u escape sequence.
python generate_reviews.py
head -n 2 data/reviews.json
Generated 6000 reviews in /home/your_user/novamarket/data/reviews.json
{"review_id": 1, "product_id": 22, "customer_id": 490, "date": "2026-06-29", "stars": 5, "text": "I love it, it's comfortable and sturdy.", "true_polarity": "positive"}
{"review_id": 2, "product_id": 112, "customer_id": 412, "date": "2026-06-24", "stars": 5, "text": "Great, it exceeded my expectations. I'm satisfied.", "true_polarity": "positive"}

The method: a sentiment lexicon

The simplest technique does not use machine learning. You start from a lexicon: a list of words with a positive (+1) or negative (−1) charge. The score of a text is the sum of the charges of its words:

flowchart LR
    T["Poor quality,<br>it broke down within a week"] --> K[Tokenise:<br>poor · quality · it · broke · down · within · a · week]
    K --> J[Join with the lexicon:<br>poor −1 · broke −1]
    J --> S[Add up: −2]
    S --> C[Classify: negative]

Tokenising means splitting the text into units, here words. In Spark, the whole process is a split, an explode, a join and a groupBy: operations you have already mastered.

Steps

  1. Copy the file to bronze/reviews/ and read it with an explicit schema.
  2. Convert the text to lower case, split it into words and get one row per word.
  3. Join with the lexicon and add up by review. Careful: a review without any word from the lexicon must not disappear.
  4. Classify according to the sign and save in silver/reviews.
  5. Evaluate against true_polarity.
  6. Aggregate by product and save gold/product_sentiment.

Deliverables

  • sentiment.py.
  • silver/reviews: one row per review, with score and sentiment.
  • gold/product_sentiment: one row per product, with the number of reviews, average stars and the percentages of positive and negative reviews.
  • A table comparing the true polarity with the calculated one, and the percentage of correct classifications.
  • A paragraph for Irene: what can and cannot be concluded.

Reference solution

Create ~/novamarket/sentiment.py:

"""Sentiment analysis of the reviews with a word lexicon.

Usage:  python sentiment.py
Writes silver/reviews (one row per review, with its sentiment) and
gold/product_sentiment (one row per product).
"""
import shutil
from pathlib import Path

from pyspark.sql import SparkSession
from pyspark.sql import functions as F

BASE = Path.home() / "novamarket"
LAKE = BASE / "lake"

# The lexicon: words with a positive (+1) or negative (-1) charge
POSITIVE_WORDS = ["excellent", "perfectly", "happy", "recommended", "fantastic", "fast",
                  "love", "comfortable", "sturdy", "nice", "good", "easy", "useful",
                  "great", "satisfied", "well"]
NEGATIVE_WORDS = ["disappointed", "broken", "poor", "bad", "broke", "terrible", "slow",
                  "scam", "faulty", "return", "horrible", "fragile", "uncomfortable",
                  "expensive", "regret", "complaints", "afraid"]

spark = SparkSession.builder.master("local[*]").appName("sentiment").getOrCreate()
spark.sparkContext.setLogLevel("ERROR")

# --- 1. Bronze: untouched copy of the file received -----------------------
bronze = LAKE / "bronze" / "reviews"
bronze.mkdir(parents=True, exist_ok=True)
shutil.copy2(BASE / "data" / "reviews.json", bronze / "reviews.json")

SCHEMA = ("review_id INT, product_id INT, customer_id INT, date DATE, stars INT, "
          "text STRING, true_polarity STRING")
reviews = spark.read.schema(SCHEMA).json(str(bronze)).dropDuplicates(["review_id"])

# --- 2. Tokenise: one row per word ----------------------------------------
words = (
    reviews
    .select("review_id", F.explode(F.split(F.lower("text"), "[^a-z]+")).alias("word"))
    .where(F.col("word") != "")
)

# --- 3. Score: join each word with the lexicon and add up by review -------
lexicon = spark.createDataFrame(
    [(w, 1) for w in POSITIVE_WORDS] + [(w, -1) for w in NEGATIVE_WORDS],
    "word STRING, value INT",
)
scores = (
    words.join(F.broadcast(lexicon), "word")               # only the charged words
    .groupBy("review_id")
    .agg(F.sum("value").alias("score"))
)
classified = (
    reviews.join(scores, "review_id", "left")              # left: reviews without lexicon words
    .fillna({"score": 0})
    .withColumn("sentiment",
                F.when(F.col("score") > 0, "positive")
                 .when(F.col("score") < 0, "negative")
                 .otherwise("neutral"))
)
classified.coalesce(1).write.mode("overwrite").parquet(str(LAKE / "silver" / "reviews"))
classified = spark.read.parquet(str(LAKE / "silver" / "reviews"))

# --- 4. Evaluate: is the lexicon right? -----------------------------------
print("True polarity (rows) versus calculated sentiment (columns):")
classified.groupBy("true_polarity").pivot(
    "sentiment", ["positive", "neutral", "negative"]).count().orderBy("true_polarity").show()
correct = classified.where(F.col("sentiment") == F.col("true_polarity")).count()
total = classified.count()
print(f"Correct: {correct} of {total} ({100 * correct / total:.1f}%)")

# --- 5. Gold: sentiment by product ----------------------------------------
products = spark.read.parquet(str(LAKE / "gold" / "dim_product")).select(
    "product_id", "name", "category")
by_product = (
    classified.groupBy("product_id").agg(
        F.count("*").alias("num_reviews"),
        F.round(F.avg("stars"), 2).alias("avg_stars"),
        F.round(100 * F.avg((F.col("sentiment") == "positive").cast("int")), 1)
         .alias("pct_positive"),
        F.round(100 * F.avg((F.col("sentiment") == "negative").cast("int")), 1)
         .alias("pct_negative"),
    )
    .join(F.broadcast(products), "product_id")
)
target = str(LAKE / "gold" / "product_sentiment")
by_product.coalesce(1).write.mode("overwrite").parquet(target)

result = spark.read.parquet(target)
print("Products with reviews:", result.count())
print("The 5 products with the worst sentiment:")
result.orderBy(F.desc("pct_negative")).select(
    "name", "category", "num_reviews", "avg_stars", "pct_negative").show(5, truncate=False)
print("Sentiment by category:")
(classified.join(F.broadcast(products), "product_id").groupBy("category").agg(
    F.count("*").alias("reviews"),
    F.round(F.avg("stars"), 2).alias("avg_stars"),
    F.round(100 * F.avg((F.col("sentiment") == "positive").cast("int")), 1).alias("pct_positive"),
).orderBy(F.desc("pct_positive")).show())

spark.stop()
  • F.split(F.lower("text"), "[^a-z]+") splits the text on any sequence of characters that are not letters: spaces, commas, full stops, apostrophes. A contraction such as "it's" therefore becomes "it" and "s", which is harmless here because neither is in the lexicon; but a lexicon entry like "don't" would never match. And if the reviews contained accented words ("café", "naïve"), they would be split in two: the character class must cover every letter the text can contain.
  • F.explode turns the list of words into one row per word. It is the operation that turns a text into a table, and from there on everything is ordinary Spark.
  • The first join is an inner join: it discards the words without a charge ("the", "product"), which are the majority. The second is left: it recovers the reviews in which no lexicon word was found, which are left with a score of 0, that is, neutral.
  • pivot (lesson 03-03) builds the cross-tabulation between the true and the calculated values. In machine learning it is called a confusion matrix.
  • F.avg((condition).cast("int")) is the compact way of calculating a percentage: the mean of ones and zeros.

The result and its limits

python sentiment.py
True polarity (rows) versus calculated sentiment (columns):
+-------------+--------+-------+--------+
|true_polarity|positive|neutral|negative|
+-------------+--------+-------+--------+
|     negative|     460|   NULL|    1771|
|      neutral|    NULL|    599|    NULL|
|     positive|    2868|   NULL|     302|
+-------------+--------+-------+--------+

Correct: 5238 of 6000 (87.3%)
Products with reviews: 200
The 5 products with the worst sentiment:
+----------------------+----------+-----------+---------+------------+
|name                  |category  |num_reviews|avg_stars|pct_negative|
+----------------------+----------+-----------+---------+------------+
|Media Player Lumen 877|television|16         |2.44     |68.8        |
|Monitor Turia 868     |computing |33         |2.03     |63.6        |
|Keyboard Kore 295     |computing |27         |2.33     |63.0        |
|Bookshelf Vento 927   |home      |24         |2.46     |62.5        |
|Media Player Kore 187 |television|37         |2.65     |62.2        |
+----------------------+----------+-----------+---------+------------+
only showing top 5 rows
Sentiment by category:
+----------+-------+---------+------------+
|  category|reviews|avg_stars|pct_positive|
+----------+-------+---------+------------+
|appliances|    887|     3.41|        61.6|
|    phones|    911|     3.26|        56.6|
|television|    814|     3.33|        55.9|
|     audio|   1342|     3.29|        54.6|
|      home|   1158|      3.2|        53.5|
| computing|    888|     3.08|        51.6|
+----------+-------+---------+------------+

87.3% correct looks like a good result. The cross-tabulation tells the full story: there are 762 errors, and they are exactly the 762 "hard" reviews. The method fails on all of them:

Text What the lexicon sees Why it fails
"Not good and not recommended" good +1, recommended +1 → positive It does not understand negation
"I have no complaints, nothing bad to say" complaints −1, bad −1 → negative Same, in the opposite direction
"Great, another gadget that stops working after a month" great +1 → positive It does not understand irony
"I was afraid it would be fragile or faulty, but not at all" afraid, fragile, faulty → negative It does not understand context

And there are more limits that this data, being template-based, does not show: spelling mistakes, words that are not in the lexicon, terms whose meaning depends on the product ("small" is good in a phone and bad in a television), other languages. With real text, such a simple lexicon would be right considerably less often.

So is it any use? For Irene's question, yes: the errors affect individual reviews, but when you aggregate by product they largely cancel out: each product's percentage of negative reviews closely tracks its average stars (the correlation between the two columns of gold/product_sentiment is −0.89). The paragraph for her would be: "We can point out with reasonable reliability which products concentrate negative opinions, and the top five deserve a review. We cannot trust the classification of any individual review, especially if it contains negations or irony, nor use it to reply automatically to a customer. With real text, before using it we would have to label a sample by hand and measure the accuracy".

How it would be done with machine learning

The lexicon is a fixed list written by hand. The alternative is for the model to learn from examples which words and combinations indicate each polarity:

  • Supervised classification with MLlib. The workflow from lesson 04-03, with text: a Tokenizer splits into words, HashingTF and IDF turn them into a numeric vector that weights words by their rarity, and a logistic regression learns from labelled reviews; the stars can serve as an approximate label. All in a Pipeline, as in predict_purchase.py. It picks up words the lexicon did not include, but it still treats the text as a bag of separate words: negation and irony escape it just the same.
  • Language models. Current models represent the meaning of whole sentences and do distinguish "not good" from "good". How they are used on large volumes of text, together with the vectors (embeddings) that make it possible, is the topic of lesson 08-03.

The choice follows the usual criterion: start with the simple option, measure, and only increase complexity if the remaining error matters for the decision.

Common mistakes in this project

  • A tokeniser that does not match the lexicon: lexicon entries with apostrophes or accents ("don't", "café") while the regular expression splits on those characters, or a lexicon in lower case and text that has not been lowercased: the words do not match and everything comes out neutral.
  • Using an inner join to attach the scores to the reviews: the neutral reviews disappear and the percentage of correct answers comes out inflated.
  • Giving the percentage of correct answers without looking at the cross-tabulation. The 87% hides a 100% failure rate on an entire class of texts.
  • Ranking products by percentage without looking at how many reviews they have. The worst on the list has 16; with three reviews, 100% negative means nothing.
  • Evaluating with the same texts used to build the lexicon. Here it is unavoidable because the data comes from templates; with real data, it would be cheating yourself.

Note on privacy. The reviews carry customer_id and free text, where a customer can write anything, including personal data. The gold table, aggregated by product, no longer contains them; silver/reviews does. In a real project, their processing must be reviewed with those responsible for data protection (Module 7).

Extensions

  • Handle negation (solved in the exercises).
  • Publish a ranking only with products that have at least 20 reviews.
  • Compare sentiment and stars: which reviews have five stars and negative text?
  • Train the MLlib classifier described above and compare it with the lexicon on the same data.

Project 3: near-real-time dashboard (open proposal)

This project has no reference solution. It has a brief, some hints and some criteria; the design is yours.

The brief

From: Irene · To: data team

On the day of a big campaign, operations cannot wait until tomorrow to know whether the website is selling. I want a screen that shows, with a delay of seconds, how the shop is doing right now: activity, purchases and conversion over the last few minutes.

Project card

Objectives Design and build a complete stream: source, windowed aggregation, sink and visualisation
Data web_events.json, replayed with simulate_arrival.py (lesson 03-05)
Tools Spark Structured Streaming; matplotlib or the visualisation tool you prefer
Estimated time 3-4 hours

Deliverables

  1. A one-page design document: which indicators the dashboard shows and with what definition, which window and which watermark, and why.
  2. A streaming script that keeps a small table with the indicators per window up to date.
  3. A second script that reads that table and draws the dashboard, and that can be rerun every few seconds.
  4. A final reflection: how much would it cost to keep this running all year (lesson 05-03), and on which days does the business justify it?

Hints

  • Starting point. count_in_stream.py already reads from ~/novamarket/stream/input with an explicit schema and aggregates by windows. Copy it under another name and use a new checkpoint.
  • Indicators. For each ten-minute window: active sessions (approx_count_distinct("session_id")), events by type and purchases. A conditional sum such as F.sum((F.col("event_type") == "purchase").cast("int")) avoids a pivot, which is trickier in streaming.
  • Conversion. The official definition (lesson 04-05) is calculated per session and per day; in a ten-minute window only an approximation fits, for example purchases divided by active sessions. Give it another name on the dashboard: it is the "one definition per metric" rule.
  • The sink. The console sink is no good for a dashboard. Structured Streaming offers foreachBatch, which hands each micro-batch as a normal DataFrame to a function of yours, where you can write as usual:
def save_dashboard(batch, batch_id):
    """Spark calls this function once per micro-batch."""
    batch.coalesce(1).write.mode("overwrite").parquet(DASHBOARD_PATH)

query = (
    indicators.writeStream
    .outputMode("complete")
    .foreachBatch(save_dashboard)
    .option("checkpointLocation", CHECKPOINT_PATH)
    .trigger(processingTime="5 seconds")
    .start()
)

With complete mode, each micro-batch contains the whole results table, and overwriting it always leaves a small, consistent table. Remember from lesson 03-05 what that mode implies for the state.

  • The dashboard. A script that reads the table, keeps the latest windows and saves a PNG. You can rerun it by hand or with watch -n 5 python draw_dashboard.py.
  • Put it to the test. Launch the stream in one terminal and simulate_arrival.py in another. Increase NUM_FILES in the simulator to get more mileage out of it.
  • Clean-up. When you finish, stop the processes and delete ~/novamarket/stream if you want to start again from scratch.

Criteria for assessing yourself

Criterion Question
Definitions Does each indicator have an unambiguous name and definition, different from the daily KPIs?
Time Do you aggregate by event time? Have you decided what happens to late events?
State Do you know how much state your query keeps and whether it grows without limit?
Restart What happens if you stop the stream and relaunch it? And if you delete the checkpoint?
Freshness Does the dashboard show the time of the latest data?
Design Can it be understood in five seconds (lesson 04-05)?
Cost Have you estimated how much it costs and when it pays off?

Common mistakes and extensions

The typical mistakes are reusing another query's checkpoint, letting the state grow without a watermark, calling something "conversion" that is not, and forgetting a streaming process that is still running. As extensions: replace the folder of files with the web_events Kafka topic if you installed the optional nm-kafka container; add the fraud rule from lesson 03-05 as a second query; or compare the current window with the same time slot on the previous day, read from the lake.

Common Mistakes and Tips

  • Starting to program without having written down what is being asked. Half of the projects that fail solve well a question nobody asked.
  • Building everything and testing at the end. An error in the first join is dragged all the way to the chart. Check each step with a count() and a show().
  • Not validating against a known figure. You have several: €31,898,257.53 of net sales in the half-year, 20,000 orders, 200,000 events. Use them.
  • Handing over the console output. The deliverable is a conclusion, supported by a table and a chart, with its limitations.
  • Hiding what did not go well. Saying "the method fails with negations" increases confidence in everything else.
  • Looking at the solution too early. Getting stuck for twenty minutes and finding your own way out teaches you more than reading ten solutions.
  • Skipping best practices "because it's an exercise". Parameters, idempotency and validation are habits, and habits are formed in exercises.
  • Tip: keep these three projects in a repository with a README that explains what each one does. It is the start of a portfolio you can show.

Exercises

The exercises in this lesson are extensions of the projects.

Exercise 1: the full half-year

Generate the monthly report for the six months of data (January to June 2026) with a shell loop. Then check, with a query on gold/monthly_sales, that the sum of the six partitions matches the course's total net sales. How many rows does the table have? Which month sold the most?

Exercise 2: handling negation

Improve sentiment.py so that a lexicon word changes sign when one of the two preceding words is a negation (no, not, nor, nothing, none, without, never). Measure the new percentage of correct answers and explain which errors remain.

Exercise 3: deciding whether the dashboard is worth it

Without programming: Irene asks whether the dashboard from Project 3 should be running all year round. With what you learnt in lesson 05-03, reason out a recommendation: what it costs, which decision it improves, and what alternative you would propose.

Solutions

Exercise 1

for m in 01 02 03 04 05 06; do python monthly_report.py 2026-$m; done

Each run overwrites only its own partition. To check the result, for example from the pyspark shell or in a script:

from pathlib import Path
from pyspark.sql import functions as F

table = spark.read.parquet(str(Path.home() / "novamarket" / "lake" / "gold" / "monthly_sales"))
print(table.count())
table.groupBy("month").agg(F.round(F.sum("sales"), 2).alias("sales")).orderBy("month").show()
print(table.agg(F.round(F.sum("sales"), 2)).first()[0])
540
+-------+----------+
|  month|     sales|
+-------+----------+
|2026-01|5654500.76|
|2026-02|4854933.02|
|2026-03|5461945.68|
|2026-04|5214949.42|
|2026-05|5590229.81|
|2026-06|5121698.84|
+-------+----------+

31898257.53

The table has 540 rows (90 per month) and the sum, €31,898,257.53, is exactly the figure for sales excluding returns that you obtained in lesson 03-03. January is the month with the most sales and February the one with the least, which is largely explained by its having three fewer days: comparing months by their total without taking their length into account is a classic interpretation error. The month column appears at the end because it is the partition column.

Exercise 2

You need the position of each word and a window that looks backwards. Import Window (from pyspark.sql import SparkSession, Window) and replace the tokenisation block:

NEGATORS = ["no", "not", "nor", "nothing", "none", "without", "never"]
order = Window.partitionBy("review_id").orderBy("position")
words = (
    reviews
    .select("review_id",
            F.posexplode(F.split(F.lower("text"), "[^a-z]+")).alias("position", "word"))
    .where(F.col("word") != "")
    .withColumn("negated",
                F.coalesce(F.lag("word", 1).over(order).isin(NEGATORS), F.lit(False))
                | F.coalesce(F.lag("word", 2).over(order).isin(NEGATORS), F.lit(False)))
)

And, when adding up, a negated word reverses its value:

    .agg(F.sum(F.when(F.col("negated"), -F.col("value")).otherwise(F.col("value")))
         .alias("score"))
  • posexplode is like explode, but it adds the position of each element.
  • F.lag("word", 1) and F.lag("word", 2) bring in the previous word and the one two places before (lesson 03-03). The coalesce turns into false the null for the first words of each review.
+-------------+--------+-------+--------+
|true_polarity|positive|neutral|negative|
+-------------+--------+-------+--------+
|     negative|     161|   NULL|    2070|
|      neutral|    NULL|    599|    NULL|
|     positive|    3029|   NULL|     141|
+-------------+--------+-------+--------+

Correct: 5698 of 6000 (95.0%)

From 87.3% to 95.0%. The 302 remaining errors are the irony ("Great, another gadget…", 161 reviews) and the negation that comes afterwards ("…fragile or faulty, but not at all", 141). You could add another rule for the "but not", and then another, and another: that is the fate of hand-written rule systems, and the reason why language ended up being handled with models that learn.

Common mistake: applying the window after filtering the lexicon words. The previous word would then be the previous word in the lexicon, not in the text, and "not" would no longer be there.

Exercise 3

A reasoned answer:

  • Cost. A streaming process runs 24 hours a day. In the calculator from lesson 05-03, the streaming cluster was the most expensive item on the platform (about €4,200 a year at fictitious prices, almost 80% of compute), and that is without counting the attention it requires: a stream that goes down in the early hours needs someone to bring it back up.
  • Decision it improves. On a normal day, none: nobody changes anything in the shop because conversion over the last ten minutes is 11% instead of 12%. During a campaign, yes: detecting within minutes that payment is failing or that an offer is not loading is worth much more than the cost.
  • Recommendation. Do not keep it running permanently. Switch it on for campaigns and launches, on an ephemeral cluster, and for the rest of the year serve the daily dashboard from gold/daily_kpis. If the fraud detection stream is already running all year, consider whether the dashboard can share that infrastructure, at a small additional cost. And before building it, check that the website's technical monitoring does not already cover the need to "know whether the shop is working".

Conclusion

You have completed a full brief on NovaMarket's lake: a chained pipeline with a quality check, a new gold table, gold/monthly_sales, parameterised, idempotent and validated against an independent source, a ranking with window functions and two charts. You have taken the bronze → silver → gold pattern to a different kind of data, text, with a lexicon-based sentiment analysis that is right 87% of the time, and you have learnt the most important thing about it: look at where it fails before trusting the percentage. And you have a near-real-time dashboard laid out, whose design, and whose economic justification, are up to you.

This lesson brings Module 5 to a close. It began by arranging the rules you had been accumulating into a framework and teaching you to test your transformations; it continued with quality measured as code and the governance that decides who answers for each piece of data; it put figures on the cost of every technical decision; it went through five sectors to show what changes and what is repeated; and it has finished by putting everything to work in projects of your own. You have moved from knowing the techniques to practising the craft.

Throughout this journey you have worked with a reduced set of tools: Spark, Parquet, a little Kafka, Airflow on paper. It was a deliberate decision, because to learn the concepts one tool of each type is enough. But as soon as you leave the practice environment you will come across platforms that have been in production for fifteen years, dozens of names in every job advert and legacy architectures that nobody is going to rewrite; and the case studies have shown you that each problem calls for different pieces. To choose well, and to understand what already exists in a company, you need the complete map. That is the purpose of Module 6, Big Data Tools and Platforms. Its first lesson, The Apache Hadoop Ecosystem, goes back to the origins: you will see what became of HDFS, YARN and MapReduce, which tools grew up around them, starting with the ones that let you query with SQL what you processed by hand in lesson 03-01, and which of them are still in use today.

© Copyright 2026. All rights reserved