spark中RDD的五大特性

RDD是什麼

下面這個是Spark源碼中RDD的第一行描述

 A Resilient Distributed Dataset (RDD), the basic abstraction in Spark. 
 Represents an immutable,partitioned collection of elements 
 that can be operated on in parallel

1.一個彈性分佈式的數據集
2.集合的元素是分區的
3.可以並行計算

RDD的五大特性和方法

1)A list of partitions
一系列分區的集合
方法:protected def getPartitions: Array[Partition]

2)A function for computing each split
針對RDD做操作其實就是針對RDD底層的partition進行操作
方法:def compute(split: Partition, context: TaskContext): Iterator[T]

3)A list of dependencies on other RDDs
rdd之間的依賴
protected def getDependencies: Seq[Dependency[_]] = deps

4)a Partitioner for key-value RDDs
對於key-valueRDD可以傳遞Partitioner進行重新分區
@transient val partitioner: Option[Partitioner] = None

5)a list of preferred locations to compute each split on
最優的位置計算,也就是數據本地化(優先把作業調度到數據所在節點)
protected def getPreferredLocations(split: Partition): Seq[String] = Nil

RDD的創建方式

RDD創建有兩種方法:
1.parallelize (一般用於測試)

val rdd = sc.parallelize(List(1, 2, 3, 4, 5))

2.External File System (用於生產)

sc.textFile("hdfs://hadoop001:9000/hello/wc.txt")

RDD的操作

RDD的操作包含transformation和action
transformation 轉換,記錄了RDD演變的過程,只有action纔會觸發transformation進行計算

transformation

算子 描述
map 針對每個元素做操作
mapPartitions 針對每個分區做操作
mapValues 針對RDD[key,value]的value做處理
flatmap map+flatten
glom 把每個分區的數據都放到數組中
filter 過濾
union a.union(b) 是兩個rdd的合併
intersection a.intersection(b)是兩個rdd的交集
subtract 差集
distinct 去重
groupByKey 按照key分組,默認map端不合並
reduceByKey 按照key分組,默認map端合併
groupBy 自定義分組
sortBy 自定義排序
sortByKey 按照key來排序
join 兩個rdd的內連接
cogroup join的底層就是cogroup

action

算子 描述
count 計算rdd中的元素個數
collect 把rdd的元素都收集到一個數組中
foreach 循環每個元素
reduce 聚合rdd中的元素,rdd.reduce(+)就是每個元素相加
first 獲取第一個元素,底層調用的是take(1)
take(n) 獲取前n個元素
top(n) 返回最大的前n個元素,底層調用的是takeOrdered
takeOrdered(n) 獲取最小的前n個元素
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章