티스토리 뷰
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 (Scala, Java, Python, R) and pair RDD functions doc (Scala, Java) for details.
Actions
The following table lists some of the common actions supported by Spark. Refer to the RDD API doc (Scala, Java, Python, R)
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. |
'BigData > Spark' 카테고리의 다른 글
mapValues/reduceByKey 예시 (0) | 2017.03.29 |
---|---|
데이터 스트리밍 개념 (0) | 2017.03.28 |
Spark 기본 개념 및 정리 (RDD) (0) | 2017.03.28 |
댓글
공지사항
최근에 올라온 글
링크
TAG
- 머신러닝
- Docker
- AWS
- Java
- TDD
- mybatis
- AI
- Gradle
- web
- 점프투파이썬
- spring
- javascript
- mysql
- API
- spark
- tensorflow
- 파이썬
- BigData
- Configuration
- Maven
- serverless
- memory
- 중앙정보처리학원
- ML
- Error
- 모두의딥러닝
- python
- executor
- 텐서플로우
- NIO
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함