coalesce
说明
包括shuffle和不发生shuffle两种方式。 主要用于缩减分区,大数据集过滤后,提高小数据集的执行效率。
函数签名
代码示例
val conf: SparkConf = new SparkConf( ) . setAppName( this . getClass. getName) . setMaster( "local[*]" )
val sc = new SparkContext( conf)
val rdd: RDD[ Int ] = sc. makeRDD( 1 to 10 , 3 )
println( "-----------------分区前--------------------" )
rdd. mapPartitionsWithIndex{
( index, datas) => {
println( index + "--->" + datas. mkString( "," ) )
datas
}
} . collect( )
println( "-----------------分区后--------------------" )
val newRDD: RDD[ Int ] = rdd. coalesce( 4 )
newRDD. mapPartitionsWithIndex{
( index, datas) => {
println( index + "--->" + datas. mkString( "," ) )
datas
}
} . collect( )
sc. stop( )
repartition
说明
底层调用的其实是coalesce,但是会发生shuffle。无论是分区数减少的操作,还是分区数增加的操作,repartition都能完成。
函数签名
代码示例
val conf: SparkConf = new SparkConf( ) . setAppName( this . getClass. getName) . setMaster( "local[*]" )
val sc = new SparkContext( conf)
val rdd: RDD[ Int ] = sc. makeRDD( 1 to 10 , 2 )
println( "-----------------分区前--------------------" )
rdd. mapPartitionsWithIndex{
( index, datas) => {
println( index + "--->" + datas. mkString( "," ) )
datas
}
} . collect( )
println( "-----------------分区后--------------------" )
val newRDD: RDD[ Int ] = rdd. repartition( 3 )
newRDD. mapPartitionsWithIndex{
( index, datas) => {
println( index + "--->" + datas. mkString( "," ) )
datas
}
} . collect( )
sc. stop( )
区别
coalesce重新分区,可以选择是否进行shuffle过程。由参数shuffle: Boolean = false/true决定。 repartition实际上是调用的coalesce,进行shuffle。 coalesce一般为缩减分区,如果扩大分区,不使用shuffle是没有意义的,repartition扩大分区执行shuffle。