So far the course has been conceptual. From Module 2 onwards you are going to get hands-on: storing data in different formats, processing it with Apache Spark, analysing it and visualising it. For that you need two things: a working environment on your own computer and some data to practise with.
In this lesson you will prepare both. You will install the essential tools (Python, Java and PySpark), get the optional ones ready (Jupyter and Docker), check that everything works and generate NovaMarket's five fictional datasets with a reproducible script. You do not need a cluster or a cloud account: Spark can run in local mode, using your laptop's cores as if they were the nodes of a miniature cluster, and that is enough to learn everything we will cover.
Take as long as you need and do not move on to the next module until the checks in this lesson work: it is the foundation for all the practical work that follows.
What you will need
| Component | Required? | What for | When it is used |
|---|---|---|---|
| Python 3 | Yes | The main language of the course | From now on |
| Java (JDK) | Yes | Spark runs on the Java virtual machine | From Module 3 |
| Virtual environment | Yes | Isolating the course libraries from the rest of the system | From now on |
| PySpark | Yes | Apache Spark, usable from Python | From Module 3 |
| pandas | Yes | Analysing small samples | We already used it in lesson 01-02 |
| Jupyter | Optional | Interactive notebooks for exploring data | Whenever you prefer it to scripts |
| Docker | Optional | Starting services such as Kafka or MongoDB without installing them | In specific lessons of Modules 2 and 3 |
Hardware requirements: any reasonably recent laptop will do. As a guide, 8 GB of RAM (preferably 16), about 5 GB of free disk space and a Linux, macOS or Windows operating system.
If you use Windows, the firm recommendation is to work inside WSL 2 (Windows Subsystem for Linux) with an Ubuntu distribution. Big Data tools were born on Linux and run there without friction; on native Windows additional problems crop up that add nothing to the learning. You install it from a PowerShell terminal opened as administrator with
wsl --install, and from then on you follow the Linux instructions. All the commands in this lesson are typed inside the Ubuntu terminal.
About versions: tools evolve quickly. In this lesson we avoid pinning specific versions; whenever one is mentioned, always check the current one in the official documentation.
Python 3
First check whether you already have it. Open a terminal and type:
If the answer is something like Python 3.12.4, it is already installed. You need a relatively recent version of Python 3: current versions of PySpark require, at the time of writing this lesson, Python 3.10 or later.
If you do not have it or it is too old:
| System | Installation |
|---|---|
| Ubuntu / Debian / WSL | sudo apt update && sudo apt install python3 python3-venv python3-pip |
| macOS (with Homebrew) | brew install python |
| Native Windows | The python.org installer (ticking "Add Python to PATH"), although WSL is recommended |
On Ubuntu and Debian the python3-venv package is needed to create virtual environments; it does not always come with the basic installation.
Java (JDK)
Apache Spark is written in Scala and runs on the Java virtual machine (JVM). When you use PySpark, your Python code will give orders to a Java process that does the heavy lifting. That is why you need a JDK (Java Development Kit) installed, even though you will not write a single line of Java.
Check whether you already have it:
A response such as openjdk version "17.0.12" tells you that it is installed and which version it is. Each version of Spark supports specific versions of Java. At the time of writing this lesson, the Spark 4 series works with Java 17 and Java 21, which are long-term support (LTS) versions. Avoid both very old versions (Java 8 or 11) and the most recent, newly released one, which may not be supported yet.
| System | Installation |
|---|---|
| Ubuntu / Debian / WSL | sudo apt install openjdk-17-jdk (or openjdk-21-jdk, depending on what your distribution offers) |
| macOS (with Homebrew) | brew install openjdk@17 |
| Native Windows | The installer of an OpenJDK distribution, such as Eclipse Temurin |
After installing it, run java -version again to confirm. If you have several versions of Java and Spark is not using the right one, see the troubleshooting section at the end of the lesson: it is solved with the JAVA_HOME environment variable.
The working folder and the virtual environment
The ~/novamarket/ structure
All the practical work in the course will be done inside a single folder in your home directory. The ~ symbol is shorthand for that directory (for example, /home/laura on Linux or /Users/laura on macOS).
mkdir -pcreates thenovamarketfolder and, inside it,data. The-poption creates any intermediate folders needed and does not raise an error if they already exist.cd ~/novamarkettakes you inside it. From now on, every command in the course assumes you are in this folder.
By the end of the lesson, the structure will look like this:
~/novamarket/ ├── .venv/ Python virtual environment (not edited by hand) ├── data/ │ ├── customers.csv │ ├── products.csv │ ├── orders.csv │ ├── order_lines.csv │ └── web_events.json ├── check_spark.py ├── generate_data.py └── check_data.py
The virtual environment
A virtual environment is a folder containing an isolated copy of Python with its own libraries. Installing what the course needs there has two advantages: it does not interfere with other projects or with the system Python, and if something breaks you only have to delete the folder and create it again.
- The first line creates the environment in the
.venvfolder (you do this only once). - The second activates it. You will notice that the terminal prompt now starts with
(.venv). While it is active,pythonandpiprefer to the environment's own.
On native Windows (PowerShell), activation is .venv\Scripts\Activate.ps1.
Important: activation only lasts while the terminal is open. Every time you open a new terminal to work on the course you will have to repeat
cd ~/novamarketandsource .venv/bin/activate. Forgetting to do so is the most common cause of the errorModuleNotFoundError: No module named 'pyspark'.
To leave the environment, use the deactivate command.
Installing PySpark (and Jupyter, optional)
With the virtual environment activated:
- The first line upgrades
pip, Python's package installer. - The second installs PySpark and pandas. The
pysparkpackage is not just a Python library: it includes the whole of Apache Spark, ready to run in local mode. That is why the download is bulky (several hundred MB) and may take a few minutes.
We use python -m pip instead of plain pip to make sure it installs into the Python of the active environment.
Check the installation:
It should display a version number. If an error appears, check that the environment is activated.
Jupyter (optional)
Jupyter lets you work with notebooks: documents that mix code, results and text, and that are run cell by cell. They are very convenient for exploring data. The whole course can be followed with ordinary scripts, so install it only if you feel like it:
The second command opens JupyterLab in your browser. As it is launched from the virtual environment, the notebooks will have PySpark and pandas available. To stop it, press Ctrl + C in the terminal.
Docker (optional)
Docker lets you run applications inside containers: self-contained packages that include the program and everything it needs. Its usefulness for us is very specific: later on there will be lessons where it helps to have a service such as Kafka or MongoDB running, and with Docker you start it with one command and remove it with another, without installing anything permanently.
For now we are only going to install it and check that it works. You can leave this step until the time comes.
| System | Installation |
|---|---|
| Windows and macOS | Docker Desktop (on Windows, with WSL 2 integration enabled) |
| Linux | Docker Engine, following the official guide for your distribution |
Check:
- The first line shows the installed version.
- The second downloads a minimal test image, runs it and displays a message beginning with
Hello from Docker!. The--rmoption removes the container when it finishes, so as not to leave anything behind.
On Linux, if a permissions error appears (permission denied), put sudo in front of the command or add your user to the docker group as the official documentation explains.
Verification: your first PySpark script
Let us confirm that Python, Java and PySpark work together. Create the file ~/novamarket/check_spark.py with this content:
from pyspark.sql import SparkSession
# 1. We start Spark in local mode
spark = (
SparkSession.builder
.master("local[*]")
.appName("check_environment")
.getOrCreate()
)
# 2. We show the version and run a minimal computation
print("Spark version:", spark.version)
numbers = spark.range(1_000_000)
print("Rows counted:", numbers.count())
# 3. We stop Spark and release resources
spark.stop()And run it:
Spark will be studied in depth in lesson 03-02; for now it is enough to understand the essentials:
SparkSessionis the entry point to Spark: every program starts by creating one..master("local[*]")says where it runs.localmeans "on this very machine, with no cluster", and[*]means "using all the available cores". It is the miniature version of the cluster we described in lesson 01-04: each core acts as a worker node..appName(...)gives the program a name and.getOrCreate()creates the session.spark.range(1_000_000)generates a table of one million rows with the numbers from 0 to 999,999, and.count()counts them. The computation is trivial; what matters is that, in order to do it, Spark starts up, spreads the work across the cores and returns the result.spark.stop()closes the session.
After a few seconds (Spark does not start instantly) you should see, among other messages:
It is normal for several warning lines beginning with WARN to appear first, for example one saying that the native Hadoop library could not be loaded (Unable to load native-hadoop library). They are not errors and you can ignore them. If what appears is an error that prevents you from seeing the two lines above, go to the troubleshooting section.
Generating the NovaMarket data
In lesson 01-01 we introduced NovaMarket's five datasets. The real figures (2 million customers, 40 million daily events) do not fit comfortably on a laptop, nor are they needed for learning. We are going to generate a scaled-down version, with the same structure:
| Dataset | Real size at NovaMarket | Practice size |
|---|---|---|
customers |
~2 million | 1,000 |
products |
Tens of thousands | 200 |
orders |
~50,000 a day | 20,000 (six months) |
order_lines |
~125,000 a day | ~50,000 |
web_events |
~40 million a day | 200,000 (one month) |
The script that follows has three features worth highlighting:
- It uses only Python's standard library: there is nothing else to install.
- It is reproducible. It uses a fixed seed for the random number generator, so that every run produces exactly the same files. That way, your results will match the ones shown in the lessons.
- It introduces quality defects on purpose: a few empty values and duplicate records. Real data never arrives clean (remember veracity, lesson 01-03), and later on you will learn to detect and fix precisely these defects.
Create the file ~/novamarket/generate_data.py with the following content. It is long, but it is divided into numbered blocks that are explained afterwards.
"""Generates the fictional NovaMarket data for the course's practical work.
Usage: python generate_data.py
Creates five files in ~/novamarket/data/. Uses only the standard library.
"""
import csv
import json
import random
from datetime import datetime, timedelta
from pathlib import Path
# ----------------------------------------------------------------------
# 1. Configuration
# ----------------------------------------------------------------------
SEED = 42
DATA_DIR = Path.home() / "novamarket" / "data"
NUM_CUSTOMERS = 1_000
NUM_PRODUCTS = 200
NUM_ORDERS = 20_000
NUM_EVENTS = 200_000
# Quality problems introduced on purpose
CUSTOMERS_WITHOUT_PROVINCE = 20
ORDERS_WITHOUT_AMOUNT = 200
DUPLICATE_ORDERS = 100
EVENTS_WITHOUT_DEVICE = 1_000
DUPLICATE_EVENTS = 500
# Time periods (the end instant is not included)
SIGNUPS_START, SIGNUPS_END = datetime(2022, 1, 1), datetime(2026, 1, 1)
ORDERS_START, ORDERS_END = datetime(2026, 1, 1), datetime(2026, 7, 1)
EVENTS_START, EVENTS_END = datetime(2026, 6, 1), datetime(2026, 7, 1)
rng = random.Random(SEED)
# ----------------------------------------------------------------------
# 2. Catalogues of possible values
# ----------------------------------------------------------------------
FIRST_NAMES = ["Lucia", "Hugo", "Martina", "Pablo", "Sofia", "Daniel", "Julia",
"Alejandro", "Paula", "Adrian", "Carmen", "Javier", "Elena",
"Sergio", "Nuria", "Carlos", "Marta", "Jordi", "Ana", "Raul"]
SURNAMES = ["Garcia", "Martinez", "Lopez", "Sanchez", "Perez", "Gomez",
"Fernandez", "Ruiz", "Navarro", "Torres", "Vidal", "Ferrer",
"Molina", "Serrano", "Ortega", "Castillo", "Soler", "Romero",
"Iglesias", "Pascual"]
# Province -> weight (NovaMarket sells more close to its base, Valencia)
PROVINCES = {"Valencia": 22, "Madrid": 18, "Barcelona": 16, "Alicante": 9,
"Sevilla": 6, "Castellon": 5, "Murcia": 5, "Malaga": 4,
"Zaragoza": 4, "Bizkaia": 3, "A Coruna": 3, "Asturias": 2,
"Illes Balears": 2, "Las Palmas": 1}
# Category -> (product types, minimum price, maximum price)
CATEGORIES = {
"computing": (["Laptop", "Monitor", "Keyboard", "Mouse", "SSD Drive"], 15, 1500),
"phones": (["Smartphone", "Case", "Charger", "Smartwatch"], 8, 1200),
"audio": (["Headphones", "Speaker", "Soundbar"], 12, 600),
"television": (["Television", "TV Mount", "Media Player"], 20, 2000),
"appliances": (["Coffee Maker", "Vacuum Cleaner", "Microwave", "Blender"], 25, 800),
"home": (["Lamp", "Chair", "Bookshelf", "Rug"], 10, 400),
}
BRANDS = ["Nova", "Altea", "Turia", "Lumen", "Kore", "Vento"]
STATUSES = ["pending", "shipped", "delivered", "returned"]
STATUS_WEIGHTS = [5, 10, 80, 5]
CHANNELS = ["web", "app"]
CHANNEL_WEIGHTS = [60, 40]
EVENT_TYPES = ["product_view", "search", "add_to_cart", "purchase"]
EVENT_TYPE_WEIGHTS = [70, 15, 11, 4]
DEVICES = ["mobile", "desktop", "tablet"]
DEVICE_WEIGHTS = [60, 32, 8]
# ----------------------------------------------------------------------
# 3. Helper functions
# ----------------------------------------------------------------------
def random_instant(start, end):
"""Returns a random datetime in the interval [start, end)."""
seconds = int((end - start).total_seconds())
return start + timedelta(seconds=rng.randrange(seconds))
def write_csv(name, header, rows):
"""Writes a list of rows to a CSV file (UTF-8, comma-separated)."""
path = DATA_DIR / name
with open(path, "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow(header)
writer.writerows(rows)
print(f"{name:<20} {len(rows):>8} rows")
def write_jsonl(name, records):
"""Writes a list of dictionaries in JSON Lines format."""
path = DATA_DIR / name
with open(path, "w", encoding="utf-8") as f:
for record in records:
f.write(json.dumps(record) + "\n")
print(f"{name:<20} {len(records):>8} lines")
# ----------------------------------------------------------------------
# 4. Generators for each dataset
# ----------------------------------------------------------------------
def generate_customers():
provinces = list(PROVINCES)
weights = list(PROVINCES.values())
rows = []
for customer_id in range(1, NUM_CUSTOMERS + 1):
name = f"{rng.choice(FIRST_NAMES)} {rng.choice(SURNAMES)}"
province = rng.choices(provinces, weights=weights)[0]
signup_date = random_instant(SIGNUPS_START, SIGNUPS_END).strftime("%Y-%m-%d")
rows.append([customer_id, name, province, signup_date])
# Quality problem: some customers with no province (empty field)
for row in rng.sample(rows, CUSTOMERS_WITHOUT_PROVINCE):
row[2] = ""
return rows
def generate_products():
categories = list(CATEGORIES)
rows = []
for product_id in range(1, NUM_PRODUCTS + 1):
category = rng.choice(categories)
types, min_price, max_price = CATEGORIES[category]
name = f"{rng.choice(types)} {rng.choice(BRANDS)} {rng.randint(100, 999)}"
price = round(rng.uniform(min_price, max_price), 2)
rows.append([product_id, name, category, f"{price:.2f}"])
return rows
def generate_orders_and_lines(products):
prices = {p[0]: float(p[3]) for p in products}
product_ids = list(prices)
orders, lines = [], []
# The instants are generated and sorted: order 1 is the oldest
instants = sorted(random_instant(ORDERS_START, ORDERS_END)
for _ in range(NUM_ORDERS))
for order_id, instant in enumerate(instants, start=1):
customer_id = rng.randint(1, NUM_CUSTOMERS)
num_lines = rng.choices([1, 2, 3, 4], weights=[20, 30, 30, 20])[0]
total_amount = 0.0
for product_id in rng.sample(product_ids, num_lines):
quantity = rng.choices([1, 2, 3], weights=[75, 20, 5])[0]
unit_price = prices[product_id]
total_amount += quantity * unit_price
lines.append([order_id, product_id, quantity, f"{unit_price:.2f}"])
status = rng.choices(STATUSES, weights=STATUS_WEIGHTS)[0]
channel = rng.choices(CHANNELS, weights=CHANNEL_WEIGHTS)[0]
orders.append([order_id, customer_id,
instant.strftime("%Y-%m-%d %H:%M:%S"),
f"{total_amount:.2f}", status, channel])
# Quality problem 1: orders with no total_amount (empty field)
for row in rng.sample(orders, ORDERS_WITHOUT_AMOUNT):
row[3] = ""
# Quality problem 2: repeated order rows (exact duplicates)
duplicates = [list(row) for row in rng.sample(orders, DUPLICATE_ORDERS)]
for row in duplicates:
orders.insert(rng.randrange(len(orders) + 1), row)
return orders, lines
def generate_events():
events = []
session_num = 0
while len(events) < NUM_EVENTS:
# Each session has one customer (or none, if browsing without signing in),
# one device and between 1 and 12 consecutive events
session_num += 1
session_id = f"s-{session_num:06d}"
customer_id = rng.randint(1, NUM_CUSTOMERS) if rng.random() < 0.7 else None
device = rng.choices(DEVICES, weights=DEVICE_WEIGHTS)[0]
instant = random_instant(EVENTS_START, EVENTS_END)
for _ in range(rng.randint(1, 12)):
event_type = rng.choices(EVENT_TYPES, weights=EVENT_TYPE_WEIGHTS)[0]
# Searches do not refer to any specific product
product_id = None if event_type == "search" else rng.randint(1, NUM_PRODUCTS)
events.append({
"customer_id": customer_id,
"session_id": session_id,
"event_type": event_type,
"product_id": product_id,
"event_time": instant.strftime("%Y-%m-%dT%H:%M:%S"),
"device": device,
})
instant += timedelta(seconds=rng.randint(5, 180))
events = events[:NUM_EVENTS]
# Chronological order and sequential event_id
events.sort(key=lambda e: e["event_time"])
events = [{"event_id": f"ev-{i:07d}", **e} for i, e in enumerate(events, start=1)]
# Quality problem 1: events with no device (null)
for event in rng.sample(events, EVENTS_WITHOUT_DEVICE):
event["device"] = None
# Quality problem 2: repeated events (same event_id)
duplicates = [dict(e) for e in rng.sample(events, DUPLICATE_EVENTS)]
for event in duplicates:
events.insert(rng.randrange(len(events) + 1), event)
return events
# ----------------------------------------------------------------------
# 5. Main program
# ----------------------------------------------------------------------
def main():
DATA_DIR.mkdir(parents=True, exist_ok=True)
print(f"Generating data in {DATA_DIR} (seed {SEED})")
customers = generate_customers()
products = generate_products()
orders, lines = generate_orders_and_lines(products)
events = generate_events()
write_csv("customers.csv",
["customer_id", "name", "province", "signup_date"], customers)
write_csv("products.csv",
["product_id", "name", "category", "price"], products)
write_csv("orders.csv",
["order_id", "customer_id", "order_date", "total_amount",
"status", "channel"], orders)
write_csv("order_lines.csv",
["order_id", "product_id", "quantity", "unit_price"], lines)
write_jsonl("web_events.json", events)
print("Done.")
if __name__ == "__main__":
main()Run it from ~/novamarket, with the virtual environment activated:
Within a few seconds it will display:
Generating data in /home/your_user/novamarket/data (seed 42) customers.csv 1000 rows products.csv 200 rows orders.csv 20100 rows order_lines.csv 50107 rows web_events.json 200500 lines Done.
How the script works
Block 1: configuration. It gathers at the top all the values you might want to change: the seed, the destination folder, the sizes and the number of defects. Path.home() returns your home directory on any operating system, so the script works the same on Linux, macOS and Windows. The key line is rng = random.Random(SEED): it creates a dedicated random number generator, initialised with the seed 42. A computer's "random" generator actually follows a sequence determined by its seed; with the same seed, the sequence is always the same. The whole script uses rng, and that is why the result is reproducible.
Block 2: catalogues. These are the lists of possible values. Text values are written without accents or other special characters (Castellon, Malaga, A Coruna) to avoid encoding problems between tools. Some lists carry weights that indicate relative frequency: 80% of orders will be delivered, 60% of events will come from mobile, and Valencia will have more customers than the other provinces.
Block 3: helper functions.
random_instantworks out how many seconds there are between two dates, picks a number of seconds at random and adds it to the start date.write_csvuses thecsvmodule from the standard library. Thenewline=""parameter is the recommended mode for writing CSV (it avoids interleaved blank lines on Windows) andencoding="utf-8"sets the encoding.write_jsonlwrites in JSON Lines format: each line of the file is a complete, independent JSON object. It is the usual format for events, because it lets you read the file line by line without loading it all into memory and append events at the end without rewriting anything.
Block 4: generators.
generate_customersandgenerate_productscreate one row per identifier, picking values from the catalogues.rng.choices(list, weights=weights)[0]picks one element according to the weights (it returns a list, hence the[0]).generate_orders_and_linesgenerates both datasets at once so that they are consistent: each order has between one and four lines with different products (rng.samplepicks without repetition), theunit_priceof each line is the catalogue price, and the order'stotal_amountis exactly the sum ofquantity × unit_priceover its lines. That relationship will allow you, later on, to rebuild the missing amounts.generate_eventsworks by sessions: each session has one customer (or none: 30% of sessions belong to unidentified visitors), one device and between 1 and 12 events a few seconds apart. At the end they are all sorted chronologically and given a sequentialevent_id.
At the end of each generator the defects are introduced: some rows are picked at random to have a field emptied and others to be inserted again at random positions.
Block 5: main program. main creates the data folder if it does not exist, calls the generators and writes the five files. The condition if __name__ == "__main__": means that main only runs when the file is launched as a program.
Fact sheet for the generated data
Keep this table for reference: it describes exactly what each file contains.
| File | Records | Format and details |
|---|---|---|
customers.csv |
1,000 | customer_id from 1 to 1,000. signup_date in the format YYYY-MM-DD, between 2022-01-01 and 2025-12-31. 14 possible provinces. |
products.csv |
200 | product_id from 1 to 200. Six categories: computing, phones, audio, television, appliances, home. price with two decimal places and a decimal point. |
orders.csv |
20,100 rows (20,000 distinct orders) | order_id from 1 to 20,000, in chronological order. order_date in the format YYYY-MM-DD HH:MM:SS, between 2026-01-01 and 2026-06-30. status: pending, shipped, delivered, returned. channel: web, app. |
order_lines.csv |
50,107 | From 1 to 4 lines per order; quantity from 1 to 3. |
web_events.json |
200,500 lines (200,000 distinct events) | JSON Lines. event_id of the form ev-0000001; session_id of the form s-000001. event_time in the ISO 8601 format YYYY-MM-DDTHH:MM:SS, during June 2026. event_type: product_view, search, add_to_cart, purchase. device: mobile, desktop, tablet. |
All the CSV files have a header as their first line, use the comma as separator and are encoded in UTF-8. The five together take up about 38 MB, of which 37 MB corresponds to web_events.json: even at reduced scale, the clickstream dominates the volume.
Quality defects introduced
| File | Defect | Number | How it appears |
|---|---|---|---|
customers.csv |
Customers with no province |
20 | Empty field |
orders.csv |
Orders with no total_amount |
200 orders | Empty field |
orders.csv |
Duplicate rows | 100 | An exact copy of another row, at a random position |
web_events.json |
Events with no device |
1,000 events | null value |
web_events.json |
Duplicate events | 500 | Repeated line, with the same event_id |
One detail you will see in the checks: since some of the duplicated rows happen to be ones that had the empty field, when you count rows (not distinct orders or events) 201 empty amounts and 1,003 null devices appear. It is a good reminder that quality defects compound one another.
Not all missing values are defects. In web_events, a null customer_id means that the visitor had not signed in, and a null product_id appears in searches, which do not refer to a specific product. These are legitimate absences: they are part of the meaning of the data. Telling one kind from the other is an important skill that we will practise.
Limitations you should be aware of
This is synthetic data, designed for learning techniques and not for drawing business conclusions:
- The values are random: there is no seasonality, no trending products and no customers with definite tastes.
ordersandweb_eventsare generated independently: an event of typepurchasedoes not correspond to a specific row inorders.- The orders span six months and the events only June 2026 (sessions that start late on the 30th may end in the first few minutes of 1 July).
Checking the generated files
Never accept a file as good without looking at it. Start with a quick inspection from the terminal:
ls -lhlists the files with their size in human-readable units.wc -lcounts the lines in each file.head -n 3shows the first three lines.
The line count should be this (the CSV files have one more line than data rows, because of the header):
1001 data/customers.csv
50108 data/order_lines.csv
20101 data/orders.csv
201 data/products.csv
200500 data/web_events.json
271911 totalAnd the beginning of the orders and events files:
order_id,customer_id,order_date,total_amount,status,channel 1,799,2026-01-01 00:02:39,1353.13,delivered,app 2,86,2026-01-01 00:09:59,601.58,shipped,web
{"event_id": "ev-0000001", "customer_id": 770, "session_id": "s-017684", "event_type": "purchase", "product_id": 142, "event_time": "2026-06-01T00:01:27", "device": "desktop"}
{"event_id": "ev-0000002", "customer_id": null, "session_id": "s-006870", "event_type": "product_view", "product_id": 119, "event_time": "2026-06-01T00:02:06", "device": "mobile"}If your lines are identical, your environment reproduces the course data exactly. If the counts match but the values differ, the most likely explanation is that your version of Python generates a slightly different random sequence: that is not a problem for following the course, although some figures in the examples will not match yours to the penny.
A more thorough check with Python
To verify the quality defects as well, create ~/novamarket/check_data.py:
import csv
import json
from collections import Counter
from pathlib import Path
DATA_DIR = Path.home() / "novamarket" / "data"
# --- CSV files: rows, columns and empty values ------------------------
for name in ["customers.csv", "products.csv", "orders.csv", "order_lines.csv"]:
with open(DATA_DIR / name, newline="", encoding="utf-8") as f:
rows = list(csv.DictReader(f))
empty = sum(1 for row in rows for value in row.values() if value == "")
print(f"{name:<18} rows={len(rows):<7} empty={empty:<5} columns={list(rows[0])}")
# --- Orders: repeated identifiers -------------------------------------
with open(DATA_DIR / "orders.csv", newline="", encoding="utf-8") as f:
ids = [row["order_id"] for row in csv.DictReader(f)]
print(f"orders: {len(ids)} rows, {len(set(ids))} distinct order_id values")
# --- Events: read line by line (JSON Lines) ---------------------------
total = 0
event_ids = set()
types = Counter()
without_device = 0
with open(DATA_DIR / "web_events.json", encoding="utf-8") as f:
for line in f:
event = json.loads(line)
total += 1
event_ids.add(event["event_id"])
types[event["event_type"]] += 1
if event["device"] is None:
without_device += 1
print(f"events: {total} lines, {len(event_ids)} distinct event_id values, "
f"{without_device} with no device")
for event_type, count in types.most_common():
print(f" {event_type:<16} {count:>7} ({count / total:.1%})")Points worth understanding:
- For the CSV files we use
csv.DictReader, which you already know from lesson 01-03. The expression that computesemptygoes through every row and every one of its values and counts those that are an empty string. set(ids)builds a set, which removes repeats: comparing its size with that of the list reveals how many duplicates there are.- The events file is not loaded in full: it is traversed with
for line in f, parsing each line separately withjson.loads. This is the correct way to read JSON Lines and it works just as well with a 37 MB file as with a 37 GB one, because only one line is in memory at any given moment. In JSON,nullbecomes Python'sNone.
When you run python check_data.py you should get:
customers.csv rows=1000 empty=20 columns=['customer_id', 'name', 'province', 'signup_date'] products.csv rows=200 empty=0 columns=['product_id', 'name', 'category', 'price'] orders.csv rows=20100 empty=201 columns=['order_id', 'customer_id', 'order_date', 'total_amount', 'status', 'channel'] order_lines.csv rows=50107 empty=0 columns=['order_id', 'product_id', 'quantity', 'unit_price'] orders: 20100 rows, 20000 distinct order_id values events: 200500 lines, 200000 distinct event_id values, 1003 with no device product_view 140451 (70.1%) search 29992 (15.0%) add_to_cart 21969 (11.0%) purchase 8088 (4.0%)
With that, the environment and the data are ready.
Troubleshooting common problems
| Symptom | Likely cause | Solution |
|---|---|---|
ModuleNotFoundError: No module named 'pyspark' |
The virtual environment is not activated in this terminal | cd ~/novamarket and source .venv/bin/activate |
JAVA_HOME is not set or Java gateway process exited before sending its port number |
Java is not installed or Spark cannot find it | Install a JDK and set JAVA_HOME (see below) |
UnsupportedClassVersionError or errors about the Java version |
The Java version is not compatible with the Spark version | Install a supported version and point JAVA_HOME to it |
| Error about the Python version when installing PySpark | Python is too old | Install a more recent version and recreate the virtual environment |
python3 -m venv fails with a message about ensurepip |
The virtual environments package is missing (Ubuntu/Debian) | sudo apt install python3-venv |
WARN messages when Spark starts |
Normal informational messages | Ignore them |
Spark takes a long time to start or fails because of the host name (UnknownHostException) |
A problem resolving the computer's name | Run export SPARK_LOCAL_IP=127.0.0.1 before the script |
On native Windows, errors mentioning winutils.exe or HADOOP_HOME |
Spark needs Hadoop utilities that Windows does not include | Use WSL 2: it avoids the problem altogether |
docker: permission denied on Linux |
The user does not belong to the docker group |
Put sudo in front or add the user to the group |
Setting JAVA_HOME
JAVA_HOME is an environment variable that says which folder the JDK is installed in. Spark consults it to decide which Java to use, so setting it solves both the "cannot find Java" case and the "uses the wrong version" case.
First locate the installation folder:
# Linux: shows the installed Java versions and their paths
update-alternatives --list java
# macOS: shows the path of JDK 17
/usr/libexec/java_home -v 17On Linux, the path you need is the one shown without the trailing /bin/java; for example, /usr/lib/jvm/java-17-openjdk-amd64. Then set the variable (adapt the path to yours):
These lines only take effect in the current terminal. To make them permanent, add them to the end of the ~/.bashrc file (or ~/.zshrc if your terminal uses zsh, as is the default on macOS) and open a new terminal. Check the result with:
If you use WSL
- Always work inside the Linux file system (
~/novamarket), not in the Windows folders mounted under/mnt/c/...: access to the latter is much slower. - Install Python and Java inside Ubuntu with
apt. The versions installed on Windows are no use inside WSL. - If you use Docker Desktop, enable integration with your WSL distribution in its settings.
If nothing works
Follow this diagnostic order, which goes from the most basic to the most specific:
python3 --version: is there a recent Python?java -version: is there a compatible Java?- Does
(.venv)appear at the start of the terminal prompt? python -c "import pyspark; print(pyspark.__version__)": is PySpark installed in the environment?python check_spark.py: read the first error line, not the last; it is usually the one that explains the cause.
As a last resort, delete the environment (rm -rf ~/novamarket/.venv) and create it again. Your scripts and your data are not affected.
Common Mistakes and Tips
- Forgetting to activate the virtual environment. This is by far the most common stumbling block. Get into the habit of checking that
(.venv)appears in the terminal before running anything. - Installing with
sudo pipor outside the environment. It mixes the course libraries with the system ones and causes conflicts that are hard to undo. Always install with the environment activated and withoutsudo. - Changing the seed or the sizes "just to try". You can, but your results will no longer match those of the course. If you experiment, go back to the original values afterwards and regenerate the data.
- Editing the files in
data/by hand. Treat them as read-only source data. If they get damaged, you regenerate them withpython generate_data.py: that is the advantage of their being reproducible. - "Fixing" the quality defects now. They are there on purpose. We will deal with them with the right tools when the time comes.
- Opening
web_events.jsonwith an ordinary text editor. At 37 MB some editors freeze. To take a look, usehead. - Tip: if you know a version control system such as Git, you can keep your course scripts in it. In that case, exclude the
.venv/anddata/folders: what you version is the code that generates the data, not the data.
Exercises
Exercise 1: exploring the data from the terminal
Without writing any Python, using only terminal commands, answer:
- How many orders (rows) are recorded with the status
returned? - How many events (lines) are of type
purchase?
Hint: the command grep -c "text" file counts the lines of a file that contain a given text.
Exercise 2: orders by channel
Write a script orders_by_channel.py that reads data/orders.csv with the standard library and shows how many rows there are for each channel. Then improve it so that it counts distinct orders, ignoring the duplicate rows.
Exercise 3: reading a real file with Spark
Extend check_spark.py (or make a copy) so that, as well as counting the range, it reads data/orders.csv and counts its rows. You will need the statement spark.read.csv(path, header=True), which returns a table on which you can call .count(). What number do you expect to get?
Solutions
Exercise 1
Results: 1003 rows of returned orders and 8088 purchase events.
Notice the commas around returned: they delimit the field and avoid accidental matches with other text. In the second command single quotes are used on the outside because the text being searched for contains double quotes.
An important nuance: grep counts lines, so both figures include any duplicate rows. For a rigorous count you have to remove duplicates first, which is exactly what the next exercise asks for.
Exercise 2
import csv
from collections import Counter
from pathlib import Path
ORDERS_PATH = Path.home() / "novamarket" / "data" / "orders.csv"
rows_by_channel = Counter()
channel_by_order = {}
with open(ORDERS_PATH, newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
rows_by_channel[row["channel"]] += 1
# A dictionary only keeps one entry per key:
# duplicate rows are overwritten without adding to the count
channel_by_order[row["order_id"]] = row["channel"]
orders_by_channel = Counter(channel_by_order.values())
print("Rows by channel: ", dict(rows_by_channel))
print("Orders by channel:", dict(orders_by_channel))The first count gives 12,073 rows for web and 8,027 for app (20,100 in total). The second adds up to exactly 20,000, with slightly lower figures for each channel. The difference between the two, one hundred rows, is the duplicates. The trick lies in using order_id as the key of a dictionary: when a key is repeated, the value is replaced instead of being added.
Common mistake: counting the lines in the file and subtracting one for the header, taking it for granted that each line is an order. With real data, that assumption almost never holds.
Exercise 3
from pathlib import Path
from pyspark.sql import SparkSession
spark = (
SparkSession.builder
.master("local[*]")
.appName("check_environment")
.getOrCreate()
)
path = str(Path.home() / "novamarket" / "data" / "orders.csv")
orders = spark.read.csv(path, header=True)
print("Rows in orders.csv:", orders.count())
spark.stop()The expected result is 20100: the 20,000 order rows plus the 100 duplicates. The header=True option tells Spark that the first line contains the column names and must not be counted as data; without it you would get 20,101. The path is converted to text with str(...) because Spark expects a string.
You have just used Spark to read a file. Exactly what happens under the hood — and why that same line would work just the same with a file a thousand times larger spread across a cluster — is what you will learn in Module 3.
Conclusion
With this lesson your workbench is ready:
- Python 3, Java (JDK) and PySpark installed, with a virtual environment that isolates the course libraries.
- Jupyter and Docker optionally available for when they prove useful.
- Spark verified in local mode, where your computer's cores play the part of the nodes of a cluster.
- The
~/novamarket/folder with the five datasets indata/, generated reproducibly withgenerate_data.py, and with deliberate quality defects that we will put to use later on.
This is the end of Module 1. In five lessons you have covered the whole of the introduction: what Big Data is and how it is characterised by the Vs; what it is for and which use cases NovaMarket is pursuing; what challenges it poses and how to decide whether a problem requires it; how a data platform is organised into layers; and, finally, you have prepared the environment for putting it into practice.
Take a look at the files you have just created. They are in CSV and JSON format, in a folder on a single disk in a single machine. For 38 MB that is perfect. But NovaMarket generates several GB of events every day: where are they stored when they do not fit on any disk? What happens if the machine holding them breaks down? Module 2, Big Data Storage Technologies, answers those questions. We will start with the part on which everything else rests: distributed file systems, which distribute and replicate files across the nodes of a cluster by applying the ideas of partitioning and replication you saw in lesson 01-04.
