What is Spark Partition?
分區(qū)(Partitioning)實(shí)質(zhì)上是將數(shù)據(jù)劃分為多個(gè)部分踪蹬。在分布式系統(tǒng)中萍歉,分區(qū)被定義為將大數(shù)據(jù)集分割后存儲(chǔ)為集群的多個(gè)文件塊。
基于數(shù)據(jù)局部性的原則,Worker節(jié)點(diǎn)拉取靠近自己的數(shù)據(jù)執(zhí)行計(jì)算任務(wù)。通過(guò)分區(qū)猪腕,網(wǎng)絡(luò)IO請(qǐng)求量大大降低,從而使得數(shù)據(jù)處理的速度大大提高钦勘。
數(shù)據(jù)的分區(qū)是基于 RDD 實(shí)現(xiàn)的陋葡,不同分區(qū)的數(shù)據(jù)可以在不同的節(jié)點(diǎn)上被不同計(jì)算任務(wù)。RDD 中單個(gè)分區(qū)內(nèi)的數(shù)據(jù)只會(huì)被同一個(gè)任務(wù)(Task)處理彻采。
Partition Techniques
HashPartitioner
HashPartitioner 是 Spark 中的默認(rèn)分區(qū)方法脖岛,基于 Java 中 Object.hashcode()
實(shí)現(xiàn)分區(qū)功能. hashcode()
的作用是保證相等的對(duì)象擁有相同的 hashcode.
RangePartitioner
如果 RDD 中的數(shù)據(jù)是可排序的,則可以選擇 RangePartitioner 將數(shù)據(jù)記錄(Record)劃分為幾乎相等的區(qū)間颊亮。Spark 通過(guò)對(duì) RDD 內(nèi)數(shù)據(jù)進(jìn)行采樣的方法來(lái)確定區(qū)間邊界柴梆。
RangePartitioner 首先基于鍵值對(duì)數(shù)據(jù)記錄排序,然后依據(jù)傳入的分區(qū)數(shù)參數(shù)對(duì)記錄進(jìn)行分區(qū)终惑。
CustomPartitioner
通過(guò)繼承 Partitioner 類绍在,可以創(chuàng)建新的分區(qū)方法,以實(shí)現(xiàn)自定義分區(qū)數(shù)量并決定每個(gè)分區(qū)中存儲(chǔ)什么數(shù)據(jù)記錄雹有。
Code Snippets
Partition
分區(qū)在 Spark 中被定義為特質(zhì)(Trait)偿渡,如下所示:
/**
* An identifier for a partition in an RDD.
*/
trait Partition extends Serializable {
/**
* Get the partition's index within its parent RDD
*/
def index: Int
// A better default implementation of HashCode
override def hashCode(): Int = index
override def equals(other: Any): Boolean = super.equals(other)
}
Partition 的定義中,我們發(fā)現(xiàn)霸奕,分區(qū)中最重要的幾個(gè)元素是:
- index, 即該記錄在父 RDD 中的分區(qū)編號(hào)溜宽,通常一條記錄所屬的分區(qū)可由其在父 RDD 中的分區(qū)編號(hào)推導(dǎo)得到;
- hashCode(), 該分區(qū)的 hashCode;
- equals(other), 用于判斷兩個(gè)分區(qū)是否相等的方法质帅。
Partitioner
Partitioner 類在 Spark 中的定義如下:
abstract class Partitioner extends Serializable {
def numPartitions: Int
def getPartition(key: Any): Int
}
從定義中可以看到适揉,一個(gè)具體的分區(qū)方法必須實(shí)現(xiàn)兩個(gè)方法:
- numPartitions, 返回該分區(qū)方法最終將劃分出的類別總數(shù)量;
- getPartition(key), 根據(jù)傳入的鍵值煤惩,確定該記錄所屬的分區(qū)嫉嘀。
Experiences
Spark 中通過(guò) spark.default.parallelism
確定了 RDD 中分區(qū)的數(shù)量,通常取值為集群中可用核心(Core)數(shù)量的 2~3 倍魄揉。