Introduction
An order-level view tells you how much each paid order contributed. A manager asks a different question: how many paid orders did we receive on each date, and what revenue did they represent? Aggregation combines several rows into fewer summary rows while preserving the chosen business meaning.
You will begin with individual paid amounts, reconcile an overall total, and then split it into daily groups. The simplified rule includes only paid orders and excludes pending and refunded orders; refunds are not subtracted as negative sales here. Each record represents one order with one product type, in one currency without tax or discounts.
The lab independently provides six valid orders and a second delivery containing one added paid order. You should know typed CSV reading, row expressions, filtering, and the minimal Parquet write/read workflow. No Hive or SQL prerequisite is needed. Use the Terminal and the prepared PySpark environment.
Establish the Rows and Amounts Being Summarized
In this step, you will check the input to the aggregation. Inspect the independent source:
cd /home/labex/project
cat /home/labex/project/data/orders.csv
The explicit reader and paid amount calculation below repeat earlier skills. Each paid order contributes quantity * unit_price as a decimal amount. Do not introduce a quantity-at-least-two filter: the one-unit paid order o2 also contributes revenue.
Save and run the complete script. The imported Spark sum function is named spark_sum to distinguish it from Python's ordinary sum; later steps will use it for DataFrame aggregation:
cat > /home/labex/project/daily_sales.py <<'PYTHON'
from pyspark.sql import SparkSession
from pyspark.sql.functions import col, count, sum as spark_sum
from pyspark.sql.types import StructType, StructField, StringType, IntegerType, DecimalType, DateType
spark = SparkSession.builder.appName("DailyPaidSales").master("local[2]").getOrCreate()
spark.sparkContext.setLogLevel("ERROR")
order_schema = StructType([
StructField("order_id", StringType(), True),
StructField("customer_id", StringType(), True),
StructField("product_id", StringType(), True),
StructField("quantity", IntegerType(), True),
StructField("unit_price", DecimalType(10, 2), True),
StructField("order_status", StringType(), True),
StructField("order_date", DateType(), True),
])
input_path = "/home/labex/project/data/orders.csv"
df = spark.read.option("header", True).schema(order_schema).csv(input_path)
paid = df.filter(col("order_status") == "paid").withColumn("order_amount", col("quantity") * col("unit_price"))
paid.select("order_id", "order_date", "order_amount").orderBy("order_id").show(truncate=False)
spark.stop()
PYTHON
bigdata-python /home/labex/project/daily_sales.py > /home/labex/project/output/paid-input.txt
cat /home/labex/project/output/paid-input.txt
Expect o1/2026-10-14/20.00, o2/2026-10-14/25.00, o4/2026-10-15/50.00, and o6/2026-10-15/30.00. There are four paid order rows, although their quantities sum to seven units. Order count, unit count, and revenue are different measures.
Before combining anything, calculate the total by hand: 20 + 25 + 50 + 30 = 125. This small oracle helps you judge the next result rather than trusting a successful execution alone.
Combine Paid Rows into an Overall Total
In this step, you will produce a one-row summary. DataFrame agg applies aggregate functions to a collection of rows. The Spark count("*") expression counts all qualifying rows; spark_sum("order_amount") adds their known amounts. alias gives each measure a readable result name.
These are Spark expressions, not a Python loop over collected records. With no grouping key, all paid rows form one group. Run the updated version, which also saves the result using the minimal overwrite-Parquet pattern already learned:
cat > /home/labex/project/daily_sales.py <<'PYTHON'
from pyspark.sql import SparkSession
from pyspark.sql.functions import col, count, sum as spark_sum
from pyspark.sql.types import StructType, StructField, StringType, IntegerType, DecimalType, DateType
spark = SparkSession.builder.appName("DailyPaidSales").master("local[2]").getOrCreate()
spark.sparkContext.setLogLevel("ERROR")
order_schema = StructType([
StructField("order_id", StringType(), True),
StructField("customer_id", StringType(), True),
StructField("product_id", StringType(), True),
StructField("quantity", IntegerType(), True),
StructField("unit_price", DecimalType(10, 2), True),
StructField("order_status", StringType(), True),
StructField("order_date", DateType(), True),
])
input_path = "/home/labex/project/data/orders.csv"
df = spark.read.option("header", True).schema(order_schema).csv(input_path)
paid = df.filter(col("order_status") == "paid").withColumn("order_amount", col("quantity") * col("unit_price"))
overall = paid.agg(count("*").alias("paid_order_count"), spark_sum("order_amount").alias("revenue"))
overall.show(truncate=False)
overall.write.mode("overwrite").parquet("/home/labex/project/output/paid-total")
spark.stop()
PYTHON
bigdata-python /home/labex/project/daily_sales.py > /home/labex/project/output/overall-sales.txt
cat /home/labex/project/output/overall-sales.txt
Expect paid_order_count = 4 and revenue = 125.00. The original input remains six rows; the overall DataFrame has one summary row. SUM ignores NULL values, so a real reporting pipeline should resolve or explicitly exclude missing amounts before this step. This prepared fixture has known valid prices and quantities.
The one-row Parquet output is a derived result, not a replacement for the original orders. Next, you will ask for one summary row per date.
Group the Same Orders by Date
In this step, you will split the same paid rows into daily groups. groupBy("order_date") puts records with equal dates into the same logical group. agg then calculates a separate count and revenue for each group. The result has the grouping key plus the named aggregate columns, rather than one row for each original order.
Run this version:
cat > /home/labex/project/daily_sales.py <<'PYTHON'
from pyspark.sql import SparkSession
from pyspark.sql.functions import col, count, sum as spark_sum
from pyspark.sql.types import StructType, StructField, StringType, IntegerType, DecimalType, DateType
spark = SparkSession.builder.appName("DailyPaidSales").master("local[2]").getOrCreate()
spark.sparkContext.setLogLevel("ERROR")
order_schema = StructType([
StructField("order_id", StringType(), True),
StructField("customer_id", StringType(), True),
StructField("product_id", StringType(), True),
StructField("quantity", IntegerType(), True),
StructField("unit_price", DecimalType(10, 2), True),
StructField("order_status", StringType(), True),
StructField("order_date", DateType(), True),
])
input_path = "/home/labex/project/data/orders.csv"
df = spark.read.option("header", True).schema(order_schema).csv(input_path)
paid = df.filter(col("order_status") == "paid").withColumn("order_amount", col("quantity") * col("unit_price"))
daily = paid.groupBy("order_date").agg(
count("*").alias("paid_order_count"),
spark_sum("order_amount").alias("revenue"),
)
daily.orderBy("order_date").show(truncate=False)
daily.printSchema()
daily.write.mode("overwrite").parquet("/home/labex/project/output/daily-sales")
spark.stop()
PYTHON
bigdata-python /home/labex/project/daily_sales.py > /home/labex/project/output/daily-sales.txt
cat /home/labex/project/output/daily-sales.txt
Expect October 14 / 2 / 45.00 and October 15 / 2 / 80.00. Their amounts add back to 125.00 and their counts to four paid orders. This reconciliation checks that grouping changed the shape, not the reporting rule.
Grouping may require Spark to bring records with the same key together across its computation partitions, an operation called a shuffle. In this local environment those computations share one machine; larger deployments can move records across machines. You do not need to set a task count or tune resources to express this calculation.
The display uses orderBy for a predictable date order. Parquet does not promise a global physical row order, so a later reader should sort when presenting a report. The stored date stays DateType and the monetary total stays decimal; decimal precision can widen during summation.
Predict and Check a Changed Delivery
In this step, you will test whether the same aggregation responds correctly to a new paid order. Inspect the additional record:
tail -n 1 /home/labex/project/data/more-orders.csv
o7 is paid on October 15 with quantity 3 and unit price 10.00. Predict the changes: that date's paid order count increases by one, while revenue increases by 30.00. October 14 should remain unchanged. Three units do not mean three new orders.
The complete version below places the unchanged reader, filter, calculation, and grouping inside one reusable Python function. It runs that function for both deliveries and reads back their separately stored results:
cat > /home/labex/project/daily_sales.py <<'PYTHON'
from pyspark.sql import SparkSession
from pyspark.sql.functions import col, count, sum as spark_sum
from pyspark.sql.types import StructType, StructField, StringType, IntegerType, DecimalType, DateType
spark = SparkSession.builder.appName("DailyPaidSales").master("local[2]").getOrCreate()
spark.sparkContext.setLogLevel("ERROR")
order_schema = StructType([
StructField("order_id", StringType(), True),
StructField("customer_id", StringType(), True),
StructField("product_id", StringType(), True),
StructField("quantity", IntegerType(), True),
StructField("unit_price", DecimalType(10, 2), True),
StructField("order_status", StringType(), True),
StructField("order_date", DateType(), True),
])
def build_daily_sales(input_path):
df = spark.read.option("header", True).schema(order_schema).csv(input_path)
paid = df.filter(col("order_status") == "paid").withColumn("order_amount", col("quantity") * col("unit_price"))
daily = paid.groupBy("order_date").agg(
count("*").alias("paid_order_count"),
spark_sum("order_amount").alias("revenue"),
)
return daily
main = build_daily_sales("/home/labex/project/data/orders.csv")
main.write.mode("overwrite").parquet("/home/labex/project/output/daily-sales")
practice = build_daily_sales("/home/labex/project/data/more-orders.csv")
practice.write.mode("overwrite").parquet("/home/labex/project/output/practice-daily-sales")
print("Original daily report:")
spark.read.parquet("/home/labex/project/output/daily-sales").orderBy("order_date").show(truncate=False)
print("Changed-delivery daily report:")
spark.read.parquet("/home/labex/project/output/practice-daily-sales").orderBy("order_date").show(truncate=False)
spark.stop()
PYTHON
bigdata-python /home/labex/project/daily_sales.py > /home/labex/project/output/changed-daily-sales.txt
cat /home/labex/project/output/changed-daily-sales.txt
The original report should remain October 14 / 2 / 45.00 and October 15 / 2 / 80.00. The changed delivery should return October 14 / 2 / 45.00 and October 15 / 3 / 110.00. Its total is five paid orders and 155.00 revenue.
Both outputs came from the same expression chain with different input files. The comparison checks that the report is derived from its data rather than from remembered training totals. Raw files and the original report remain available for review.
Summary
You reconciled per-order amounts, an overall paid-sales total, and daily grouped measures using Spark aggregation. Adding one known paid order changed only the expected date's count and revenue, while both actual Parquet reports remained inspectable. Next, customer and product reference tables will add region and category context to these measures.



