The implementation process of spark operator is detailed in the second

Source: Internet
Author: User
4.count

def count (): Long = Sc.runjob (this, utils.getiteratorsize_). Sum

Calculates the total amount of data, each partition calculates its own total, then summarizes to the driver end, the driver end then adds the total number of each partition to count the amount of data corresponding to the RDD, the process is as follows:


5.countApprox

The number of RDD elements is returned within a certain time-out period, the total number of RDD elements is distributed in accordance with the normal distribution, the distribution factor is confidence, and when timeout is exceeded, an incomplete result is returned.

/**
*:: Experimental::
* Approximate version of Count () that returns a potentially incomplete result
* Within a timeout, even if not all tasks has finished.
*/
@Experimental
def Countapprox (
Timeout:long,
confidence:double = 0.95): partialresult[boundeddouble] = withscope {

A function that defines the total count on the Excutor side
Val
countelements: (Taskcontext, iterator[t]) = = Long = {(CTX, iter) = =
var result = 0L
while (Iter.hasnext) {
Result + = 1L
Iter.next ()
}
Result
}

A listener callback function is defined on the driver side, and when the task is completed, the merge operation is triggered, and when the time-out expires or the task is completed in advance, the current state is taken, i.e. Currentresult
Val
evaluator = newcountevaluator (partitions.length, confidence)

Submit a Task
Sc.runapproximatejob (This, countelements, evaluator, timeout)

}

Keep looking down and see how evaluator is executed:

def Runapproximatejob[t,u, R] (
    rdd:rdd[t],
    func: ( Taskcontext, Iterator[t]) =>u,
    evaluator:approximateevaluator[u, R],
     Timeout:long): partialresult[r] = {
  assertnotstopped ()
  val callSite = getca Llsite
  Loginfo ( "Starting job:" + callsite.shortform)
  Val start = System.nanotime
  val cleanedfunc = Clean (func)

Cleanedfunc is Countelements,evaluator is Countevaluator, timeout time is timeout
Val
result = Dagscheduler.runapproximatejob (Rdd, Cleanedfunc, evaluator, CallSite, timeout,
Localproperties.get)
Loginfo (
"Job finished:" + callsite.shortform +", took" + (System.nanotime-start)/1e9 + "s")
Result

}

Continue to see the implementation of 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] = {

Defines a listener that triggers tasksucceeded when a task is completed and returns the current value of Countevaluator when the time-out expires
Val
listener = newapproximateactionlistener (Rdd, func, evaluator, timeout)
val func2 = func.asinstanceof[(Taskcontext,iterator[_]) = _]
val partitions = (0until rdd.partitions.size). ToArray
val jobId = nextjobid.getandincrement ()

Submit a Task
Eventprocessloop.post (jobsubmitted (
JobId, Rdd, FUNC2, partitions, allowlocal = false, CallSite, Listener,
Serializationutils.clone (properties)))

Wait for calculation results
Listener.awaitresult ()//would throw an exception if the job fails

}

So the logic for the total number of timeout calculations is mainly in Approximateactionlistener, see Approximateactionlistener:

private [spark] class approximateactionlistener[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 returne D a partialresult
 

Trigger the tasksucceeded callback function when a partition is complete
override def tasksucceeded (Index:int, Result:any) {
Synchronized {

Update the current value of Countevaluator
Evaluator.merge (index, Result.asinstanceof[u])
Finishedtasks + = 1
if (finishedtasks== totaltasks) {//When all partitions complete are exit wait, return the result of the calculation
If we had already returned a Partialresult, set its final value
Resultobject.foreach (r = R.setfinalvalue (Evaluator.currentresult ()))
Notify any waiting thread, the May has called Awaitresult

Exit wait
this. Notifyall ()
}
}
}
...
/**
* Waits to-timeout milliseconds since the listener is created and then returns a
* Partialresult with the result so far. This could be complete if the whole job was done.
*/

//wait for calculation results
defAwaitresult (): partialresult[r] = synchronized {
ValFinishtime = starttime+ Timeout
while(true) {
ValTime = System.currenttimemillis ()
if(failure.isdefined) {
ThrowFailure.get
}else if(finishedtasks== totaltasks) {//If the calculation is completed within the timeout period, all results are returned
return new
Partialresult (Evaluator.currentresult (),true)
}else if(Time >= Finishtime) {//If it has timed out, some results are returned
Resultobject = Some (NewPartialresult (Evaluator.currentresult (),false))
returnResultobject.get
}Else{//If the timeout period is not reached, continue to hibernate
this
. Wait (Finishtime-time)
}
}
Should never is reached, but required to keep the compiler happy
return NULL
}

}

