我需要一组记录:
1)按'日期','城市'和'亲切'分组
2)按'奖
对每个组进行排序在我的代码中:
import org.apache.spark.SparkConf
import org.apache.spark.SparkContext
object Sort {
case class Record(name:String, day: String, kind: String, city: String, prize:Int)
val recs = Array (
Record("n1", "d1", "k1", "c1", 10),
Record("n1", "d1", "k1", "c1", 9),
Record("n1", "d1", "k1", "c1", 8),
Record("n2", "d2", "k2", "c2", 1),
Record("n2", "d2", "k2", "c2", 2),
Record("n2", "d2", "k2", "c2", 3)
)
def main(args: Array[String]): Unit = {
val conf = new SparkConf()
.setAppName("Test")
.set("spark.executor.memory", "2g")
val sc = new SparkContext(conf)
val rs = sc.parallelize(recs)
val rsGrp = rs.groupBy(r => (r.day, r.kind, r.city)).map(_._2)
val x = rsGrp.map{r =>
val lst = r.toList
lst.map{e => (e.prize, e)}
}
x.sortByKey()
}
}
当我尝试对组进行排序时,我收到错误:
value sortByKey is not a member of org.apache.spark.rdd.RDD[List[(Int,
Sort.Record)]]
有什么问题?怎么排序?
答案 0 :(得分:11)
您需要定义一个Key,然后使用mapValues对它们进行排序。
import org.apache.spark.{SparkContext, SparkConf}
import org.apache.spark.rdd.RDD
import org.apache.spark.SparkContext._
object Sort {
case class Record(name:String, day: String, kind: String, city: String, prize:Int)
// Define your data
def main(args: Array[String]): Unit = {
val conf = new SparkConf()
.setAppName("Test")
.setMaster("local")
.set("spark.executor.memory", "2g")
val sc = new SparkContext(conf)
val rs = sc.parallelize(recs)
// Generate pair RDD neccesary to call groupByKey and group it
val key: RDD[((String, String, String), Iterable[Record])] = rs.keyBy(r => (r.day, r.city, r.kind)).groupByKey
// Once grouped you need to sort values of each Key
val values: RDD[((String, String, String), List[Record])] = key.mapValues(iter => iter.toList.sortBy(_.prize))
// Print result
values.collect.foreach(println)
}
}
答案 1 :(得分:7)
groupByKey很贵,它有两个含义:
根据您的使用情况,您有更好的选择:
答案 2 :(得分:0)
将map
替换为flatMap
val x = rsGrp.map{r =>
val lst = r.toList
lst.map{e => (e.prize, e)}
}
这会给你一个
org.apache.spark.rdd.RDD[(Int, Record)] = FlatMappedRDD[10]
然后你可以在上面的RDD上调用sortBy(_._ 1)。
答案 3 :(得分:0)
作为@gasparms解决方案的替代方案,我认为可以尝试过滤后跟rdd.sortyBy操作。您筛选满足关键条件的每条记录。先决条件是您需要跟踪所有密钥(过滤器组合)。您还可以在遍历记录时构建它。