RDD-自定义分区器案例

复制代码
package org.example

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


case class Order(id: Int, price: Double, info: String) {
  override def toString: String = s"$id, $price, $info"
}

class orderPartitioner extends Partitioner{

  override def numPartitions: Int = 3

  override def getPartition(key: Any): Int = {
    //0-1000 => 1
    //1001-2000 => 2
    //3
    if (key.asInstanceOf[Int] <= 1000) {
      0
    } else if (key.toString.toInt <= 2000) {
      1
    } else {
      2
    }
  }
}

object PartitionOrder {
  def main(args: Array[String]): Unit = {
    val conf = new SparkConf().setAppName("Partition").setMaster("local[*]")
    val sc = new SparkContext(conf)

    //读入data/order.csv 创建RDD
    val orderRDD = sc.textFile("data/order.csv")

    val rdd1 = orderRDD.map(line => {
      val fields = line.split(",")
      val order = Order(fields(0).toInt, fields(1).toDouble, fields(2))
      (order.id, order)
    })

    val rdd2 = rdd1.partitionBy(new orderPartitioner)

    rdd2.map(x => x._2).saveAsTextFile("data/output1")

    rdd2.mapPartitions(iter => {
      var count = 0

      var sum = 0.0
      iter.foreach(x => {
        sum += x._2.price
        count += 1
      })
      Iterator(s"${count}件, ${sum}元")
    })saveAsTextFile("data/output2")
  }
相关推荐
Easy_API7 小时前
2.8万亿参数,编程反超GPT-6 Astra:Kimi K3.1 Pro把开源模型推到了哪一步
大数据·人工智能·gpt·深度学习
GlobalInfo7 小时前
2026年机器人多指灵巧手市场分析报告——涵盖行业调查、趋势分析与发展前景
大数据·人工智能·microsoft·微服务·机器人
微订校园外卖平台9 小时前
校园外卖平台选模板还是定制:架构、数据流与验收清单
大数据·架构·外卖系统·本地生活·微订
Eloudy10 小时前
Qwen2.5-14B-Instruct-AWQ 模型文件结构分析
大数据·elasticsearch·搜索引擎
重生之高冷汉堡包13 小时前
跨境电商运营团队如何安全交接店铺账号?多账号权限管理指南
大数据
玩AI的奶茶13 小时前
MiniMax H3 出 30 秒长片:显存账、拼接法和一次的成本
大数据·人工智能·ai·gpu算力·算力租赁
SelectDB13 小时前
Doris Arrow Flight SQL 高速读取协议实战:与 Snowflake 客户端取数链路对照
大数据·数据库·数据分析
爱签AI电子合同14 小时前
电子合同全维度实测与选型指南
大数据·人工智能
AI办公探索者14 小时前
从SaaS到本地部署:大模型推理成本优化与8888元私有化方案的技术解析
大数据·人工智能
做运维的阿瑞14 小时前
云项目可观测性与成本治理:告警、日志、Dashboard 与预算标签
大数据·云原生·云计算·terraform