Problem: I have a problem to map most common value of a key in spark(using scala). I have done it with RDD but don't know how to do efficiently with DF/DS(sparksql)
dataset is like
key1 = value_a
key1 = value_b
key1 = value_b
key2 = value_a
key2 = value_c
key2 = value_c
key3 = value_a
After spark transformation and access output should be each key with its common value
Output
key1 = valueb
key2 = valuec
key3 = valuea
Tried until now:
RDD
I have tried to map and reduce by group of (key,value),count
in RDD and it makes logic but I cant translate this into sparksql(DataFrame/Dataset) (as I want minimum shuffle across network)
Here is my code for RDD
val data = List(
"key1,value_a",
"key1,value_b",
"key1,value_b",
"key2,value_a",
"key2,value_c",
"key2,value_c",
"key3,value_a"
)
val sparkConf = new SparkConf().setMaster("local").setAppName("example")
val sc = new SparkContext(sparkConf)
val lineRDD = sc.parallelize(data)
val pairedRDD = lineRDD.map { line =>
val fields = line.split(",")
(fields(0), fields(2))
}
val flatPairsRDD = pairedRDD.flatMap {
(key, val) => ((key, val), 1)
}
val SumRDD = flatPairsRDD.reduceByKey((a, b) => a + b)
val resultsRDD = SumRDD.map{
case ((key, val), count) => (key, (val,count))
}.groupByKey.map{
case (key, valList) => (name, valList.toList.sortBy(_._2).reverse.head)
}
resultsRDD.collect().foreach(println)
DataFrame , Using Windowing: I am trying with Window.partitionBy("key", "value")
to aggregate the count over the window
. and thn sorting
and agg()
respectively