spark二次排序

一般的二次排序,可以参考https://www.iteblog.com/archives/1819.html这篇文章,但是他的这种方式有问题。在这块代码:

item._2.toList.sortWith(_.toInt<_.toInt)

如果数据量非常大的话,会全部加在到内存中,容易造成内存溢出。

在spark中可以使用repartitionAndSortWithinPartitions这个算子,它会一边进行shuffle的时候就会对分区中的数据进行排序,要使用这个算子需要做两件事:

  1. 自定义Partitioner

  2. 提供一个隐式的Ordering,可以看一下OrderedRDDFunctions源码中该算子需要的参数

    private val ordering = implicitly[Ordering[K]]
    
    def repartitionAndSortWithinPartitions(partitioner: Partitioner): RDD[(K, V)] = self.withScope {
     new ShuffledRDD[K, V, V](self, partitioner).setKeyOrdering(ordering)
    }

数据还是上面那篇文章中的数据

2015,1,24
2015,3,56
2015,1,3
2015,2,-43
2015,4,5
2015,3,46
2014,2,64
2015,1,4
2015,1,21
2015,2,35
2015,2,0

还是将年和月拼成一个字符串然后将(年-月, 总数)当做key,value其实随便。

在进行分区时,只要<年-月>相同的都分到相同分区中

在进行排序是,先比较<年-月>,如果<年-月>相同再比较总数

代码

import org.apache.spark.{Partitioner, SparkConf, SparkContext}

object SparkTest {

  def main(args: Array[String]): Unit = {
    implicit val ord = new Ordering[(String, Int)] {
      override def compare(x: (String, Int), y: (String, Int)): Int = {
        val c = x._1.compareTo(y._1)
        if (c == 0) x._2.compareTo(y._2) else c
      }
    }

    val conf = new SparkConf().setMaster("local[*]").setAppName("SparkTest")
    val sc = new SparkContext(conf)
    val rdd = sc.parallelize(Seq("2015,1,24", "2015,3,56", "2015,1,3", "2015,2,-43", "2015,4,5", "2015,3,46", "2014,2,64", "2015,1,4", "2015,1,21", "2015,2,35", "2015,2,0"))
    rdd.map(s => {
      val arr = s.split(",")
      ((s"${arr(0)}-${arr(1)}", arr(2).toInt), arr(2).toInt)
    })
      .repartitionAndSortWithinPartitions(new CustomPartitioner(3))
      .map { case ((k, v), _) => (k, v) }
      .saveAsTextFile("xxxxxx")

  }

  class CustomPartitioner(partitions: Int) extends Partitioner {

    require(partitions > 0, s"Number of partitions ($partitions) cannot be negative.")

    def numPartitions: Int = partitions

    def getPartition(key: Any): Int = key match {
      case (k: String, _: Int) => math.abs(k.hashCode % numPartitions)
      case null => 0
      case _ => math.abs(key.hashCode % numPartitions)
    }

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

    override def hashCode: Int = numPartitions
  }

}

最后三个分区的数据

(2014-2,64)
(2015-1,3)
(2015-1,4)
(2015-1,21)
(2015-1,24)
(2015-4,5)
(2015-2,-43)
(2015-2,0)
(2015-2,35)
(2015-3,46)
(2015-3,56)
### Spark 二次排序实现方法 在 Spark 中实现二次排序的核心在于自定义键(Key),并让该键继承 `Ordered` 和 `Serializable` 接口。通过重写 `compare` 方法来指定排序逻辑,最终利用 `sortByKey` 算子完成排序操作。 以下是基于 Scala 的具体实现方式: #### 自定义 Key 类 为了支持多字段排序,需创建一个自定义的 Key 类,并实现 `Ordered` 接口中的 `compare` 方法。此方法决定了排序顺序。 ```scala class SecondarySortKey(val first: Int, val second: Int) extends Ordered[SecondarySortKey] with Serializable { override def compare(that: SecondarySortKey): Int = { if (this.first - that.first != 0) { this.first - that.first // 首先按第一个字段升序排列 } else { this.second - that.second // 如果第一个字段相同,则按第二个字段升序排列 } } override def toString(): String = s"$first,$second" } ``` #### 主程序代码 下面是一个完整的示例代码,展示如何读取文件、映射为 `(Key, Value)` 对、执行排序以及输出结果。 ```scala object SparkSecondarySortExample { def main(args: Array[String]): Unit = { val conf = new SparkConf().setAppName("SparkSecondarySort").setMaster("local[*]") val sc = new SparkContext(conf) // 加载输入数据 val inputRDD = sc.textFile("input/data.txt") // 将每行转换为 (CustomKey, Line) 形式的 RDD val keyValueRDD = inputRDD.map { line => val fields = line.split(",") (new SecondarySortKey(fields(0).toInt, fields(1).toInt), line) } // 按照自定义 Key 进行排序 val sortedRDD = keyValueRDD.sortByKey() // 提取出原始的数据行 val resultRDD = sortedRDD.map(_._2) // 输出结果 resultRDD.collect().foreach(println) sc.stop() } } ``` 以上代码实现了以下功能: - **加载数据**:从本地文件系统中读取数据[^1]。 - **映射处理**:将每一行解析为由自定义 Key 和原字符串组成的元组[^4]。 - **排序操作**:调用 `sortByKey()` 函数按照自定义 Key 定义的规则进行全局排序[^2]。 - **提取结果**:移除辅助的 Key 数据结构,仅保留实际的内容[^3]。 #### 输入与输出样例 假设输入文件 `data.txt` 如下: ``` 1,5,Alice 2,3,Bob 1,7,Charlie 2,1,Dave ``` 运行上述程序后得到的结果将是: ``` 1,5,Alice 1,7,Charlie 2,1,Dave 2,3,Bob ``` 这表明首先依据第一列数值从小到大排序;如果存在相同的值,则进一步比较第二列以决定位置关系。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值