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")
}
RDD-自定义分区器案例
懒惰的橘猫2025-05-14 9:26
相关推荐
武子康13 小时前
大数据-237 离线数仓 - Hive 广告业务实战:ODS→DWD 事件解析、广告明细与转化分析落地大大大大晴天15 小时前
Flink生产问题排障-Kryo serializer scala extensions are not available武子康3 天前
大数据-236 离线数仓 - 会员指标验证、DataX 导出与广告业务 ODS/DWD/ADS 全流程武子康4 天前
大数据-235 离线数仓 - 实战:Flume+HDFS+Hive 搭建 ODS/DWD/DWS/ADS 会员分析链路DianSan_ERP4 天前
电商API接口全链路监控:构建坚不可摧的线上运维防线够快云库4 天前
能源行业非结构化数据治理实战:从数据沼泽到智能资产AI周红伟4 天前
周红伟:智能体全栈构建实操:OpenClaw部署+Agent Skills+Seedance+RAG从入门到实战B站计算机毕业设计超人4 天前
计算机毕业设计Django+Vue.js高考推荐系统 高考可视化 大数据毕业设计(源码+LW文档+PPT+详细讲解)计算机程序猿学长4 天前
大数据毕业设计-基于django的音乐网站数据分析管理系统的设计与实现(源码+LW+部署文档+全bao+远程调试+代码讲解等)B站计算机毕业设计超人4 天前
计算机毕业设计Django+Vue.js音乐推荐系统 音乐可视化 大数据毕业设计 (源码+文档+PPT+讲解)