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")
  }
相关推荐
培培说证18 小时前
2026 中专大数据技术专业考证书门槛低的有哪些?
大数据
小北方城市网18 小时前
第1课:架构设计核心认知|从0建立架构思维(架构系列入门课)
大数据·网络·数据结构·python·架构·数据库架构
收获不止数据库18 小时前
黄仁勋2026CES演讲复盘:旧世界,裂开了!
大数据·数据库·人工智能·职场和发展
老胡全房源系统19 小时前
房产中介管理系统哪一款性价比高
大数据·人工智能·房产经纪人培训
黄焖鸡能干四碗19 小时前
信息安全网络安全评估报告(WORD)
大数据·网络·人工智能·安全·web安全·制造·需求分析
汤姆yu19 小时前
基于python大数据的协同过滤音乐推荐系统
大数据·开发语言·python
Data_agent19 小时前
Cssbuy 模式淘宝 / 1688 代购系统南美市场搭建指南
大数据·python
川西胖墩墩19 小时前
团队协作泳道图制作工具 PC中文免费
大数据·论文阅读·人工智能·架构·流程图
云启数智YQ20 小时前
企业进行大数据迁移的注意事项有些什么?
大数据·大文件传输·跨国文件传输·内外网文件传输·大文件传输软件
房产中介行业研习社20 小时前
嘉兴国商区2026年1月品质楼盘推荐
大数据·人工智能·房产直播技巧·房产直播培训