티스토리 뷰


Transformation 함수
scala> val rdd1 = sc.parallelize(List("coffee","coffee","tea","milk"))
rdd1: org.apache.spark.rdd.RDD[String] = ParallelCollectionRDD[9] at parallelize at <console>:27

scala> val rdd2 = sc.parallelize(List("coffee","cola","water"))
rdd2: org.apache.spark.rdd.RDD[String] = ParallelCollectionRDD[10] at parallelize at <console>:27

intersection() 두개 이상의 RDD 데이터 교집합 RDD 반환 [Transformation 함수shuffling
scala> rdd1.intersection(rdd2).foreach(println)
coffee

subtract() 첫번째 RDD 항목들 중 두 번째 RDD 항목 제외한 RDD 반환 [Transformation 함수]
scala> rdd1.subtract(rdd2).foreach(println)
milk
tea

cartesian()  카테시안 곱 계산 [Transformation 함수] shuffling
scala> rdd1.cartesian(rdd2).foreach(println)
(coffee,coffee)
(coffee,cola)
(coffee,water)
(coffee,coffee)
(coffee,cola)
(coffee,water)
(tea,coffee)
(tea,cola)
(tea,water)
(milk,coffee)
(milk,cola)
(milk,water)

sample(withReplacement,fraction,[seed]) 복원 추출/비복원 추출로 표본 뽑아냄 [Transformation 함수]
scala> rdd1.sample(false,0.5).foreach(println)
coffee
tea
milk



scala> val pairs1 = lines.flatMap(x=>x.split(" ")).map(word=>(word,1)).take(10)
pairs1: Array[(String, Int)] = Array((holden,1), (likes,1), (coffee,1), (panda,1), (likes,1), (long,1), (strings,1), (and,1), (coffee,1))

mapValues() 각 value에 count를 위한 1을 붙이고 [Transformation 함수]
reduceByKey() key별 (value의 총합, 값 갯수) [Transformation 함수]
scala> pairs1.mapValues(x=>(x,1)).reduceByKey((x,y)=>(x._1+y._1,x._2+y._2)).take(6)
res126: Array[(String, (Int, Int))] = Array((long,(1,1)), (coffee,(2,2)), (holden,(1,1)), (likes,(2,2)), (panda,(1,1)), (strings,(1,1)))

combineByKey() key별 집합 연산 일반적으로 사용 -> map-side 집합연산
한 파티션 내의 데이터들을 하나씩 처리. 각 데이터는 이전에 나온 적이 없는 키를 갖고 있거나 이전에 나온 적이 있는 키
새로운 데이터 경우 createCombiner()함수로 해당 키에 대한 accumulator 생성.
이전에 나온 키의 경우 mergeValue()함수로 합함.
파티션별 계산이 끝나고 RDD전체에서 최종적으로 결과를 합칠 때 동일 키에 대한 accummulator를 가지면 mergeCombiner()함수로 합함.
//예제 -> input이 없음. 함수 인자들만 참고
scala> val result = input.combineByKey((v)=>(v,1),(acc:(Int,Int),v)=>(acc._1+v,acc._2+1),(acc1:(Int,Int),acc2:(Int,Int))=>(acc1._1+acc2._1,acc1._2+acc2._2)).map{case(key,value)=>(key,vlaue._1/value._2.toFloat)}

병렬화 수준지정. 스파크에 특정 개수의 파티션을 사용하라고 요청
val data = Seq(("a",3),("b",4),("a",1))
sc.parallelize(data).reduceByKey((x,y)=>x+y).take(2)
sc.parallelize(data).reduceByKey((x,y)=>x+y,10).take(2)


Actions 함수
scala> val data = sc.parallelize(List(1,2,3,3))
data: org.apache.spark.rdd.RDD[Int] = ParallelCollectionRDD[29] at parallelize at <console>:27

countByValue() RDD에 있는 각 값의 개수 리턴 [Actions 함수]
scala> data.countByValue()
res22: scala.collection.Map[Int,Long] = Map(1 -> 1, 3 -> 2, 2 -> 1)

takeSample(withReplacement,n,[seed]) 복원/비복원 추출로 n개 표본 뽑아냄 [Actions 함수]
scala> data.takeSample(false,1).take(1).foreach(println)
3

aggregate(zeroValue) reduce와 유사하나 다른 타입 리턴, 아래 예제에서는 (총합,갯수)로 리턴 [Actions 함수]
scala> data.aggregate((0,0))((x,y)=>(x._1+y,x._2+1),(x,y)=>(x._1+y._1,x._2+y._2))
res32: (Int, Int) = (9,4)

persist() 영속화, 데이터를 JVM 힙heap 영역에 객체 형태로 저장함 [캐싱 함수]
scala> val input = sc.parallelize(List(1,2,3,4,5))
input: org.apache.spark.rdd.RDD[Int] = ParallelCollectionRDD[38] at parallelize at <console>:27
scala> import org.apache.spark.storage.StorageLevel
import org.apache.spark.storage.StorageLevel
scala> val result = input.map(x=>x*x)
result: org.apache.spark.rdd.RDD[Int] = MapPartitionsRDD[39] at map at <console>:30
scala> result.persist(StorageLevel.DISK_ONLY)
res34: result.type = MapPartitionsRDD[39] at map at <console>:30
scala> println(result.count())
5
scala> println(result.collect().mkString(","))
1,4,9,16,25



--------------------------------------------------------------------------------------------------------------------------------------------------

Transformations

The following table lists some of the common transformations supported by Spark. Refer to the RDD API doc (ScalaJavaPythonR) and pair RDD functions doc (ScalaJava) for details.

TransformationMeaning
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 func returns true.
flatMap(func)Similar to map, but each input item can be mapped to 0 or more output items (so func should 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(withReplacementfractionseed)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([numTasks]))Return a new dataset that contains the distinct elements of the source dataset.
groupByKey([numTasks])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. 
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 numTasks argument to set a different number of tasks.
reduceByKey(func, [numTasks])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)(seqOpcombOp, [numTasks])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], [numTasks])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, [numTasks])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 leftOuterJoinrightOuterJoin, and fullOuterJoin.
cogroup(otherDataset, [numTasks])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.

Actions

The following table lists some of the common actions supported by Spark. Refer to the RDD API doc (ScalaJavaPythonR)

and pair RDD functions doc (ScalaJava) for details.

ActionMeaning
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(withReplacementnum, [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.




'BigData > Spark' 카테고리의 다른 글

mapValues/reduceByKey 예시  (0) 2017.03.29
데이터 스트리밍 개념  (0) 2017.03.28
Spark 기본 개념 및 정리 (RDD)  (0) 2017.03.28
댓글
공지사항
최근에 올라온 글
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함