from pyspark.sql import SparkSession
from pyspark.sql.functions import col, sum, avg, desc, row_number
from pyspark.sql.window import Window
from pyspark.sql.types import StructType, StructField, StringType, IntegerType, DoubleType
# Initialize SparkSession
spark = SparkSession.builder \
.appName("PySparkRetailAnalytics") \
.master("local[*]") \
.getOrCreate()
# Explicit Schema Definition for speed and reliability
schema = StructType([
StructField("order_id", StringType(), False),
StructField("customer_id", StringType(), False),
StructField("category", StringType(), True),
StructField("quantity", IntegerType(), True),
StructField("unit_price", DoubleType(), True),
StructField("state", StringType(), True)
])
# Read raw data into DataFrame
df = spark.read.csv("data/retail_transactions.csv", header=True, schema=schema)
# 1. Transformation: Calculate Total Sales & Filter High Quantity
transformed_df = df \
.withColumn("total_sales", col("quantity") * col("unit_price")) \
.filter(col("quantity") > 0)
# 2. Window Transformation: Rank Top Customers by State
window_spec = Window.partitionBy("state").orderBy(desc("total_sales"))
ranked_df = transformed_df.withColumn("rank_in_state", row_number().over(window_spec))
# 3. Action: Display Top 5 Rows in Console
print("Top Transactions by State:")
ranked_df.filter(col("rank_in_state") <= 3).show(5, truncate=False)
# 4. Action: Save as Partitioned Snappy Parquet (Production Format)
ranked_df.write \
.partitionBy("state") \
.mode("overwrite") \
.parquet("output/processed_retail_parquet")
print("PySpark Job Completed Successfully!")