重分区的两种方式(coalesce与reparation):
dataset(spark2.0以上,dataset/dataframe):coalesce(shuffle=false);reparation(shuffle=true,且可按column进行分区);
rdd:coalesce(默认shuffle=false,可传参数,开启shuffle);reparation(shuffle=true)。
spark2.10中重分区方法源码:
def repartition(numPartitions: Int)(implicit ord: Ordering[T] = null): RDD[T] = withScope {
coalesce(numPartitions, shuffle = true)
}
def coalesce(numPartitions: Int, shuffle: Boolean = false,
partitionCoalescer: Option[PartitionCoalescer] = Option.empty)
(implicit ord: Ordering[T] = null)
: RDD[T]{
...
}
def repartition(numPartitions: Int): Dataset[T] = withTypedPlan {
Repartition(numPartitions, shuffle = true, logicalPlan)
}
def repartition(numPartitions: Int, partitionExprs: Column*): Dataset[T] = withTypedPlan {
RepartitionByExpression(partitionExprs.map(_.expr), logicalPlan, Some(numPartitions))
}
def coalesce(numPartitions: Int): Dataset[T] = withTypedPlan {
Repartition(numPartitions, shuffle = false, logicalPlan)
}
shuffle开关的区别(见图):
在增大分区时,一定涉及到shuffle write,此时shuffle=false,重分区失效;
在减小分区时,shuffle=true的并行度高于shuffle=false。
shuffle=true时,在reparation时拆分成stage(rdd宽依赖),经历MapPartitionsRDD、CoalescedRDD、ShuffledRowRDD
shuffle=false时,不会拆分stage(rdd窄依赖),只有CoalescedRDD;
rdd coalesce(shuffle=false):
rdd coalesce(shuffle=true):(原本satge2被拆分)
总结:一般来说,在减小区数时,分区数差距较小、数据量较小shuffle=false,反之shuffle=true。
注:shuffle=false时,reparation前需要有action操作,否则前面的transform操作的task数都会受限!