一、RDD Operations
1.Transfoamation
(1)概述:就是一个RDD转换成为另外一个RDD (体现了RDD是不可变的)
Example:
map :RDDA map RDDB
(2)所有的transformation都是lazy(用到的时候才去加载,不用就不处理)的,所以他不会立刻去计算结果,他仅仅只是记住你的数据集transformation关系。
Example:
RDDa.map().filter().map().filter() 他会记住这些转换关系,像一个文件一样,但不会执行。
(3)只有出发Action时才会执行,这种lazy模式能使他更高效
Example:rdda.map().reduce() :他前面都不会执行,遇到reduce才执行,返回就一个结果,没有多余的数据集,节约资源,减小IO。
(4)常用的transformation:
flatmap和map的区别?
map返回的是每个的单个项,flatmap返回的是个Seq数组,类似于打扁操作。
(5)mapValues:这是一个仅仅指针对Value做操作的算子。
2.Action
(1)概述:返回一个数据集
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. |
takeSample和takeOrdered有什么区别?
takeSample:这个是随机取出n个元素,前面是个Boolean类型,表示是否替换。