from pyspark.sql import SparkSession
from pyspark.sql.functions import from_json, col, when, current_timestamp
from pyspark.sql.types import StructType, StructField, StringType, DoubleType
# Initialize Spark with Kafka connector
spark = SparkSession.builder \
.appName("KafkaPySparkPostgresPipeline") \
.config("spark.jars.packages", "org.apache.spark:spark-sql-kafka-0-10_2.12:3.5.0,org.postgresql:postgresql:42.6.0") \
.getOrCreate()
# Define transaction schema
schema = StructType([
StructField("txn_id", StringType(), False),
StructField("account_id", StringType(), False),
StructField("amount", DoubleType(), False),
StructField("country", StringType(), True)
])
# 1. Read Kafka Stream
df_kafka = spark.readStream \
.format("kafka") \
.option("kafka.bootstrap.servers", "localhost:9092") \
.option("subscribe", "financial_events") \
.load()
# 2. Parse & Apply Fraud Logic
processed_df = df_kafka \
.select(from_json(col("value").cast("string"), schema).alias("data")) \
.select("data.*") \
.withColumn("is_suspicious", when(col("amount") > 50000, True).otherwise(False)) \
.withColumn("processed_at", current_timestamp())
# 3. Write Micro-Batches to PostgreSQL
def write_to_postgres(batch_df, batch_id):
batch_df.write \
.format("jdbc") \
.option("url", "jdbc:postgresql://localhost:5432/finance_db") \
.option("dbtable", "live_transactions") \
.option("user", "postgres_admin") \
.option("password", "strong_password") \
.option("driver", "org.postgresql.Driver") \
.mode("append") \
.save()
print(f"Batch {batch_id} committed to PostgreSQL successfully.")
query = processed_df.writeStream \
.foreachBatch(write_to_postgres) \
.option("checkpointLocation", "/tmp/spark_checkpoints/postgres_sink") \
.start()
query.awaitTermination()