-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspark-streaming.py
162 lines (123 loc) · 4.65 KB
/
spark-streaming.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
# Importing Libraries
from pyspark.sql import SparkSession
from pyspark.sql.functions import *
from pyspark.sql.types import *
from pyspark.sql.functions import from_json
from pyspark.sql.window import Window
# Starting Spark Session
spark = SparkSession \
.builder \
.appName("RDA") \
.getOrCreate()
spark.sparkContext.setLogLevel('ERROR')
# Reading Input from kafka Producer
RawData = spark \
.readStream \
.format("kafka") \
.option("kafka.bootstrap.servers","18.211.252.152:9092") \
.option("startingOffsets", "latest") \
.option("subscribe","real-time-project") \
.load()
# Defining the Schema
JsonSchema = StructType() \
.add("invoice_no", LongType()) \
.add("country", StringType()) \
.add("timestamp", TimestampType()) \
.add("type", StringType()) \
.add("items", ArrayType(StructType([
StructField("SKU", StringType()),
StructField("title", StringType()),
StructField("unit_price", DoubleType()),
StructField("quantity", IntegerType())
])))
# Creating dataframe from input data after applying the schema
OrderStream = RawData.select(from_json(col("value").cast("string"), JsonSchema).alias("data")).select("data.*")
# UDF for calculating total_items
def items_TotalCount(items):
total_count = 0
for item in items:
total_count = total_count + item['quantity']
return total_count
# UDF for calculating order type
def is_order(type):
if type=="ORDER":
return 1
else:
return 0
# UDF for calculating return type
def is_return(type):
if type=="RETURN":
return 1
else:
return 0
# UDF for calculating total_cost
def TotalCostSum(items,type):
total_sum = 0
for item in items:
total_sum = total_sum + item['unit_price'] * item['quantity']
if type=="RETURN":
return total_sum * (-1)
else:
return total_sum
# Converting to UDF’s with the utility functions
isorder = udf(is_order, IntegerType())
isreturn = udf(is_return, IntegerType())
totalcount = udf(items_TotalCount, IntegerType())
totalcost = udf(TotalCostSum, DoubleType())
# Calculating columns(total_cost, total_items, is_order, is_return)
order_stream = OrderStream \
.withColumn("total_cost", totalcost(OrderStream.items, OrderStream.type)) \
.withColumn("total_items", totalcount(OrderStream.items)) \
.withColumn("is_order", isorder(OrderStream.type)) \
.withColumn("is_return", isreturn(OrderStream.type))
# Writing the Inetermediary data into Console
orderStreamOutput = order_stream \
.select("invoice_no", "country", "timestamp","total_cost","total_items","is_order","is_return") \
.writeStream \
.outputMode("append") \
.format("console") \
.option("truncate", "false") \
.trigger(processingTime="1 minute") \
.start()
# Calculating time-based KPI
timeBasedKPIs = order_stream \
.withWatermark("timestamp", "1 minute") \
.groupby(window("timestamp", "1 minute", "1 minute")) \
.agg(count("invoice_no").alias("OPM"),
sum("total_cost").alias("total_sales_volume"),
avg("total_cost").alias("average_transaction_size"),
avg("is_return").alias("rate_of_return")) \
.select("window", "OPM", "total_sales_volume", "average_transaction_size", "rate_of_return")
# Stream for time based KPIs
timeBasedKPIsOutput = timeBasedKPIs \
.writeStream \
.outputMode("Append") \
.format("json") \
.option("format","append") \
.option("truncate", "false") \
.option("path", "time-wise-kpi") \
.option("checkpointLocation", "time-kpi") \
.option("truncate", "False") \
.trigger(processingTime="1 minute") \
.start()
# Calculating time-based and country-based KPIs
timeAndCountryBasedKPIs = order_stream \
.withWatermark("timestamp", "1 minute") \
.groupby(window("timestamp", "1 minute", "1 minute"), "country") \
.agg(count("invoice_no").alias("OPM"),
sum("total_cost").alias("total_sales_volume"),
avg("is_return").alias("rate_of_return")) \
.select("window", "country", "OPM", "total_sales_volume", "rate_of_return")
# Stream for time and country based KPIs
timeAndCountryBasedKPIsOutput = timeAndCountryBasedKPIs \
.writeStream \
.outputMode("Append") \
.format("json") \
.option("format","append") \
.option("truncate", "false") \
.option("path", "time-country-wise-kpi") \
.option("checkpointLocation","time-country-kpi") \
.trigger(processingTime="1 minute") \
.start()
# Waiting infinitely to read the data
timeAndCountryBasedKPIsOutput.awaitTermination()