spark-rdd

rdd Resilient Distributed DataSets 容錯的 并行的數(shù)據(jù)結(jié)果

transform 和 action 算子

https://blog.csdn.net/zzh118/article/details/52048521

transfrom操作:
  • parallelize, mkRDD:
  sc.makeRDD(Array((1,"A"),(2,"B"),(3,"C"),(4,"D")),2) 
  • map
  • flatMap
  • flatMapValues:
    def flatMapValues[U](f: V => TraversableOnce[U]): RDD[(K, U)]
  • filter
  • mapValues:
    def mapValues[U](f: V => U): RDD[(K, U)]
  • distinct(numPartitions: Int) numPartitions 可缺省
  • glom:
    將每個分區(qū)中的元素轉(zhuǎn)換成Array,這樣每個分區(qū)就只有一個數(shù)組元素派任,最終返回一個RDD def glom(): RDD[Array[T]]
  • groupByKey:
    返回 (K, Seq[V])的RDD
  • reduceByKey:
    (_ + _)
  • combineByKey
    使用用戶設(shè)置好的聚合函數(shù)對每個key中得value進(jìn)行組合(combine),可以將輸入類型為RDD[(k, v)]轉(zhuǎn)成RDD[(k, c)]粪摘。
  • sortByKey()
  • sortBy()
def sortBy[K](
      f: (T) => K,
      ascending: Boolean = true,
      numPartitions: Int = this.partitions.length)
      (implicit ord: Ordering[K], ctag: ClassTag[K]): RDD[T] = withScope {
    this.keyBy[K](f)
        .sortByKey(ascending, numPartitions)
        .values
  }

def sortByKey(ascending: Boolean = true, numPartitions: Int = self.partitions.length)
      : RDD[(K, V)] = self.withScope
  {
    val part = new RangePartitioner(numPartitions, self, ascending)
    new ShuffledRDD[K, V, V](self, part)
      .setKeyOrdering(if (ascending) ordering else ordering.reverse)
  }

val rdd = spark.sparkContext.makeRDD(1 to 10 zip (11 to 20))
val f = (x: (Int,Int)) => x._1%3
rdd.sortBy(f, false, 2)
rdd.sortBy
rdd.sortByKey(false, 2)
  • zip ()

  • zipWithUniqueId()

  • zipWithIndex()

  • zipPartitions()

  • cogroup
    相當(dāng)于SQL中的全外關(guān)聯(lián)full outer join熏纯,返回左右RDD中的記錄,關(guān)聯(lián)不上的為空。

  • join, leftOuterJoin唐瀑、rightOuterJoin操作.

  • sample:

def sample(
      withReplacement: Boolean,  // 是否有放回采樣团南,可以做降采樣或者升采樣
      fraction: Double,
      seed: Long = Utils.random.nextLong)
  • cartesian 笛卡兒積
    def cartesian[U: ClassTag](other: RDD[U]): RDD[(T, U)]
  • union噪沙,++操作 并集
  • subtract 差集
  • intersection 交集
  • groupByKey: def groupByKey(): RDD[(K, Iterable[V])]
  • partitionBy: 重新分區(qū)
action操作: 輸出結(jié)果非RDD, 將觸發(fā)依賴的transform操作
  • reduce
  • collect
  • count
  • first
  • take
  • takeSample(withReplacecment, num, seed) 返回數(shù)組
  • countBykey() : 返回Map(K, Int)
  • foreach
  • foreachPartition
  • saveAsTextFile
  • saveAsSequenceFile
  • flod:
    折疊(fold)操作和reduce(歸約)操作比較類似吐根。fold操作需要從一個初始的“種子”值開始正歼,并以該值作為上下文,處理集合中的每個元素拷橘。
rdd.map(_._1).fold(0)(_ + _)
  • aggregate
    def aggregate[U: ClassTag](zeroValue: U)(seqOp: (U, T) => U, combOp: (U, U) => U):

官網(wǎng)給的列表:

Transformations

The following table lists some of the common transformations supported by Spark. Refer to the RDD API doc (Scala, Java, Python, R) and pair RDD functions doc (Scala, Java) for details.

Transformation Meaning
map(func) Return a new distributed dataset formed by passing each element of the source through a function func.
filter(func) Return a new dataset formed by selecting those elements of the source on which funcreturns true.
flatMap(func) Similar to map, but each input item can be mapped to 0 or more output items (so funcshould return a Seq rather than a single item).
mapPartitions(func) Similar to map, but runs separately on each partition (block) of the RDD, so func must be of type Iterator<T> => Iterator<U> when running on an RDD of type T.
mapPartitionsWithIndex(func) Similar to mapPartitions, but also provides func with an integer value representing the index of the partition, so func must be of type (Int, Iterator<T>) => Iterator<U> when running on an RDD of type T.
sample(withReplacement, fraction, seed) Sample a fraction fraction of the data, with or without replacement, using a given random number generator seed.
union(otherDataset) Return a new dataset that contains the union of the elements in the source dataset and the argument.
intersection(otherDataset) Return a new RDD that contains the intersection of elements in the source dataset and the argument.
distinct([numPartitions])) Return a new dataset that contains the distinct elements of the source dataset.
groupByKey([numPartitions]) When called on a dataset of (K, V) pairs, returns a dataset of (K, Iterable<V>) pairs.

Note: If you are grouping in order to perform an aggregation (such as a sum or average) over each key, using reduceByKey or aggregateByKey will yield much better performance.
這里也提到了局义, 用reduceByKey和aggregateByKey而非groupByKey, 減少shuffle冗疮, 數(shù)據(jù)傾斜的處理中也可以作為一個兩步聚合的方案
Note: By default, the level of parallelism in the output depends on the number of partitions of the parent RDD. You can pass an optional numPartitions argument to set a different number of tasks. |
| reduceByKey(func, [numPartitions]) | When called on a dataset of (K, V) pairs, returns a dataset of (K, V) pairs where the values for each key are aggregated using the given reduce function func, which must be of type (V,V) => V. Like in groupByKey, the number of reduce tasks is configurable through an optional second argument. |
| aggregateByKey(zeroValue)(seqOp, combOp, [numPartitions]) | When called on a dataset of (K, V) pairs, returns a dataset of (K, U) pairs where the values for each key are aggregated using the given combine functions and a neutral "zero" value. Allows an aggregated value type that is different than the input value type, while avoiding unnecessary allocations. Like in groupByKey, the number of reduce tasks is configurable through an optional second argument. |
| sortByKey([ascending], [numPartitions]) | When called on a dataset of (K, V) pairs where K implements Ordered, returns a dataset of (K, V) pairs sorted by keys in ascending or descending order, as specified in the boolean ascending argument. |
| join(otherDataset, [numPartitions]) | When called on datasets of type (K, V) and (K, W), returns a dataset of (K, (V, W)) pairs with all pairs of elements for each key. Outer joins are supported through leftOuterJoin, rightOuterJoin, and fullOuterJoin. |
| cogroup(otherDataset, [numPartitions]) | When called on datasets of type (K, V) and (K, W), returns a dataset of (K, (Iterable<V>, Iterable<W>)) tuples. This operation is also called groupWith. |
| cartesian(otherDataset) | When called on datasets of types T and U, returns a dataset of (T, U) pairs (all pairs of elements). |
| pipe(command, [envVars]) | Pipe each partition of the RDD through a shell command, e.g. a Perl or bash script. RDD elements are written to the process's stdin and lines output to its stdout are returned as an RDD of strings. |
| coalesce(numPartitions) | Decrease the number of partitions in the RDD to numPartitions. Useful for running operations more efficiently after filtering down a large dataset. |
| repartition(numPartitions) | Reshuffle the data in the RDD randomly to create either more or fewer partitions and balance it across them. This always shuffles all data over the network. |
| repartitionAndSortWithinPartitions(partitioner) | Repartition the RDD according to the given partitioner and, within each resulting partition, sort records by their keys. This is more efficient than calling repartition and then sorting within each partition because it can push the sorting down into the shuffle machinery. |
上面這些都是會導(dǎo)致重新分區(qū)的操作萄唇, 即寬依賴, 是stage的分割點术幔, 帶來shuffle

Actions

The following table lists some of the common actions supported by Spark. Refer to the RDD API doc (Scala, Java, Python, R)

and pair RDD functions doc (Scala, Java) for details.

Action Meaning
reduce(func) Aggregate the elements of the dataset using a function func (which takes two arguments and returns one). The function should be commutative and associative so that it can be computed correctly in parallel.
collect() Return all the elements of the dataset as an array at the driver program. This is usually useful after a filter or other operation that returns a sufficiently small subset of the data.
count() Return the number of elements in the dataset.
first() Return the first element of the dataset (similar to take(1)).
take(n) Return an array with the first n elements of the dataset.
takeSample(withReplacement, num, [seed]) Return an array with a random sample of num elements of the dataset, with or without replacement, optionally pre-specifying a random number generator seed.
takeOrdered(n, [ordering]) Return the first n elements of the RDD using either their natural order or a custom comparator.
saveAsTextFile(path) Write the elements of the dataset as a text file (or set of text files) in a given directory in the local filesystem, HDFS or any other Hadoop-supported file system. Spark will call toString on each element to convert it to a line of text in the file.
saveAsSequenceFile(path)
(Java and Scala) Write the elements of the dataset as a Hadoop SequenceFile in a given path in the local filesystem, HDFS or any other Hadoop-supported file system. This is available on RDDs of key-value pairs that implement Hadoop's Writable interface. In Scala, it is also available on types that are implicitly convertible to Writable (Spark includes conversions for basic types like Int, Double, String, etc).
saveAsObjectFile(path)
(Java and Scala) Write the elements of the dataset in a simple format using Java serialization, which can then be loaded usingSparkContext.objectFile().
countByKey() Only available on RDDs of type (K, V). Returns a hashmap of (K, Int) pairs with the count of each key.
foreach(func) Run a function func on each element of the dataset. This is usually done for side effects such as updating an Accumulator or interacting with external storage systems.

