4.count
|
def count(): Long = sc.runJob(this, Utils.getIteratorSize_).sum |
計算資料總量,每個分區各自計算自己的總數,然後匯總到driver端,driver端再把每個分區的總數相加統計出對應rdd的資料量,其流程如下:
5.countApprox
在一定的逾時時間之內返回rdd元素的個數,其rdd元素的總數分布符合常態分佈,其分布因子為confidence,當超過timeout時,返回一個未完成的結果。
|
/**
* :: Experimental ::
* Approximate version of count() that returns a potentially incomplete result
* within a timeout, even if not all tasks have finished.
*/
@Experimental def countApprox(
timeout: Long,
confidence: Double = 0.95): PartialResult[BoundedDouble] = withScope {
//定義在excutor端計算總數的函數
val countElements: (TaskContext, Iterator[T]) => Long = { (ctx, iter) =>
var result = 0L
while (iter.hasNext) {
result += 1L
iter.next()
}
result
}
//定義在driver端的一個監聽回呼函數,當task完成的時候,會觸發裡面的merge操作,當逾時時間到之後或者任務提前完成的話,會取裡面的目前狀態,即currentResult
val evaluator = newCountEvaluator(partitions.length, confidence)
//提交任務
sc.runApproximateJob(this, countElements, evaluator, timeout)
} |
繼續往下看,看看evaluator是如何執行的:
|
def runApproximateJob[T,U, R](
rdd: RDD[T],
func: (TaskContext, Iterator[T]) =>U,
evaluator: ApproximateEvaluator[U, R],
timeout: Long): PartialResult[R] = {
assertNotStopped()
val callSite = getCallSite
logInfo("Starting job: " + callSite.shortForm)
val start = System.nanoTime
val cleanedFunc = clean(func)
// cleanedFunc就是countElements,evaluator就是CountEvaluator,逾時時間為timeout
val result = dagScheduler.runApproximateJob(rdd, cleanedFunc, evaluator, callSite, timeout,
localProperties.get)
logInfo(
"Job finished: " + callSite.shortForm +", took " + (System.nanoTime- start) / 1e9 + " s")
result
} |
繼續看runApproximateJob的實現:
|
def runApproximateJob[T,U, R](
rdd: RDD[T],
func: (TaskContext, Iterator[T]) =>U,
evaluator: ApproximateEvaluator[U, R],
callSite: CallSite,
timeout: Long,
properties: Properties): PartialResult[R] = {
//定義一個監聽器,當有任務完成的時候觸發taskSucceeded,當逾時時間到的時候返回CountEvaluator的當前值
val listener = newApproximateActionListener(rdd, func, evaluator, timeout)
val func2 = func.asInstanceOf[(TaskContext,Iterator[_]) => _]
val partitions = (0until rdd.partitions.size).toArray
val jobId = nextJobId.getAndIncrement()
//提交任務
eventProcessLoop.post(JobSubmitted(
jobId, rdd, func2, partitions, allowLocal = false, callSite, listener,
SerializationUtils.clone(properties)))
//等待計算結果
listener.awaitResult() // Will throw an exception if the job fails
} |
因此其逾時計算總數的邏輯主要在ApproximateActionListener裡面,請看ApproximateActionListener:
|
private[spark] classApproximateActionListener[T, U, R](
rdd: RDD[T],
func: (TaskContext, Iterator[T]) =>U,
evaluator: ApproximateEvaluator[U, R],
timeout: Long)
extends JobListener {
val startTime= System.currentTimeMillis()
val totalTasks= rdd.partitions.size
var finishedTasks= 0
var failure: Option[Exception] = None // Set if the job has failed (permanently)
var resultObject: Option[PartialResult[R]] = None// Set if we've already returned a PartialResult
//當某個分區完成的時候觸發taskSucceeded回呼函數
override def taskSucceeded(index: Int, result: Any) {
synchronized {
//更新CountEvaluator的當前值
evaluator.merge(index, result.asInstanceOf[U])
finishedTasks += 1
if (finishedTasks== totalTasks) {//當全部分區都完成的是退出等待,返回計算結果
// If we had already returned a PartialResult, set its final value
resultObject.foreach(r => r.setFinalValue(evaluator.currentResult()))
// Notify any waiting thread that may have called awaitResult
//退出等待
this.notifyAll()
}
}
}
……
/**
* Waits for up to timeout milliseconds since the listener was created and then returns a
* PartialResult with the result so far. This may be complete if the whole job is done.
*/
//等待計算結果
def awaitResult(): PartialResult[R] = synchronized {
val finishTime = startTime+ timeout
while (true) {
val time = System.currentTimeMillis()
if (failure.isDefined) {
throw failure.get
} else if (finishedTasks== totalTasks) {//如果在逾時時間之內計算完成,則返回全部結果
return new PartialResult(evaluator.currentResult(),true)
} else if (time >= finishTime) {//如果已經逾時,則返回部分結果
resultObject = Some(newPartialResult(evaluator.currentResult(), false))
return resultObject.get
} else {//如果逾時時間沒到,則繼續休眠
this.wait(finishTime - time)
}
}
// Should never be reached, but required to keep the compiler happy
return null
}
} |
其中如果在逾時時間之內沒有完成的話,evaluator.currentResult()會返回符合總數符合常態分佈的一個近似結果,感興趣的同學可以繼續研究下去:
|
private[spark] classCountEvaluator(totalOutputs: Int, confidence: Double)
extends ApproximateEvaluator[Long, BoundedDouble] {
var outputsMerged= 0
var sum: Long =0
override def merge(outputId: Int, taskResult: Long) {
outputsMerged += 1
sum += taskResult
}
override def currentResult(): BoundedDouble = {
if (outputsMerged== totalOutputs) {//全部完成
new BoundedDouble(sum,1.0, sum,sum)
} else if (outputsMerged== 0) {//一個任務都沒完成
new BoundedDouble(0,0.0, Double.NegativeInfinity, Double.PositiveInfinity)
} else {//部分完成,計算其理論總數的常態分佈參數
val p = outputsMerged.toDouble / totalOutputs
val mean = (sum+ 1 - p) / p
val variance = (sum+ 1) * (1 - p) / (p * p)
val stdev = math.sqrt(variance)
val confFactor = newNormalDistribution().
inverseCumulativeProbability(1 - (1- confidence) / 2)
val low = mean - confFactor * stdev
val high = mean + confFactor * stdev
new BoundedDouble(mean, confidence, low, high)
}
}
} |
因此countApprox的計算過程大致如下:1)excutor端不斷的計算分區的總數然後上報給driver端;2)driver端接受excutor上報的總數進行統計,如果在逾時時間之內沒有全部上報完成的話,則強制退出,返回一個其總數符合常態分佈的值,如果在逾時時間之內計算完成的話,則返回一個準確值。
6.countApproxDistinct
作用是對RDD集合內容進行去重統計,該統計是一個大約的統計,參數relativeSD控制統計的精確度。relativeSD越小,結果越準確。
|
/**
* Return approximate number of distinct elements in the RDD.
*
* The algorithm used is based on streamlib's implementation of "HyperLogLog in Practice:
* Algorithmic Engineering of a State of The Art Cardinality Estimation Algorithm", available
* <a href="http://dx.doi.org/10.1145/2452376.2452456">here</a>.
*
* @param relativeSD Relative accuracy. Smaller values create counters that require more space.
* It must be greater than 0.000017.
*/ def countApproxDistinct(relativeSD: Double =0.05): Long = withScope {
require(relativeSD > 0.000017, s"accuracy ($relativeSD) must be greater than 0.000017")
val p = math.ceil(2.0* math.log(1.054 / relativeSD) / math.log(2)).toInt
countApproxDistinct(if (p < 4) 4 elsep, 0)
} |
採用的是HyperLogLog in Practice演算法,原理比較深奧,有興趣的可以深究。
執行個體如下:
|
object CountApproxDistinct {
def main(args: Array[String]) {
val conf = new SparkConf().setAppName("spark-demo").setMaster("local")
val sc = new SparkContext(conf)
/**
* 構建一個集合,分成20個partition
*/
val a = sc.parallelize(1 to 10000 , 20)
//RDD a內容複寫5遍,其中有50000個元素
val b = a++a++a++a++a
//結果是9760,不傳參數,預設是0.05
println(b.countApproxDistinct())
//結果是9760
println(b.countApproxDistinct(0.05))
//8224
println(b.countApproxDistinct(0.1))
//10000
println(b.countApproxDistinct(0.001))
}
} |
7.collect
|
def collect(): Array[T] = withScope {
val results = sc.runJob(this, (iter:Iterator[T]) => iter.toArray)
Array.concat(results: _*)
} |
擷取Rdd的所有資料,然後緩衝在Driver端,其流程如下:
如果RDD資料量很大的話,請謹慎使用,因為會緩衝該RDD的所有資料量。
8.toLocalIterator
返回一個保護所有記錄的迭代器
|
/**
* Return an iterator that contains all of the elements in this RDD.
*
* The iterator will consume as much memory as the largest partition in this RDD.
*
* Note: this results in multiple Spark jobs, and if the input RDD is the result
* of a wide transformation (e.g. join with different partitioners), to avoid
* recomputing the input RDD should be cached first.
*/ def toLocalIterator:Iterator[T] = withScope {
//針對每個分區觸發一次action
def collectPartition(p: Int): Array[T] = {
sc.runJob(this, (iter: Iterator[T]) => iter.toArray, Seq(p), allowLocal =false).head
}
//調用flatMap將所有記錄組裝起來返回單個迭代器
(0 until partitions.length).iterator.flatMap(i => collectPartition(i))
} |
即:
|
scala> val rdd = sc.parallelize(1 to 10,2)
rdd: org.apache.spark.rdd.RDD[Int] = ParallelCollectionRDD[0] at parallelize at <console>:24
scala> val it = rdd.toLocalIterator
it: Iterator[Int] = non-empty iterator
scala> while(it.hasNext){
| println(it.next)
| }
1
2
3
4
5
6
7
8
9
10 |
9.takeOrdered
takeOrdered函數用於從RDD中,按照預設(升序)或指定定序,返回前num個元素。
|
def takeOrdered(num: Int)(implicitord: Ordering[T]): Array[T] = withScope {
if (num == 0) {
Array.empty
} else {
val mapRDDs = mapPartitions { items =>
//先在excutor端進行排序,按照ord定序,轉化為前num個優先隊列
// Priority keeps the largest elements, so let's reverse the ordering.
val queue = new BoundedPriorityQueue[T](num)(ord.reverse)
queue ++= util.collection.Utils.takeOrdered(items, num)(ord)
Iterator.single(queue)
}
if (mapRDDs.partitions.length ==0) {
Array.empty
} else {
//將分區的計算結果傳送給driver,轉化為數組,進行排序取前num條記錄
mapRDDs.reduce { (queue1, queue2) =>
queue1 ++= queue2
queue1
}.toArray.sorted(ord)
}
}
} |
例如:
|
List<Integer> data = Arrays.asList(1,4,3,2,5,6);
JavaRDD<Integer> JavaRDD = jsc.parallelize(data,2);
for(Integer integer:JavaRDD.takeOrdered(2)){
System.out.println(integer);
}
列印
1
2 |
其執行流程如下: