1. 程式人生 > 其它 >大資料學習(26)—— Spark之RDD

大資料學習(26)—— Spark之RDD

做大資料一定要有一個概念,需要處理的資料量非常大,少則幾十T,多則上百P,全部放記憶體是不可能的,會OOM,必須要用迭代器一條一條處理。

RDD叫做彈性分散式資料集,是早期Spark最核心的概念,是一種資料集合,它的核心就是迭代器。

建立方式

有兩種建立RDD的方式:

  • 在驅動程式中並行化現有集合
  • 引用外部儲存系統中的資料集

示例1:並行化集合

    val rdd = sc.parallelize(Array(1,2,3,2,3,2,5))

示例2:引用外部檔案

    val file = sc.textFile("hdfs://mycluster/data.txt")
    val rdd 
= file.flatMap(s => s.split(" "))

RDD操作

RDD 支援兩種型別的操作:

  • transformations,轉換操作,從現有的資料集建立一個新的資料集。
  • actions,執行操作,對資料集執行計算後返回一個值給驅動程式。

Spark 中的所有轉換都是惰性的,因為它們不會立即計算結果。相反,他們只記住應用於某些基本資料集(例如檔案)的轉換。僅當操作需要將結果返回到驅動程式時才計算轉換。這種設計使 Spark 能夠更高效地執行。

轉換操作

常用的轉換操作如下表。很多轉換操作傳入的都是一個函式,這是Scala的語法,可以理解為Java的Lambda表示式。用多了就習慣了。

TransformationMeaning
map(func) Return a new distributed dataset formed by passing each element of the source through a functionfunc.
filter(func) Return a new dataset formed by selecting those elements of the source on whichfuncreturns true.
flatMap(func) Similar to map, but each input item can be mapped to 0 or more output items (sofunc
should return a Seq rather than a single item).
mapPartitions(func) Similar to map, but runs separately on each partition (block) of the RDD, sofuncmust be of type Iterator<T> => Iterator<U> when running on an RDD of type T.
mapPartitionsWithIndex(func) Similar to mapPartitions, but also providesfuncwith an integer value representing the index of the partition, sofuncmust be of type (Int, Iterator<T>) => Iterator<U> when running on an RDD of type T.
sample(withReplacement,fraction,seed) Sample a fractionfractionof 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, usingreduceByKeyoraggregateByKeywill yield much better performance.
Note:By default, the level of parallelism in the output depends on the number of partitions of the parent RDD. You can pass an optionalnumPartitionsargument 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 functionfunc, which must be of type (V,V) => V. Like ingroupByKey, 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 ingroupByKey, 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 booleanascendingargument.
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 throughleftOuterJoin,rightOuterJoin, andfullOuterJoin.
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 calledgroupWith.
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 callingrepartitionand then sorting within each partition because it can push the sorting down into the shuffle machinery.

執行操作

執行操作觸發計算,返回結果。沒有執行操作的RDD不會生成Job,沒有實際意義。

ActionMeaning
reduce(func) Aggregate the elements of the dataset using a functionfunc(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 firstnelements of the dataset.
takeSample(withReplacement,num, [seed]) Return an array with a random sample ofnumelements of the dataset, with or without replacement, optionally pre-specifying a random number generator seed.
takeOrdered(n,[ordering]) Return the firstnelements 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 functionfuncon each element of the dataset. This is usually done for side effects such as updating anAccumulatoror interacting with external storage systems.
Note: modifying variables other than Accumulators outside of theforeach()may result in undefined behavior.

洗牌

shuffle (洗牌)是 Spark 重新分配資料的機制。我們在學習MapReduce的時候,在reduce階段,資料就是根據key值通過shuffle操作到達不同的分割槽。這個操作涉及到資料複製,代價很高。應通過合理的API呼叫或者調優,儘量避免發生shuffle。

在程式本地執行時,4040埠可以檢視DAG,從圖中能看出是否有shuffle發生。

上圖對應的程式碼如下

    val conf = new SparkConf().setAppName("Test").setMaster("local")
    val sc = new SparkContext(conf)
    sc.setLogLevel("ERROR")
    val rdd = sc.parallelize(Array(1,2,3,2,1,4,5,2))
    val kv = rdd.map(x=>(x,1)).reduceByKey(_+_)
    kv.foreach(println)

在呼叫reduceByKey時,作業產生了新的Stage1,這個過程就發生了shuffle,把相同key值的資料重新分割槽,計算出結果。

效能影響

發生shuffle時,它涉及到磁碟I/O,資料序列化和網路I/O,因此代價非常高。部分shuffle操作會用到相當多的堆記憶體,因為它在傳輸資料的過程中,會用到記憶體資料結構來組織資料。其中,reduceByKey和aggregateByKey這兩個運算元是在資料對映端建立記憶體資料結構,其他的byKey操作是在歸約端建立。如果資料不適合放在記憶體裡,Spark會將其溢寫到磁碟上,從而導致額外的磁碟I/O開銷和垃圾回收。

Shuffle還會在磁碟上生成大量中間檔案。從 Spark 1.3 開始,這些臨時檔案會一直保留,直到相應的 RDD 不再使用並被垃圾回收。這樣做是為了在重新計算血統時不需要重新建立 shuffle 檔案。如果應用程式保留對這些 RDD 的引用或者 GC 不頻繁啟動,那長時間執行的 Spark 作業可能會消耗大量磁碟空間。

其他

Spark支援把資料持久化在記憶體中或者磁碟上,在效能調優的時候根據不同場景做出選擇,這裡不再贅述。