溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

RDD編程

發(fā)布時間:2020-07-25 14:52:54 來源:網(wǎng)絡(luò) 閱讀:554 作者:maninglwj 欄目:大數(shù)據(jù)

1.RDD基礎(chǔ):

  Spark中RDD是不可變的分布式對象集合。每個RDD被分為多個分區(qū),這些分區(qū)運行在集群中的不同節(jié)點上。RDD可以包含任意類型的對象(甚至可以是自定義的)。

 前面講到,Spark包含轉(zhuǎn)化操作和行動操作。Spark只會惰性計算這些RDD。它們只有第一次在一個行動操作中用到時,才會真正計算。默認(rèn)情況下,Spark的RDD會在你每次對它們進(jìn)行行動操作時重新計算。如果想在多個行動操作中重用同一個RDD,可以使用RDD.persist()讓Spark把這個RDD緩存(內(nèi)存或者磁盤)下來。


2.創(chuàng)建RDD:

Spark提供2種創(chuàng)建方式:

(1)讀取外部數(shù)據(jù)集:之前的sc.textFile()就屬于這種類型。更加常用的方式。

(2)在驅(qū)動器程序中對一個集合(list、Set等)進(jìn)行并行化,要使用SparkContext.parallelize()方法。


3.RDD操作:

RDD主要分成數(shù)據(jù)類型RDD和鍵值對RDD。有一些操作可以適用于所有類型的RDD,這時候可以直接創(chuàng)建JavaRDD對象,例如map(),filter()等。有些操作只適用于數(shù)據(jù)類型的RDD,例如 ,這時候創(chuàng)建JavaDoubleRDD對象。有些操作只適用于鍵值對RDD,例如 ,這時候創(chuàng)建JavaPairRDD對象。

3.1 轉(zhuǎn)化操作:

3.1.1 譜系圖:

通過轉(zhuǎn)化操作,從已有的RDD中派生出新的RDD,Spark會使用譜系圖來記錄這些不同RDD之間的依賴關(guān)系。如下圖所示:

RDD編程


3.1.2 :

  1. 基本的轉(zhuǎn)化操作(map、flatMap、filter、distinct、sample),假設(shè)RDD的數(shù)據(jù){1, 2, 3, 3}:

  2. RDD的集合操作(union、intersection、subtract、cartesian),兩個RDD分別是{1,2,3}、{3,4,5}:

函數(shù)名作用例子運行結(jié)果
map()Apply a function to each element in the RDD and return an RDD of the result.rdd.map(x => x +1){2, 3, 4, 4}
flatMap()Apply a function to each element in the RDD and return an RDD of the contents of the iterators returned. Often used to extract words.rdd.flatMap(x =>x.to(3)){1, 2, 3, 2, 3, 3, 3}
filter()Return an RDD consisting of only elements that pass the condition passed to filter().rdd.filter(x => x!= 1){2, 3, 3}
distinct()Remove duplicates.rdd.distinct(){1, 2, 3}
sample(withReplacement,fraction, [seed])Sample an RDD, with or without replacement.rdd.sample(false,0.5)不確定
union()Produce an RDD containing elements from both RDDs.rdd.union(other){1, 2, 3, 3, 4, 5}
intersection()RDD containing only elements found in both RDDs.rdd.intersection(other){3}
subtract()Remove the contents of one RDD (e.g., remove training data).rdd.subtract(other){1, 2}
cartesian()Cartesian product with the other RDD.rdd.cartesian(other){(1, 3), (1, 4),… (3, 5)}



4.給Spark傳遞函數(shù):

大多數(shù)的轉(zhuǎn)化操作和一部分行動操作,都需要給Spark方法傳遞函數(shù)。在java中,函數(shù)式實現(xiàn)了包org.apache.spark.api.java.function下面任意一個接口的類。該包下面有許多接口,下面是一些基礎(chǔ)接口:

函數(shù)名需要實現(xiàn)的方法
用法
Function<T, R> R call(T)Take in one input and return one output, for use with operations like map()and filter(). 

Function2<T1, T2,R> 

R call(T1, T2)Take in two inputs and return one output, for use with operations like aggregate() or fold(). 
FlatMapFunction<T,R>Iterable<R> call(T) Take in one input and return zero or more outputs, for use with operations like flatMap().


向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI