In this post we are going to cover how to build a PySpark pipeline with Claude Code, from a messy CSV file and a JSON file to clean Parquet, with unit tests. Claude reads the raw data, plans the pipeline in plan mode, writes the code, runs it with Spark in local mode on a laptop, and writes pytest tests. The last step is to cross-check the Parquet output with DuckDB and save the commands in CLAUDE.md.
Claude Code is Claude working inside your project folder. It can read your files, write code and run commands in your terminal, and it asks before it edits a file or runs a command unless you allow it. For a data engineer that means Claude does not just write Spark code that looks right. It runs spark-submit and pytest and works from the real output. Every Spark output in this post is real.
Part 4 of the Claude for Data Engineers series on TechBrothersIT.
Let's create some sample data
Our project is shop-pipeline. It has raw orders in data/raw/orders.csv (22 rows) and customers in data/raw/customers.json (8 customers, one JSON object per line). The data is messy on purpose: repeated orders, an order without a customer, mixed-case status values, and country codes with extra spaces. The CLAUDE.md file sets three rules: PySpark 4.3 in local mode, pure transform functions in pipeline/transforms.py, and raw files read with an explicit schema and mode FAILFAST, never inferSchema.
# shop-pipeline
Batch pipeline for the online shop: raw files in `data/raw/` -> cleaned -> daily revenue -> Parquet in `output/`.
- PySpark 4.3, local mode (Java 21). No cluster needed.
- Keep transformations in `pipeline/transforms.py` as pure functions (DataFrame in, DataFrame out).
- Read raw files with an explicit schema and mode FAILFAST, never inferSchema.order_id,customer_id,order_ts,status,qty,unit_price
1001,101,2026-10-01 09:15:00,shipped,2,25.00
1002,102,2026-10-01 10:02:00,shipped,1,120.00
1003,103,2026-10-01 11:40:00,Shipped,3,15.50
1004,104,2026-10-01 13:05:00,shipped,1,89.99
1004,104,2026-10-01 13:05:00,shipped,1,89.99
1005,105,2026-10-01 16:20:00,CANCELLED,2,40.00
1006,106,2026-10-01 18:45:00,shipped,4,12.00
1007,101,2026-10-02 08:30:00,shipped,1,250.00
1008,107,2026-10-02 09:55:00, shipped ,2,35.00
1009,102,2026-10-02 12:10:00,placed,5,9.99
1010,108,2026-10-02 14:00:00,shipped,1,60.00
1010,108,2026-10-02 14:00:00,shipped,1,60.00
1011,103,2026-10-02 15:35:00,shipped,2,45.00
1012,,2026-10-02 17:00:00,shipped,1,30.00
1013,105,2026-10-02 19:25:00,shipped,0,55.00
1014,106,2026-10-03 09:05:00,shipped,3,22.00
1015,104,2026-10-03 10:45:00,cancelled,1,99.00
1016,107,2026-10-03 12:30:00,shipped,2,18.50
1017,108,2026-10-03 13:50:00,placed,1,140.00
1018,101,2026-10-03 15:15:00,shipped,6,7.25
1019,102,2026-10-03 17:40:00,Shipped,1,75.00
1020,103,2026-10-03 20:05:00,shipped,2,33.00{"customer_id": 101, "name": "Ava Patel", "country": "US"}
{"customer_id": 102, "name": "Liam Chen", "country": "us"}
{"customer_id": 103, "name": "Mia Fischer", "country": "DE"}
{"customer_id": 104, "name": "Noah Smith", "country": "GB"}
{"customer_id": 105, "name": "Emma Wagner", "country": "de "}
{"customer_id": 106, "name": "Oliver Brown", "country": "gb"}
{"customer_id": 107, "name": "Sofia Garcia", "country": " US"}
{"customer_id": 108, "name": "Lucas Meyer", "country": "De"}Step 1: Read the raw data and plan
Let's start with the raw data and a plan. We open the project folder and start Claude Code. It is a new folder, so Claude Code asks if we trust it, and we choose yes. Then we press Shift+Tab three times to get to plan mode. In plan mode Claude can read and explore, but it does not change any files. Now we ask for the pipeline.
Build a PySpark pipeline: clean data/raw orders and customers, daily revenue by country, write Parquet, add testsClaude reads data/raw/orders.csv and data/raw/customers.json first, and tells us what is wrong with them.
The raw data needs cleaning: order ids 1004 and 1010 appear twice, order 1012 has no customer, 1013 has qty 0, status comes as Shipped / CANCELLED / shipped , and country codes as us, US, de .
That is exactly the mess we put in: two duplicate orders, one order without a customer, one with a quantity of zero, and status and country values in mixed case. Then Claude shows its plan:
pipeline/transforms.pywith three pure functions:clean_orders,clean_customersanddaily_revenuerun_pipeline.py: read the raw files with an explicit schema, transform, and write Parquet partitioned byorder_datetests/: pytest unit tests with a local SparkSession- run it with
spark-submit, thenpython -m pytest -q
We choose Yes, manually approve edits, so Claude asks before it writes each file.
Always let Claude look at the real data before it writes code. The plan is much better when it has seen the mess.
Step 2: Write the code
Now Claude writes the code. It starts with the transformations in pipeline/transforms.py. Claude asks before it creates the file and shows us the code. We choose the second option, to allow all edits for the rest of this session. Now we are in accept edits mode, so the next file, the job script run_pipeline.py, is written without asking. Here are the files, including an empty pipeline/__init__.py so pipeline can be imported as a package.
"""Pure transformations for the orders pipeline: DataFrame in, DataFrame out."""
from pyspark.sql import DataFrame, functions as F
def clean_orders(orders: DataFrame) -> DataFrame:
"""Drop duplicates, orders without a customer and qty <= 0; normalise status; add amount."""
return (
orders.dropDuplicates(["order_id"])
.filter(F.col("customer_id").isNotNull())
.filter(F.col("qty") > 0)
.withColumn("status", F.lower(F.trim("status")))
.withColumn("order_date", F.to_date("order_ts"))
.withColumn("amount", F.round(F.col("qty") * F.col("unit_price"), 2))
)
def clean_customers(customers: DataFrame) -> DataFrame:
"""Country codes arrive as 'us', ' US', 'de ' -> 'US', 'DE'."""
return customers.withColumn("country", F.upper(F.trim("country")))
def daily_revenue(orders: DataFrame, customers: DataFrame) -> DataFrame:
"""Orders and revenue per day and country, cancelled orders excluded."""
return (
orders.filter(F.col("status") != "cancelled")
.join(customers.select("customer_id", "country"), "customer_id", "left")
.groupBy("order_date", "country")
.agg(F.count("order_id").alias("orders"), F.round(F.sum("amount"), 2).alias("revenue"))
.orderBy("order_date", "country")
)"""Orders pipeline: raw CSV + JSON -> clean -> daily revenue by country -> Parquet."""
from pyspark.sql import SparkSession, functions as F
from pipeline.transforms import clean_customers, clean_orders, daily_revenue
ORDERS_SCHEMA = "order_id INT, customer_id INT, order_ts TIMESTAMP, status STRING, qty INT, unit_price DECIMAL(10,2)"
CUSTOMERS_SCHEMA = "customer_id INT, name STRING, country STRING"
spark = SparkSession.builder.master("local[2]").appName("orders-pipeline").getOrCreate()
raw_orders = spark.read.csv("data/raw/orders.csv", header=True, schema=ORDERS_SCHEMA, mode="FAILFAST")
raw_customers = spark.read.json("data/raw/customers.json", schema=CUSTOMERS_SCHEMA, mode="FAILFAST")
orders = clean_orders(raw_orders)
customers = clean_customers(raw_customers)
daily = daily_revenue(orders, customers)
print(f"raw orders: {raw_orders.count()}")
print(f"clean orders: {orders.count()}")
print(f"total revenue: {daily.agg(F.sum('revenue')).first()[0]}")
daily.show()
daily.write.mode("overwrite").partitionBy("order_date").parquet("output/daily_revenue")
print("wrote output/daily_revenue")
spark.stop()The job script reads the raw files with an explicit schema, in FAILFAST mode. A row that does not fit the schema stops the job, instead of quietly turning into nulls, which is what the default PERMISSIVE mode does. Then it runs the three transforms, prints the raw count, the clean count and the total revenue, shows the daily table, and writes Parquet partitioned by order_date. master("local[2]") runs Spark on the laptop with two threads, so no cluster is needed.
The write uses mode("overwrite"). When we run the job again, it replaces the output instead of adding a second copy, so the job is safe to rerun.
Put rules like explicit schemas in your CLAUDE.md file. Claude reads that file at the start of every session.
Inside the transforms
Let's look inside pipeline/transforms.py. clean_orders drops duplicate order IDs, orders without a customer, and quantities of zero or less. Then it trims and lowercases the status, turns the order_ts timestamp into an order_date, and adds amount as qty * unit_price, rounded to 2 decimals. clean_customers fixes the country codes with trim and upper, so us, US and de become US and DE. And daily_revenue removes cancelled orders, joins the customers, and groups by day and country.
Each function takes a DataFrame and returns a DataFrame. Nothing here reads or writes files, so every rule is easy to test with a small hand-made DataFrame. That is what we do in step 4.
dropDuplicates(["order_id"]) keeps any one of the rows that share an order ID. That is fine here because the duplicates are exact copies. If your duplicates can differ, decide which row wins, for example the latest one.
Step 3: Run it with Spark
Time to run it with Spark, on the laptop.
Run the pipelineClaude wants to run spark-submit. In accept edits mode file edits are automatic, but commands still ask. We choose Yes, and don't ask again for spark-submit. After the run Claude also lists the output folder. ls is a read-only command, so it runs without a prompt.
spark-submit run_pipeline.pyraw orders: 22
clean orders: 18
total revenue: 1301.94
+----------+-------+------+-------+
|order_date|country|orders|revenue|
+----------+-------+------+-------+
|2026-10-01| DE| 1| 46.50|
|2026-10-01| GB| 2| 137.99|
|2026-10-01| US| 2| 170.00|
|2026-10-02| DE| 2| 150.00|
|2026-10-02| US| 3| 369.95|
|2026-10-03| DE| 2| 206.00|
|2026-10-03| GB| 1| 66.00|
|2026-10-03| US| 3| 155.50|
+----------+-------+------+-------+
wrote output/daily_revenuels output/daily_revenue_SUCCESS
order_date=2026-10-01
order_date=2026-10-02
order_date=2026-10-03Here is the real output. 22 raw orders, and 18 after cleaning: the two duplicates (1004 and 1010), order 1012 without a customer and order 1013 with a quantity of zero are gone. The total revenue is 1301.94, and we will check that number with a second tool later. The daily table has 8 rows, one per day and country. The two cancelled orders (1005 and 1015) are left out, and every country code is clean: only DE, GB and US.
ls shows one folder per day, order_date=2026-10-01 to order_date=2026-10-03, plus the _SUCCESS marker. That is what partitionBy gives you: a query for one day reads only that folder. Partition by a column your queries filter on, with a modest number of values. Partitioning by customer, for example, would create thousands of tiny files.
Run Spark locally on a small sample first. It is quick, and you catch most bugs before you ever touch a real cluster.
Step 4: Unit tests with pytest
A pipeline without tests is a guess. So let's add tests.
Add unit tests for the three transformsClaude writes tests/conftest.py with one local Spark session shared by all the tests (a pytest fixture with scope="session"), then tests/test_transforms.py with four tests. We are still in accept edits mode, so both files are written without asking. Then Claude wants to run pytest, and we choose Yes, and don't ask again for pytest.
import pytest
from pyspark.sql import SparkSession
@pytest.fixture(scope="session")
def spark():
"""One local Spark session for the whole test run."""
session = SparkSession.builder.master("local[1]").appName("tests").getOrCreate()
yield session
session.stop()from datetime import datetime
from decimal import Decimal
from pipeline.transforms import clean_customers, clean_orders, daily_revenue
COLS = "order_id INT, customer_id INT, order_ts TIMESTAMP, status STRING, qty INT, unit_price DECIMAL(10,2)"
TS = datetime(2026, 10, 1, 9, 0)
def test_clean_orders_drops_duplicates_missing_customer_and_zero_qty(spark):
raw = spark.createDataFrame([
(1, 10, TS, "shipped", 1, Decimal("5.00")),
(1, 10, TS, "shipped", 1, Decimal("5.00")), # duplicate
(2, None, TS, "shipped", 1, Decimal("5.00")), # no customer
(3, 11, TS, "shipped", 0, Decimal("5.00")), # qty 0
], COLS)
assert [r.order_id for r in clean_orders(raw).collect()] == [1]
def test_clean_orders_normalises_status_and_computes_amount(spark):
raw = spark.createDataFrame([(1, 10, TS, " Shipped ", 3, Decimal("2.50"))], COLS)
row = clean_orders(raw).first()
assert row.status == "shipped"
assert row.amount == Decimal("7.50")
assert str(row.order_date) == "2026-10-01"
def test_clean_customers_uppercases_country(spark):
raw = spark.createDataFrame([(1, "A", " us"), (2, "B", "de ")], "customer_id INT, name STRING, country STRING")
assert [r.country for r in clean_customers(raw).orderBy("customer_id").collect()] == ["US", "DE"]
def test_daily_revenue_excludes_cancelled_orders(spark):
raw = spark.createDataFrame([
(1, 10, TS, "shipped", 2, Decimal("10.00")),
(2, 10, TS, "CANCELLED", 1, Decimal("99.00")),
], COLS)
customers = spark.createDataFrame([(10, "A", "US")], "customer_id INT, name STRING, country STRING")
rows = daily_revenue(clean_orders(raw), customers).collect()
assert [(r.country, r.orders, r.revenue) for r in rows] == [("US", 1, Decimal("20.00"))]python -m pytest -q.... [100%]
4 passed in 24.13sThe four tests check one rule each: duplicates and bad rows are dropped, the status and the amount are right, country codes are upper case, and cancelled orders are not counted. Each test builds a tiny DataFrame by hand with createDataFrame, so the input is obvious when you read the test. The cancelled-orders test runs clean_orders first, so it also covers a status that arrives as CANCELLED in upper case. 4 passed is a real run: Spark started, ran every test, and stopped again.
Test small hand-made DataFrames, with one bad case in each test. When a test fails, you know exactly which rule broke.
Step 5: Check the Parquet, save the commands
Two more things before we finish. First, we check the Parquet output with a second tool.
Check the Parquet output with DuckDBClaude runs a DuckDB query that reads every Parquet file under output/daily_revenue with hive_partitioning = true, so the order_date folder names become a column again. This time we choose plain Yes, just for this one command.
duckdb -c "SELECT count(*) AS rows, sum(orders) AS orders, sum(revenue) AS revenue FROM read_parquet('output/daily_revenue/*/*.parquet', hive_partitioning = true)"┌───────┬────────┬───────────────┐
│ rows │ orders │ revenue │
│ int64 │ int128 │ decimal(38,2) │
├───────┼────────┼───────────────┤
│ 8 │ 16 │ 1301.94 │
└───────┴────────┴───────────────┘DuckDB finds 8 rows, 16 orders, and a revenue of 1301.94, the same total that Spark printed. Two engines, the same answer. The 16 orders are the 18 clean orders minus the two cancelled ones. If the numbers did not match, that is the first thing to fix, before anyone builds a report on this output.
Second, we ask Claude to save the commands in CLAUDE.md.
Add the run, test and check commands to CLAUDE.mdWe are in accept edits mode, so Claude edits the file without asking. It adds a ## Commands section with the run, test and check commands.
# shop-pipeline
Batch pipeline for the online shop: raw files in `data/raw/` -> cleaned -> daily revenue -> Parquet in `output/`.
- PySpark 4.3, local mode (Java 21). No cluster needed.
- Keep transformations in `pipeline/transforms.py` as pure functions (DataFrame in, DataFrame out).
- Read raw files with an explicit schema and mode FAILFAST, never inferSchema.
## Commands
- Run the pipeline: `spark-submit run_pipeline.py` (writes `output/daily_revenue/`, partitioned by `order_date`)
- Run the tests: `python -m pytest -q`
- Check the output: `duckdb -c "SELECT ... FROM read_parquet('output/daily_revenue/*/*.parquet', hive_partitioning = true)"`Now every new session knows how to run, test and check this project.
When you choose "Yes, and don't ask again", Claude Code saves an allow rule in .claude/settings.local.json, so the next spark-submit or pytest run does not ask.
The checklist: Spark with Claude
Here is the checklist I use for Spark work with Claude Code.
PySpark with Claude Code
- Read the real data, plan in plan mode
- Pure transforms: DataFrame in, DataFrame out
- Run locally, check the output with a second tool
- Commands and rules in
CLAUDE.md
Let Claude read the real raw files and plan in plan mode, before any code. Keep transforms pure, so they are easy to test with small DataFrames. Run locally with spark-submit, and check the output with a second tool. And write the commands and rules in CLAUDE.md, so every session starts with them.
Key points to remember
- Plan mode after reading the raw data
- Pure transforms in pipeline/transforms.py
- spark-submit in local mode
- Unit tests with pytest
- Cross-check with DuckDB, commands in CLAUDE.md
The full script
This bash script writes every file Claude wrote, in the same order, and runs every command, so you can reproduce all the results without Claude.
Show the full script (every file and every command, in order)
#!/usr/bin/env bash
# Claude for Data Engineers #4: Build a PySpark Pipeline with Claude Code
# Rebuilds the demo project without Claude: writes every file Claude wrote, in the same order,
# and runs every command from the video. Run it in an empty folder.
# Tools used in the video: Python 3.13, DuckDB 2.0.0, pandas 3.0.5, PySpark 4.3.0 (local mode, Java 21),
# dbt-core 1.12.6 with dbt-duckdb 1.11.0, PostgreSQL 16. Install the ones this project uses first.
mkdir -p shop-pipeline && cd shop-pipeline
# ---------- starting files ----------
cat > CLAUDE.md <<'CLAUDE_DE_EOF'
# shop-pipeline
Batch pipeline for the online shop: raw files in `data/raw/` -> cleaned -> daily revenue -> Parquet in `output/`.
- PySpark 4.3, local mode (Java 21). No cluster needed.
- Keep transformations in `pipeline/transforms.py` as pure functions (DataFrame in, DataFrame out).
- Read raw files with an explicit schema and mode FAILFAST, never inferSchema.
CLAUDE_DE_EOF
mkdir -p data/raw
cat > data/raw/orders.csv <<'CLAUDE_DE_EOF'
order_id,customer_id,order_ts,status,qty,unit_price
1001,101,2026-10-01 09:15:00,shipped,2,25.00
1002,102,2026-10-01 10:02:00,shipped,1,120.00
1003,103,2026-10-01 11:40:00,Shipped,3,15.50
1004,104,2026-10-01 13:05:00,shipped,1,89.99
1004,104,2026-10-01 13:05:00,shipped,1,89.99
1005,105,2026-10-01 16:20:00,CANCELLED,2,40.00
1006,106,2026-10-01 18:45:00,shipped,4,12.00
1007,101,2026-10-02 08:30:00,shipped,1,250.00
1008,107,2026-10-02 09:55:00, shipped ,2,35.00
1009,102,2026-10-02 12:10:00,placed,5,9.99
1010,108,2026-10-02 14:00:00,shipped,1,60.00
1010,108,2026-10-02 14:00:00,shipped,1,60.00
1011,103,2026-10-02 15:35:00,shipped,2,45.00
1012,,2026-10-02 17:00:00,shipped,1,30.00
1013,105,2026-10-02 19:25:00,shipped,0,55.00
1014,106,2026-10-03 09:05:00,shipped,3,22.00
1015,104,2026-10-03 10:45:00,cancelled,1,99.00
1016,107,2026-10-03 12:30:00,shipped,2,18.50
1017,108,2026-10-03 13:50:00,placed,1,140.00
1018,101,2026-10-03 15:15:00,shipped,6,7.25
1019,102,2026-10-03 17:40:00,Shipped,1,75.00
1020,103,2026-10-03 20:05:00,shipped,2,33.00
CLAUDE_DE_EOF
mkdir -p data/raw
cat > data/raw/customers.json <<'CLAUDE_DE_EOF'
{"customer_id": 101, "name": "Ava Patel", "country": "US"}
{"customer_id": 102, "name": "Liam Chen", "country": "us"}
{"customer_id": 103, "name": "Mia Fischer", "country": "DE"}
{"customer_id": 104, "name": "Noah Smith", "country": "GB"}
{"customer_id": 105, "name": "Emma Wagner", "country": "de "}
{"customer_id": 106, "name": "Oliver Brown", "country": "gb"}
{"customer_id": 107, "name": "Sofia Garcia", "country": " US"}
{"customer_id": 108, "name": "Lucas Meyer", "country": "De"}
CLAUDE_DE_EOF
# ---------- step 1: The transforms and the job script ----------
mkdir -p pipeline
cat > pipeline/__init__.py <<'CLAUDE_DE_EOF'
CLAUDE_DE_EOF
mkdir -p pipeline
cat > pipeline/transforms.py <<'CLAUDE_DE_EOF'
"""Pure transformations for the orders pipeline: DataFrame in, DataFrame out."""
from pyspark.sql import DataFrame, functions as F
def clean_orders(orders: DataFrame) -> DataFrame:
"""Drop duplicates, orders without a customer and qty <= 0; normalise status; add amount."""
return (
orders.dropDuplicates(["order_id"])
.filter(F.col("customer_id").isNotNull())
.filter(F.col("qty") > 0)
.withColumn("status", F.lower(F.trim("status")))
.withColumn("order_date", F.to_date("order_ts"))
.withColumn("amount", F.round(F.col("qty") * F.col("unit_price"), 2))
)
def clean_customers(customers: DataFrame) -> DataFrame:
"""Country codes arrive as 'us', ' US', 'de ' -> 'US', 'DE'."""
return customers.withColumn("country", F.upper(F.trim("country")))
def daily_revenue(orders: DataFrame, customers: DataFrame) -> DataFrame:
"""Orders and revenue per day and country, cancelled orders excluded."""
return (
orders.filter(F.col("status") != "cancelled")
.join(customers.select("customer_id", "country"), "customer_id", "left")
.groupBy("order_date", "country")
.agg(F.count("order_id").alias("orders"), F.round(F.sum("amount"), 2).alias("revenue"))
.orderBy("order_date", "country")
)
CLAUDE_DE_EOF
cat > run_pipeline.py <<'CLAUDE_DE_EOF'
"""Orders pipeline: raw CSV + JSON -> clean -> daily revenue by country -> Parquet."""
from pyspark.sql import SparkSession, functions as F
from pipeline.transforms import clean_customers, clean_orders, daily_revenue
ORDERS_SCHEMA = "order_id INT, customer_id INT, order_ts TIMESTAMP, status STRING, qty INT, unit_price DECIMAL(10,2)"
CUSTOMERS_SCHEMA = "customer_id INT, name STRING, country STRING"
spark = SparkSession.builder.master("local[2]").appName("orders-pipeline").getOrCreate()
raw_orders = spark.read.csv("data/raw/orders.csv", header=True, schema=ORDERS_SCHEMA, mode="FAILFAST")
raw_customers = spark.read.json("data/raw/customers.json", schema=CUSTOMERS_SCHEMA, mode="FAILFAST")
orders = clean_orders(raw_orders)
customers = clean_customers(raw_customers)
daily = daily_revenue(orders, customers)
print(f"raw orders: {raw_orders.count()}")
print(f"clean orders: {orders.count()}")
print(f"total revenue: {daily.agg(F.sum('revenue')).first()[0]}")
daily.show()
daily.write.mode("overwrite").partitionBy("order_date").parquet("output/daily_revenue")
print("wrote output/daily_revenue")
spark.stop()
CLAUDE_DE_EOF
# ---------- step 2: Run the pipeline with spark-submit ----------
spark-submit run_pipeline.py
ls output/daily_revenue
# ---------- step 3: Unit tests with a local SparkSession ----------
mkdir -p tests
cat > tests/conftest.py <<'CLAUDE_DE_EOF'
import pytest
from pyspark.sql import SparkSession
@pytest.fixture(scope="session")
def spark():
"""One local Spark session for the whole test run."""
session = SparkSession.builder.master("local[1]").appName("tests").getOrCreate()
yield session
session.stop()
CLAUDE_DE_EOF
mkdir -p tests
cat > tests/test_transforms.py <<'CLAUDE_DE_EOF'
from datetime import datetime
from decimal import Decimal
from pipeline.transforms import clean_customers, clean_orders, daily_revenue
COLS = "order_id INT, customer_id INT, order_ts TIMESTAMP, status STRING, qty INT, unit_price DECIMAL(10,2)"
TS = datetime(2026, 10, 1, 9, 0)
def test_clean_orders_drops_duplicates_missing_customer_and_zero_qty(spark):
raw = spark.createDataFrame([
(1, 10, TS, "shipped", 1, Decimal("5.00")),
(1, 10, TS, "shipped", 1, Decimal("5.00")), # duplicate
(2, None, TS, "shipped", 1, Decimal("5.00")), # no customer
(3, 11, TS, "shipped", 0, Decimal("5.00")), # qty 0
], COLS)
assert [r.order_id for r in clean_orders(raw).collect()] == [1]
def test_clean_orders_normalises_status_and_computes_amount(spark):
raw = spark.createDataFrame([(1, 10, TS, " Shipped ", 3, Decimal("2.50"))], COLS)
row = clean_orders(raw).first()
assert row.status == "shipped"
assert row.amount == Decimal("7.50")
assert str(row.order_date) == "2026-10-01"
def test_clean_customers_uppercases_country(spark):
raw = spark.createDataFrame([(1, "A", " us"), (2, "B", "de ")], "customer_id INT, name STRING, country STRING")
assert [r.country for r in clean_customers(raw).orderBy("customer_id").collect()] == ["US", "DE"]
def test_daily_revenue_excludes_cancelled_orders(spark):
raw = spark.createDataFrame([
(1, 10, TS, "shipped", 2, Decimal("10.00")),
(2, 10, TS, "CANCELLED", 1, Decimal("99.00")),
], COLS)
customers = spark.createDataFrame([(10, "A", "US")], "customer_id INT, name STRING, country STRING")
rows = daily_revenue(clean_orders(raw), customers).collect()
assert [(r.country, r.orders, r.revenue) for r in rows] == [("US", 1, Decimal("20.00"))]
CLAUDE_DE_EOF
python -m pytest -q
# ---------- step 4: Cross-check the Parquet output with DuckDB ----------
duckdb -c "SELECT count(*) AS rows, sum(orders) AS orders, sum(revenue) AS revenue FROM read_parquet('output/daily_revenue/*/*.parquet', hive_partitioning = true)"
# ---------- step 5: Save the commands in CLAUDE.md ----------
cat > CLAUDE.md <<'CLAUDE_DE_EOF'
# shop-pipeline
Batch pipeline for the online shop: raw files in `data/raw/` -> cleaned -> daily revenue -> Parquet in `output/`.
- PySpark 4.3, local mode (Java 21). No cluster needed.
- Keep transformations in `pipeline/transforms.py` as pure functions (DataFrame in, DataFrame out).
- Read raw files with an explicit schema and mode FAILFAST, never inferSchema.
## Commands
- Run the pipeline: `spark-submit run_pipeline.py` (writes `output/daily_revenue/`, partitioned by `order_date`)
- Run the tests: `python -m pytest -q`
- Check the output: `duckdb -c "SELECT ... FROM read_parquet('output/daily_revenue/*/*.parquet', hive_partitioning = true)"`
CLAUDE_DE_EOF
Part 5: Build a dbt Project with Claude Code
The project and its data are invented for teaching. Every file on this page is the real file from the demo project, and every output is the real output of the command above it, captured when the video was made (each step ran twice in a fresh folder and the outputs were compared). The Claude screens in the video are a simplified recreation for teaching. Always review what Claude changes and runs. Claude plans, features and limits are current as of November 2026; check the official Claude and Claude Code documentation before you rely on them. Part of the Claude for Data Engineers series on TechBrothersIT.



No comments:
Post a Comment
Note: Only a member of this blog may post a comment.