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