Note: modifying variables other than Accumulators outside of the foreach() may result in undefined behavior. See Understanding closures for more details.
這個編程中要注意: 即使foreach另萤, 對于其中的變量也要用累加器Accumulators(map類操作就不用講了)

The Spark RDD API also exposes asynchronous versions of some actions, like foreachAsync for foreach, which immediately return a FutureAction to the caller instead of blocking on completion of the action. This can be used to manage or wait for the asynchronous execution of the action.

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市诅挑,隨后出現(xiàn)的幾起案子四敞,更是在濱河造成了極大的恐慌,老刑警劉巖拔妥,帶你破解...
    沈念sama閱讀 222,681評論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件忿危,死亡現(xiàn)場離奇詭異,居然都是意外死亡没龙,警方通過查閱死者的電腦和手機铺厨,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,205評論 3 399
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來兜畸,“玉大人努释,你說我怎么就攤上這事∫б。” “怎么了伐蒂?”我有些...
    開封第一講書人閱讀 169,421評論 0 362
  • 文/不壞的土叔 我叫張陵,是天一觀的道長肛鹏。 經(jīng)常有香客問我逸邦,道長恩沛,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 60,114評論 1 300
  • 正文 為了忘掉前任缕减,我火速辦了婚禮雷客,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘桥狡。我一直安慰自己搅裙,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 69,116評論 6 398
  • 文/花漫 我一把揭開白布裹芝。 她就那樣靜靜地躺著部逮,像睡著了一般。 火紅的嫁衣襯著肌膚如雪嫂易。 梳的紋絲不亂的頭發(fā)上兄朋,一...
    開封第一講書人閱讀 52,713評論 1 312
  • 那天,我揣著相機與錄音怜械,去河邊找鬼颅和。 笑死,一個胖子當(dāng)著我的面吹牛缕允,可吹牛的內(nèi)容都是我干的峡扩。 我是一名探鬼主播,決...
    沈念sama閱讀 41,170評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼灼芭,長吁一口氣:“原來是場噩夢啊……” “哼有额!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起彼绷,我...
    開封第一講書人閱讀 40,116評論 0 277
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎茴迁,沒想到半個月后寄悯,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,651評論 1 320
  • 正文 獨居荒郊野嶺守林人離奇死亡堕义,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,714評論 3 342
  • 正文 我和宋清朗相戀三年猜旬,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片倦卖。...
    茶點故事閱讀 40,865評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡洒擦,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出怕膛,到底是詐尸還是另有隱情熟嫩,我是刑警寧澤,帶...
    沈念sama閱讀 36,527評論 5 351
  • 正文 年R本政府宣布褐捻,位于F島的核電站掸茅,受9級特大地震影響椅邓,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜昧狮,卻給世界環(huán)境...
    茶點故事閱讀 42,211評論 3 336
  • 文/蒙蒙 一景馁、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧逗鸣,春花似錦合住、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,699評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至沪悲,卻和暖如春获洲,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背殿如。 一陣腳步聲響...
    開封第一講書人閱讀 33,814評論 1 274
  • 我被黑心中介騙來泰國打工贡珊, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人涉馁。 一個月前我還...
    沈念sama閱讀 49,299評論 3 379
  • 正文 我出身青樓门岔,卻偏偏與公主長得像,于是被迫代替她去往敵國和親烤送。 傳聞我的和親對象是個殘疾皇子寒随,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,870評論 2 361

推薦閱讀更多精彩內(nèi)容

  • 文丨加林仙人 01 離春節(jié)越來越近试和,朋友圈里的每個人讯泣,除了曬出熱鬧非凡的年會、收獲頗豐的年終獎阅悍,曬出最多的好渠,便是翹...
    加琳寫作閱讀 443評論 0 2
  • 讓我想起了魯迅的《示眾》,中國人的看客精神是刻在骨子里的节视,而現(xiàn)在看與被看的關(guān)系只是隔了一層手機屏幕拳锚,熱情而愛憎分明...
    雅米yamy閱讀 466評論 0 0
  • 《送別》中,聽著小天使們的歌聲寻行,再瞧瞧這歌詞寫的呀霍掺,一直覺得能寫出這首歌的,一定是個奇才。 三言兩語抗楔,道出世事無奈...
    公主搓澡么閱讀 236評論 0 0
  • 終于有勇氣來回憶心中那段沉痛的時光棋凳。今年,距離父親去世整整七年连躏。我從17歲成長到24歲剩岳。我終于長大了。從一個...
    雨涵清柳閱讀 175評論 5 2