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")
  }
相关推荐
boppu21 小时前
布草特殊污渍去渍剂的种类及作用
大数据·人工智能
Achou.Wang1 天前
深入理解go语言-第5章 并发编程——Go的灵魂
大数据·算法·golang
事变天下1 天前
迈瑞的足球之夏:从一次救援到全球守护
大数据·科技
中微极客1 天前
多智能体编排实战:CrewAI vs AutoGen(2026版)
大数据·网络·人工智能
西邮彭于晏1 天前
图文详解:Git分支创建、合并与冲突解决|新手零门槛完整教程
大数据·git·elasticsearch
IanSkunk1 天前
企业AI办公落地技术拆解:从WorkBuddy任务引擎到JOTO实施路径
大数据·人工智能
上海心泾国际物流有限公司1 天前
2024-2026年进出口报关政策五大变化
大数据·经验分享·交通物流
Xvisio诠视科技1 天前
从“感知”到“理解”:空间计算如何成为具身智能世界模型的“数据底座”?
大数据·空间计算
jerryinwuhan1 天前
数据预处理技术 2026-2027-1 开篇-课程介绍
大数据·python
Elastic 中国社区官方博客1 天前
Elastic 和 OpenAI 合作,将前沿智能引入非结构化企业数据
大数据·数据库·人工智能·elasticsearch·搜索引擎·ai