spark core sortBy和sortByKey探索

感觉自己好久没有更新过博客了,本人最近有点儿迷失,特来写篇技术博客,以做自警

不知道大家有没有注意到,大家在编写spark程序调用sortBy/sortByKey这两个算子的时候大家会不会有这样子的疑问,他们两个明明是transformation,为啥在执行的时候却触发了作业的执行呢?今天就和大家一起一探究竟?

 val wordCountRdd = spark.sparkContext.textFile(path).
      flatMap(_.split(" ")).
      map(word => (word, 1)).
      reduceByKey(_ + _)

    val sortByCountDescRdd = wordCountRdd.sortBy(-_._2)

当你在shell输入一下的code时,会发现如下图:
在这里插入图片描述
出现了类似action的运行条,到底怎么回事儿呢?
首先sortBy的实现就是调用了sortByKey,所以我们只关注sortByKey的实现

def sortByKey(ascending: Boolean = true, numPartitions: Int = self.partitions.length)
      : RDD[(K, V)] = self.withScope
  {
    val part = new RangePartitioner(numPartitions, self, ascending)
    new ShuffledRDD[K, V, V](self, part)
      .setKeyOrdering(if (ascending) ordering else ordering.reverse)
  }

此时先看RangePartitioner分区器的实现,只挑重要部分开始描述啊

private[spark] object RangePartitioner {

  /**
   * Sketches the input RDD via reservoir sampling on each partition.
   *
   * @param rdd the input RDD to sketch
   * @param sampleSizePerPartition max sample size per partition
   * @return (total number of items, an array of (partitionId, number of items, sample))
   */
  def sketch[K : ClassTag](
      rdd: RDD[K],
      sampleSizePerPartition: Int): (Long, Array[(Int, Long, Array[K])]) = {
    val shift = rdd.id
    // val classTagK = classTag[K] // to avoid serializing the entire partitioner object
    val sketched = rdd.mapPartitionsWithIndex { (idx, iter) =>
      val seed = byteswap32(idx ^ (shift << 16))
      val (sample, n) = SamplingUtils.reservoirSampleAndCount(
        iter, sampleSizePerPartition, seed)
      Iterator((idx, n, sample))
    }.collect()
    val numItems = sketched.map(_._2).sum
    (numItems, sketched)
  }

在这里调用了RDD的collect action算子出发了作业的运行,其实此处的collection是对key进行采样已确认key的分布情况,总之是在为做全局排序做准备。

想知道详细的请查看spark源码执行吧

Spark中的sort byorder by是用于对数据进行排序的操作。sort by是将数据放到多个reduce里面进行排序,排序后每一个reduce里面的数据是有序的,但是全部数据不一定有序。如果reduce个数为1,此时全部数据有序,等价于order by操作。当需要对全部数据排序时,可以先使用sort by局部排序(sort by可以设置reduce个数),然后再使用order by排序,将会大大提高效率。\[1\] Spark采用的排序方法是TIMSort,它是归并排序的优化版,并且在小数据量时切换为binarySort来提升效率。无论是TimSort还是binarySort都是排序稳定的,因此不应该出现多次结果不一致的情况。在Spark的代码中,可以追踪到ShuffleInMemorySorter类中的insertRecord方法,该方法用于将记录插入到排序器中。\[2\] 另外,Spark中还有其他与排序相关的操作,如group by、distribute byorder by。group by将相同的key放到同一个reduce中,但后面必须跟聚合操作;distribute bygroup by的作用类似,都是将key值相同的数据放到同一个reduce中;而order by是全局排序,而sort by是局部排序,当sort by中reduce为1时,等价于order by。\[3\] #### 引用[.reference_title] - *1* *3* [【Hive】sort by、order by、 distribute by、 group by 、cluster by区别](https://blog.youkuaiyun.com/Asher117/article/details/108979573)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down1,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [避坑:Spark Sql的Order By排序是不稳定的](https://blog.youkuaiyun.com/weixin_39445556/article/details/121072103)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值