使用JavaPairRDD(键,值)对,我想以定义的顺序处理与每个键相关联的值(值比较器)。 是否可以在Apache Spark中使用?
使用Hadoop我会使用secondary sort模式。我正在寻找一种解决方案,它可以处理一组不适合内存的值(即使是一组具有相同键的值)
答案 0 :(得分:6)
以下是Sandy Ryza使用Spark进行高级分析的实现:
我重命名了一些变量并添加了一些注释,因此在更一般的上下文中是有意义的(本书中使用了这个片段来分析出租车数据,并且相应地命名了一些变量)。
def groupByKeyAndSortValues[K: Ordering : ClassTag, V: ClassTag, S](
rdd: RDD[(K,V)],
secondaryKeyFunc: (V) => S,
splitFunc: (V, V) => Boolean,
numPartitions: Int): RDD[(K, List[V])] = {
// Extract the secondary key by applying a function to the value.
val presess = rdd.map {
case (key, value) => {
((key, secondaryKeyFunc(value)), value)
}
}
// Define a partitioner that gets a partition by the first
// element of the new tuple key.
val partitioner = new FirstKeyPartitioner[K, S](numPartitions)
// Set the implicit ordering by the first element of the new
// tuple key
implicit val ordering: Ordering[(K, S)] = Ordering.by(_._1)
presess.repartitionAndSortWithinPartitions(partitioner).mapPartitions(groupSorted(_, splitFunc))
}
/**
* Groups the given iterator according to the split function. Assumes
* the data comes in sorted.
*/
def groupSorted[K, V, S](
it: Iterator[((K, S), V)],
splitFunc: (V, V) => Boolean): Iterator[(K, List[V])] = {
val res = List[(K, ArrayBuffer[V])]()
it.foldLeft(res)((list, next) => list match {
case Nil => {
val ((key, _), value) = next
List((key, ArrayBuffer(value)))
}
case cur :: rest => {
val (curKey, valueBuf) = cur
val ((key, _), value) = next
if (!key.equals(curLic) || splitFunc(valueBuf.last, value)) {
(key, ArrayBuffer(value)) :: list
} else {
valueBuf.append(value)
list
}
}
}).map { case (key, buf) => (key, buf.toList) }.iterator
}
这是分区:
class FirstKeyPartitioner[K1, K2](partitions: Int) extends
Partitioner {
val delegate = new HashPartitioner(partitions)
override def numPartitions = delegate.numPartitions
override def getPartition(key: Any): Int = {
val k = key.asInstanceOf[(K1, K2)]
delegate.getPartition(k._1)
}
}
答案 1 :(得分:4)
添加二级排序功能存在一个未解决的问题。然后到二级排序的方式是
rdd.map(row => (row.value, row.key)).sortByKey().map(row => (row.value, row.key))
sortByKey不会合并您的键,因此您可以使用相同值的倍数。