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
162
163
164
165
166
|
import org.apache.spark.sql.SparkSession
import org.apache.spark.rdd.RDD
import org.apache.spark.HashPartitioner
/** A Spark application that analyzes co-purchased products.
*
* This object processes a CSV input file containing order-product pairs and
* generates a report of products that are frequently purchased together. The
* analysis helps identify product relationships and potential recommendations
* for a shopping system.
*
* Input format: CSV file with each line containing "orderId,productId" Output
* format: CSV file with each line containing "product1,product2,count"
*
* @example
* {{{
* // Run the application with input path and output path
* spark-submit co-purchase-analysis.jar input.csv output/
* }}}
*/
object CoPurchaseAnalysis {
/** Represents a pair of products that were purchased together.
*
* @param product1
* The identifier of the first product
* @param product2
* The identifier of the second product
*/
case class ProductPair(product1: Int, product2: Int)
/** Validates command line arguments and checks file existence.
*
* @param args
* Command line arguments array containing input file path and output
* directory path
* @return
* Some(errorMessage) if validation fails, None if validation succeeds
*/
def checkArguments(args: Array[String]): Option[String] = {
if (args.length != 2) {
return Some("Need params: <inputPath> <outputFolder>")
}
return None
}
/** Creates and configures a SparkSession.
*
* @param appName
* The name of the Spark application
* @return
* Configured SparkSession instance
*/
def createSparkSession(appName: String): SparkSession = {
var session = SparkSession.builder
.appName(appName)
.config("spark.executor.memory", "6g")
.config("spark.executor.cores", "4")
.config("spark.driver.memory", "4g")
val creds = System.getenv("GOOGLE_APPLICATION_CREDENTIALS")
if (creds != null) {
session
.config("spark.hadoop.google.cloud.auth.service.account.enable", "true")
.config(
"spark.hadoop.google.cloud.auth.service.account.json.keyfile",
creds
)
}
session.getOrCreate()
}
/** Parses a single line from the input file into a tuple. Expects the line to
* be in CSV format with orderId and productId.
*
* @param line
* Input line in format "orderId,productId"
* @return
* (Int, Int) tuple containing the parsed data
*/
def parseLine(line: String): (Int, Int) = {
val parts = line.split(",")
(parts(0).toInt, parts(1).toInt)
}
/** Processes the order data to generate co-purchase statistics.
*
* The processing pipeline includes: (1) Grouping orders by orderId, (2)
* Generating product pairs for each order, (3) Counting occurrences of each
* product pair
*
* @param data
* RDD containing (Int, Int)
* @param partitionsNumber
* Number of partitions used by HashPartitioner
* @return
* RDD containing CoPurchase instances with purchase frequency counts
*/
def processData(
data: RDD[(Int, Int)],
partitionsNumber: Int
): RDD[String] = {
val pairs = data
.partitionBy(new HashPartitioner(partitionsNumber))
.groupByKey()
.flatMap { case (_, productIds) =>
val products = productIds.toSeq
for {
x <- products
y <- products if x < y
} yield (ProductPair(x, y), 1)
}
val coProducts = pairs.reduceByKey(_ + _)
val result = coProducts.map {
case (ProductPair(product1, product2), count) =>
s"${product1},${product2},${count}"
}
result.repartition(1)
}
/** Main entry point for the application.
*
* @param args
* Command line arguments array
*/
def main(args: Array[String]): Unit = {
val argsError = checkArguments(args)
if (!argsError.isEmpty) {
println(argsError.get)
return
}
// Configuration values should be passed as parameters
val config = Map(
"appName" -> "Co-Purchase Analysis",
"inputPath" -> args(0),
"outputPath" -> args(1)
)
// Program execution composed of pure functions
val spark = createSparkSession(config("appName"))
try {
spark.sparkContext.setLogLevel("ERROR")
val inputRDD = spark.sparkContext
.textFile(config("inputPath"))
.map(parseLine)
val cores = spark.conf.get("spark.executor.cores", "4").toInt
val nodes = spark.conf.get("spark.executor.instance", "4").toInt
val partitinosNumber =
math.max(cores * nodes * 2, spark.sparkContext.defaultParallelism * 2)
val result = processData(inputRDD, partitinosNumber)
.saveAsTextFile(config("outputPath"))
} finally {
spark.stop()
}
}
}
|