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")
  }
相关推荐
Dxy12393102161 小时前
别再让 ES 把你拖垮!5 个实战技巧让搜索性能提升 10 倍
大数据·elasticsearch·搜索引擎
2501_943695331 小时前
大专市场调查与统计分析专业,怎么辨别企业招聘的“画饼”岗位?
大数据
七夜zippoe1 小时前
CANN Runtime跨进程通信 共享设备上下文的IPC实现
大数据·cann
威胁猎人1 小时前
【黑产大数据】2025年全球电商业务欺诈风险研究报告
大数据
L543414462 小时前
告别代码堆砌匠厂架构让你的系统吞吐量翻倍提升
大数据·人工智能·架构·自动化·rpa
证榜样呀2 小时前
2026 大专计算机专业必考证书推荐什么
大数据·前端
LLWZAI2 小时前
让朱雀AI检测无法判断的AI公众号文章,当创作者开始与算法「躲猫猫」
大数据·人工智能·深度学习
SickeyLee2 小时前
产品经理案例分析(五):电商产品后台设计:撑起前台体验的 “隐形支柱”
大数据
callJJ3 小时前
Spring AI 文本聊天模型完全指南:ChatModel 与 ChatClient
java·大数据·人工智能·spring·spring ai·聊天模型