If it is not completed within the time-out period, Evaluator.currentresult () will return an approximate result that matches the total number of the normal distribution, and interested students can continue to study:

Private[Spark]classCountevaluator (Totaloutputs:int, confidence:double)
extendsApproximateevaluator[long, Boundeddouble] {

varoutputsmerged= 0
varSum:long =0

Override DefMerge (Outputid:int, Taskresult:long) {
Outputsmerged + = 1
Sum + = Taskresult
}

Override DefCurrentresult (): boundeddouble = {
if(outputsmerged== totaloutputs) {//Complete
New
Boundeddouble (sum,1.0, Sum,sum)
}else if(outputsmerged== 0) {//A task is not completed
New
Boundeddouble (0,0.0, double.negativeinfinity, double.positiveinfinity)
}Else{//Partially completed, calculates the normal distribution parameters of its theoretical totals
Val
p = outputsmerged.todouble/totaloutputs
Valmean = (sum+ 1-p)/P
ValVariance = (sum+ 1) * (1-P)/(p * p)
ValStdev = math.sqrt (Variance)
ValConffactor =NewNormaldistribution ().
Inversecumulativeprobability (1-(1-confidence)/2)
ValLow = Mean-conffactor * Stdev
ValHigh = mean + Conffactor * Stdev
NewBoundeddouble (mean, confidence, low, high)
}
}

}

Therefore, the calculation process of the Countapprox is as follows: 1) The total number of Excutor end continuous calculation partition and then reported to the driver end, 2) the driver end to accept the total number of excutor reported to the statistics, if not all the report completed within the timeout period, then forced to quit, Returns a value whose total number conforms to the normal distribution, and returns an exact value if the calculation is completed within the time-out period.
6.countApproxDistinct

The function is to de-relativesd the content of the Rdd collection, which is an approximate statistic, and the parameters control the accuracy of the statistic. The smaller the RELATIVESD, the more accurate the result.

/**
* 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" &GT;HERE&LT;/A&GT;.
*
*@param relativesdRelative accuracy. Smaller values create counters that require more space.
* It must be greater than 0.000017.
*/
defCountapproxdistinct (relativesd:double =0.05): Long = withscope {
Require (Relativesd > 0.000017,S "Accuracy ($Relativesd) must be greater than 0.000017 ")
Valp = Math.ceil (2.0* math.log (1.054/RELATIVESD)/Math.log (2)). ToInt
Countapproxdistinct (if(P < 4) 4ElseP, 0)
}

The use of the Hyperloglog in practice algorithm, the principle is more esoteric, interested can be delve into.

Object countapproxdistinct {

  def main (args:array[string]) {

  &nb Sp Val conf = new sparkconf (). Setappname ("Spark-demo"). Setmaster ("local")

    val sc = new Sparkcontext (conf)

   /**

     * Build a collection divided into 20 partition

     */

    val A = sc.parallelize (1 to 10000)

   // RDD a content is copied 5 times, with 50,000 elements

    val B = a++a++a++a++a

   //The result is 9760, no arguments are passed, Default is 0.05

    println (b.countapproxdistinct ())

   //result is 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: _*)

}

Get all the data for the RDD and then cache it on the driver side with the following flow:


If the amount of RDD data is large, use it sparingly, because all the amount of data for that RDD will be cached.


8.toLocalIterator

Returns an iterator that protects all records

/**
 * Return An iterator it contains all of the elements in this RDD.
 *
 * The iterator would 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.
&NBSP;*/
def tolocaliterator:iterator[t] = withscope {

//trigger once for each partition action
  def collectpartition (P:int): array[t] = {
    sc.runjob ( this , (iter:iterator[ T] = = Iter.toarray, Seq (p), allowlocal = false ). Head
 }

// Call FlatMap to assemble all records to return a single iterator
  (0 until Partitions.length). Iterator.flatmap (i = collectpartition ( i)

}

That

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

The takeordered function is used to return the first num elements from the RDD, either by default (ascending) or by specifying a collation.

def takeordered (num:int) (implicitord:ordering[t]): array[t] = withscope {
if (num = = 0) {
Array.empty
} Else {
val maprdds = mappartitions {items =

Sort on the Excutor side first, and convert to the first NUM priority queue according to the Ord sort rule
Priority keeps the largest elements and 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 {

Transfer the computed results of a partition to a driver, convert to an array, and sort the previous num entries
Maprdds.reduce {(queue1, queue2) =
Queue1 ++= queue2
Queue1
}.toarray.sorted (ORD)
}
}

}

For example:

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);
}

Print

1

2

The execution process is as follows:



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.