-
Notifications
You must be signed in to change notification settings - Fork 7
/
Partitioner.scala
35 lines (31 loc) · 1000 Bytes
/
Partitioner.scala
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
package org.hammerlab.spark
import org.apache.spark
/**
* Convenience-methods for creating Spark [[Partitioner]]s from (partial-)functions
*/
object Partitioner {
def apply(num: NumPartitions,
pf: PartialFunction[Any, PartitionIndex]): spark.Partitioner =
new spark.Partitioner {
override def numPartitions: PartitionIndex = num
override def getPartition(key: Any): PartitionIndex =
if (pf.isDefinedAt(key))
pf(key)
else
throw UnexpectedKey(key)
}
def apply[T](num: NumPartitions,
fn: T ⇒ PartitionIndex): spark.Partitioner =
new spark.Partitioner {
override def numPartitions: PartitionIndex = num
override def getPartition(key: Any): PartitionIndex =
try {
fn(key.asInstanceOf[T])
} catch {
case _: ClassCastException ⇒
throw UnexpectedKey(key)
}
}
}
case class UnexpectedKey(key: Any)
extends AssertionError(s"Key: $key")