1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
| |
package com.lyzx.day11
import breeze.linalg.split
import org.apache.spark.{SparkConf, SparkContext}
class T1 {
/*
parallelize方法是把scala内部集合准换为一个RDD的操作即创建spark中RDD穿的操作
*/
def f1_parallelize(sc:SparkContext): Unit ={
val arr =Array(1,2,3,4,5)
val arrRdd = sc.parallelize(arr);
arrRdd.map(_*10).foreach(println)
}
def f2_flatMap(sc:SparkContext): Unit ={
val arr = Array(1,2,3,4,5)
val rdd = sc.parallelize(arr)
rdd.map(item=>(1 to item)).foreach(item=>println("map:"+item))
rdd.flatMap(item=>(1 to item)).foreach(item=>print(item+" "))
}
/*
glom函数(glom有偷、抢、看的意思)
该函数把一个RDD中每一个partition上的所有T类型的元素转换为Array[T]即把每个partition上的元素全部集中到一个数组中
*/
def f3_glom(sc:SparkContext,partitions:Int): Unit ={
//把1-10的集合放在partitions个分区中,用<<>>代表一个partition,当partitions=3时,rdd中的数据为[<<1,2,3>>,<<4,5,6>>,<<7,8,9,10>>]
val rdd = sc.makeRDD((1 to 10),partitions)
//调用glom函数把该RDD上的3个分区中的每一个partition上的元素全部放到一个数组中,通过调用glom()函数后该RDD上的数据变为,[[1,2,3],[4,5,6],[7,8,9,10]]
rdd.glom().collect().foreach(item=>{
println("item.length="+item.length)
item.foreach(
item=>println(item)
)
})
} //2 7 9 || 4 5 6 8 10 || 1 3
def f4_randomSplit(sc:SparkContext): Unit ={
val rdd = sc.makeRDD(1 to 10 ,10)
val randomRdd = rdd.randomSplit(Array(1,8))
println(randomRdd.length) // randomRdd(0).collect().foreach(println) // println("==============================") // randomRdd(1).collect().foreach(println) // println("==============================") // randomRdd(2).collect().foreach(println)
}
}
object T1{
def main(args: Array[String]) {
val conf = new SparkConf();
conf.setAppName("operation").setMaster("local")
val sc = new SparkContext(conf)
val t1 = new T1 // t1.f1_parallelize(sc) // t1.f2_flatMap(sc) // t1.f3_glom(sc,3)
t1.f4_randomSplit(sc)
}
}
|