Spark Partitioner使用 2015-09-02 21:01

说明

Spark原生有两种Partitioner:RangePartitioner和HashPartitioner。同时,支持自定义Partitioner。

示例

 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
import org.apache.spark.Partitioner
import org.apache.spark.RangePartitioner

// 自定义Partitioner函数
class MyPartitioner(partitions: Int) extends Partitioner {
  def numPartitions: Int = partitions

  def getPartition(key: Any): Int = { 
      key match {
        case null => 0
        case iKey: Int => iKey % numPartitions
        case _ => 0
      }
  }

  override def equals(other: Any): Boolean = {
      other match {
        case h: MyPartitioner =>
          h.numPartitions == numPartitions
        case _ =>
          false
      }
  }
}


//打印出各partition的数据
def myfunc(index: Int, iter: Iterator[(Int, Int)]) : Iterator[(Int, Int)] = {
  println("[partID:" +  index + ", val: " + iter.toList + "]")
  iter
}

val a = sc.parallelize(List((1,1),(2,2),(3,3),(1,11),(2,12),(3,13),(4,14),(5,15),(6,16)), 1)
a.mapPartitionsWithIndex(myfunc).collect
// [partID:0, val: List((1,1), (2,2), (3,3), (1,11), (2,12), (3,13), (4,14), (5,15), (6,16))]

// 默认继承父RDD的Partition数量,并使用内置的HashPartitioner
val b = a.reduceByKey(_ + _)
b.mapPartitionsWithIndex(myfunc).collect
// 结果如下:
// [partID:0, val: List((4,14), (1,12), (6,16), (3,16), (5,15), (2,14))]

// 指定Partition的数量为2,使用内置的HashPartitioner
val c = a.reduceByKey(_ + _, 2)
c.mapPartitionsWithIndex(myfunc).collect
// 结果如下:
// [partID:0, val: List((4,14), (6,16), (2,14))]
// [partID:1, val: List((1,12), (3,16), (5,15))]


// 指定分区函数,在分区函数中指定分区数量
val p = new MyPartitioner(3)
val d = a.reduceByKey(p, _ + _)
d.mapPartitionsWithIndex(myfunc).collect
// 结果如下:
// [partID:0, val: List((6,16), (3,16))]
// [partID:1, val: List((4,14), (1,12))]
// [partID:2, val: List((5,15), (2,14))]

// 按key范围分区
val p2 = new RangePartitioner(3, a, false)
val e = a.reduceByKey(p2, _ + _)
e.mapPartitionsWithIndex(myfunc).collect
// 结果如下,各分区内的key是降序的:
// [partID:1, val: List((4,14), (3,16))]
// [partID:0, val: List((6,16), (5,15))]
// [partID:2, val: List((1,12), (2,14))]

Spark源码中cogroup-like函数的默认Partitioner

逻辑是:如果父RDD有分区函数,继承之.如果没有,使用HashPartitioner。如果设置并行度,使用之。如果没有,继承父RDD中最大分区数量。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
def defaultPartitioner(rdd: RDD[_], others: RDD[_]*): Partitioner = {
    val bySize = (Seq(rdd) ++ others).sortBy(_.partitions.size).reverse
    for (r <- bySize if r.partitioner.isDefined) {
      return r.partitioner.get
    }
    if (rdd.context.conf.contains("spark.default.parallelism")) {
      new HashPartitioner(rdd.context.defaultParallelism)
    } else {
      new HashPartitioner(bySize.head.partitions.size)
    }
  }
Tags: #Spark    Post on Spark