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
相关推荐
培培说证18 小时前
2026 中专大数据技术专业考证书门槛低的有哪些?小北方城市网18 小时前
第1课:架构设计核心认知|从0建立架构思维(架构系列入门课)收获不止数据库18 小时前
黄仁勋2026CES演讲复盘:旧世界,裂开了!老胡全房源系统19 小时前
房产中介管理系统哪一款性价比高黄焖鸡能干四碗19 小时前
信息安全网络安全评估报告(WORD)汤姆yu19 小时前
基于python大数据的协同过滤音乐推荐系统Data_agent19 小时前
Cssbuy 模式淘宝 / 1688 代购系统南美市场搭建指南川西胖墩墩19 小时前
团队协作泳道图制作工具 PC中文免费云启数智YQ20 小时前
企业进行大数据迁移的注意事项有些什么?房产中介行业研习社20 小时前
嘉兴国商区2026年1月品质楼盘推荐