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
相关推荐
大数据张老师3 分钟前
用 AI 做数据分析:从“数字”里挖“规律”博闻录2 小时前
以 “有机” 重构增长:云集从电商平台到健康生活社区的跃迁nbsaas-boot3 小时前
收银系统优惠功能架构:可扩展设计指南(含可扩展性思路与落地细节)lingling0094 小时前
实验记录安全存储:生物医药科研的数字化基石优秘智能UMI4 小时前
私有化大模型架构解决方案构建指南TDengine (老段)15 小时前
TDengine 转化类函数 TO_CHAR 用户手册黄雪超15 小时前
Kafka——多线程开发消费者实例ManageEngineITSM16 小时前
从混乱到秩序:IT服务管理如何重塑企业运营效率青云交17 小时前
Java 大视界 -- 基于 Java 的大数据分布式存储在工业互联网数据管理与边缘计算协同中的创新实践(364)