📔
Data Science with Apache Spark
  • Preface
  • Contents
  • Basic Prerequisite Skills
  • Computer needed for this course
  • Spark Environment Setup
  • Dev environment setup, task list
  • JDK setup
  • Download and install Anaconda Python and create virtual environment with Python 3.6
  • Download and install Spark
  • Eclipse, the Scala IDE
  • Install findspark, add spylon-kernel for scala
  • ssh and scp client
  • Summary
  • Development environment on MacOS
  • Production Spark Environment Setup
  • VirtualBox VM
  • VirtualBox only shows 32bit on AMD CPU
  • Configure VirtualBox NAT as Network Adapter on Guest VM and Allow putty ssh Through Port Forwarding
  • Docker deployment of Spark Cluster
  • Create customized Apache Spark Docker container
  • Dockerfile
  • docker-compose and docker-compose.yml
  • Launch custom built Docker container with docker-compose
  • Entering Docker Container
  • Setup Hadoop, Hive and Spark on Linux without docker
  • Hadoop Preparation
  • Hadoop setup
  • Configure $HADOOP_HOME/etc/hadoop
  • HDFS
  • Start and stop Hadoop
  • Work with Hadoop and HDFS file system
  • Connect to Hadoop web interface port 50070 and 8088
  • Install Hive
  • hive home
  • Initialize hive schema
  • Start hive metastore service.
  • hive-site.xml
  • Hive client
  • Setup Apache Spark
  • Spark Home
  • Jupyter-notebook server
  • Python 3 Warm Up
  • Basics
  • Iterables/Collections
  • Strings
  • List
  • Tuple
  • Dictionary
  • Set
  • Conditional statement
  • for loop
  • while loop
  • Functions and methods
  • map and filter
  • map and filter takes function as input
  • lambda
  • Python Class
  • Input and if statement
  • Input from a file
  • Output to a file
  • try except
  • Python coding exercise
  • Scala Warm Up
  • Start Spylon-kernel on Jupyter-notebook
  • Type of Variable: Mutable or immutable
  • Block statement
  • Scala Data Type
  • Array in Scala
  • Methods
  • Functions
  • Anonymous function
  • Scala map and filter methods
  • Class
  • Objects
  • Trait
  • Tuple in Scala
  • List/Seq
  • Set in Scala
  • Scala Map
  • Scala if statement
  • Scala for loop
  • Scala While Loop
  • Scala Exceptions + try catch finally
  • Scala coding exercise
  • Run a program to estimate pi
  • Common Spark command line
  • Run Scala code with spark-submit
  • Python with Apache Spark using Jupyter notebook
  • Spark Core Introduction
  • Spark and Scala Version
  • Basic Spark Package
  • Resilient Distributed Datasets (RDDs)
  • RDD Operations
  • Passing Function to Spark
  • Printing elements of an RDD
  • Working with key value pair
  • RDD Transformation Functions
  • RDD Action Functions
  • SPARK SQL
  • SQL
  • Datasets and DataFrames
  • SparkSession
  • Creating DataFrames
  • Running SQL Queries Programmatically
  • Issue from running Cartesian Join Query
  • Creating Datasets
  • Interoperating with RDD
  • Untyped User-Defined Aggregate Functions
  • Generic Load/Save Functions
  • Manually specify file option
  • Run SQL on files directly
  • Save Mode
  • Saving to Persistent Tables
  • Bucketing, Sorting and Partitioning
  • Apache Arrow
  • Install Python Arrow Module PyArrow
  • Issue might happen import PyArrow
  • Enabling for Conversion to/from Pandas in Python
  • Connect to any data source the same consistent way
  • Spark SQL Implementation Example in Scala
  • Run scala code in Eclipse IDE
  • Hive Integration, run SQL or HiveQL queries on existing warehouses.
  • Example: Enrich JSON
  • Integrate Tableau Data Visualization with Hive Data Warehouse and Apache Spark SQL
  • Connect Tableau to Spark SQL running in VM with VirtualBox with NAT
  • Issues with connecting from Tableau to Spark SQL
  • SPARK Streaming
  • Discretized Streams (DStreams)
  • Transformations on DStreams
  • map(func)
  • filter(func)
  • repartition(numPartitions)
  • union(otherStream)
  • reduce(func)
  • count()
  • countByValue()
  • reduceByKey(func, [numTasks])
  • join(otherStream, [numTasks])
  • cogroup(otherStream, [numTasks])
  • transform(func)
  • updateStateByKey(func)
  • Scala Tips for updateStateByKey
  • repartition(numPartitions)
  • DStream Window Operations
  • DStream Window Transformation
  • countByWindow(windowLength, slideInterval)
  • reduceByWindow(func, windowLength, slideInterval)
  • reduceByKeyAndWindow(func, windowLength, slideInterval, [numTasks])
  • reduceByKeyAndWindow(func, invFunc, windowLength, slideInterval, [numTasks])
  • countByValueAndWindow(windowLength, slideInterval, [numTasks])
  • window(windowLength, slideInterval)
  • Window DStream print(n)
  • saveAsTextFiles(prefix, [suffix])
  • saveAsObjectFiles(prefix, [suffix])
  • saveAsHadoopFiles(prefix, [suffix])
  • foreachRDD(func)
  • Build Twitter Scala API Library for Spark Streaming using sbt
  • Spark Streaming with Twitter, you can get public tweets by using Twitter API.
  • Spark streaming use case with Python
  • Spark Graph Computing
  • Spark Graph Computing Continue
  • Graphx
  • Package org.apache.spark.graphx
  • Edge Class
  • EdgeContext Class
  • EdgeDirection Class
  • EdgeRDD Class
  • EdgeTriplet Class
  • Graph Class
  • GraphLoader Object
  • GraphOps Class
  • GraphXUtils Object
  • PartitionStrategy Trait
  • Pregel Object
  • TripletFields Class
  • VertexRDD Class
  • Package org.apache.spark.graphx.impl
  • AggregatingEdgeContext Class
  • EdgeRDDImpl Class
  • Class GraphImpl<VD,ED>
  • Class VertexRDDImpl<VD>
  • Package org.apache.spark.graphx.lib
  • Class ConnectedComponents
  • Class LabelPropagation
  • Class PageRank
  • Class ShortestPaths
  • Class StronglyConnectedComponents
  • Class SVDPlusPlus
  • Class SVDPlusPlus.Conf
  • Class TriangleCount
  • Package org.apache.spark.graphx.util
  • Class BytecodeUtils
  • Class GraphGenerators
  • Graphx Example 1
  • Graphx Example 2
  • Graphx Example 3
  • Spark Graphx Describes Organization Chart Easy and Fast
  • Page Rank with Apache Spark Graphx
  • bulk synchronous parallel with Google Pregel Graphx Implementation Use Cases
  • Tree and Graph Traversal with and without Spark Graphx
  • Graphx Graph Traversal with Pregel Explained
  • Spark Machine Learning
  • Binary Classification
  • Multiclass Classification
  • Regression
  • Correlation
  • Image Data Source
  • ML DataFrame is SQL DataFrame
  • ML Transformer
  • ML Estimator
  • ML Pipeline
  • Transformer/Estimator Parameters
  • Extracting, transforming and selecting features
  • TF-IDF
  • Word2Vec
  • FeatureHasher
  • Tokenizer
  • CountVectorizer
  • StopWordRemover
  • n-gram
  • Binarizer
  • PCA
  • PolynomialExpansion
  • StringIndexer
  • Discrete Cosine Transform (DCT)
  • One-hot encoding
  • StandardScaler
  • IndexToString
  • VectorIndexer
  • Interaction
  • Normalizer
  • MinMaxScaler
  • MaxAbScaler
  • Bucketizer
  • ElementwiseProduct
  • SQLTransformer
  • VectorAssembler
  • VectorSizeHint
  • QuantileDiscretizer
  • Imputer
  • VectorSlicer
  • RFormula
  • ChiSqSelector
  • Locality Sensitive Hashing
  • MinHash for Jaccard Distance
  • Classification and Regression
  • LogisticRegression
  • OneVsRest
  • Naive Bayes classifiers
  • Decision trees
  • Random forests
  • Gradient-boosted trees (GBTs)
  • Multilayer perceptron classifier
  • Linear Support Vector Machine
  • Linear Regression
  • Generalized linear regression
  • Isotonic regression
  • Decision Tree Regression
  • Random Forest Regression
  • Gradient-boosted tree regression
  • Survival regression
  • Clustering
  • k-means
  • Latent Dirichlet allocation or LDA
  • Bisecting k-means
  • A Gaussian Mixture Model
  • Collaborative filtering
  • Frequent Pattern Mining
  • FP-Growth
  • PrefixSpan
  • ML Tuning: model selection and hyperparameter tuning
  • Model selection (a.k.a. hyperparameter tuning)
  • Cross-Validation
  • Train-Validation Split
  • Spark Machine Learning Applications
  • Apache Spark SQL & Machine Learning on Genetic Variant Classifications
  • Data Visualization with Vegas Viz and Scala with Spark ML
  • Apache Spark Machine Learning with Dremio Data Lake Engine
  • Dremio Data Lake Engine Apache Arrow Flight Connector with Spark Machine Learning
  • Neural Network with Apache Spark Machine Learning Multilayer Perceptron Classifier
  • Setup TensorFlow, Keras, Theano, Pytorch/torchvision on the CentOS VM
  • Virus Xray Image Classification with Tensorflow Keras Python and Apache Spark Scala
  • Appendix -- Video Presentations
  • References
Powered by GitBook
On this page

Was this helpful?

RDD Transformation Functions

Use syntax:

<RDD Variable>.<transformation function>(func)

map(func)

Return a new distributed dataset formed by passing each element of the source through a function func.

val rdd=sc.parallelize(List(1,2,3,4,5))
rdd.map(x=>x+1).collect.foreach(println)
/*
2
3
4
5
6
*/

filter(func)

Return a new dataset formed by selecting those elements of the source on which func returns true.

val rdd=sc.parallelize(List(1,2,3,4,5))
rdd.filter(x=>x%2==0).collect.foreach(println)
/*
2
4
*/

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).

val rdd=sc.parallelize(List("1 2","3 4","5 6"))
rdd.collect.foreach(println)
/*
1 2
3 4
5 6
*/
rdd.flatMap(x=>x.split(' ')).collect.foreach(println)
/*
1
2
3
4
5
6
*/

mapPartitions(func)

Similar to map, but runs separately on each partition (block) of the RDD, so func must be of type Iterator => Iterator when running on an RDD of type T. (Note: T is datatype placeholder, can be Int, String, etc)

val rdd = sc.parallelize(List(1,2,3,4,5,6),2)
val rdd2= rdd.mapPartitions( (i: Iterator[Int]) => 
    i.toList.toIterator)

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) => Iterator when running on an RDD of type T.

val rdd = sc.parallelize(Seq(1,2,3,4,5),3)
rdd.mapPartitionsWithIndex( 
    (index: Int, i: Iterator[Int]) => i.toList
    .map(x => index + ", "+x).iterator)
   .collect.foreach(println)
/*
0, 1
1, 2
1, 3
2, 4
2, 5
*/

sample(withReplacement, fraction, seed)

Sample a fraction of the data, with or without replacement, using a given random number generator seed.

withReplacement, Boolean argument, true or false. If true, same element can appear in the sample output; if false, same element can not appear in the sample output.

val rdd = sc.parallelize(Seq(1,2,3,4,5))
rdd.sample(true,0.7,1).collect.foreach(println)
/*
1
1
2
*/

union(otherDataset)

Return a new dataset that contains the union of the elements in the source dataset and the argument.

val rdd = sc.parallelize(Seq(1,2,3,4,5))
rdd.union(sc.parallelize(Seq(10,11,12,13,14)))
    .collect.foreach(println)
    
/*
1
2
3
4
5
10
11
12
13
14
*/

intersection(otherDataset)

Return a new RDD that contains the intersection of elements in the source dataset and the argument.

sc.parallelize(Seq(1,2,3,4,5))
   .intersection(sc.parallelize(Seq(10,11,3,4,15)))
   .collect.foreach(println)

/*
4
3
*/

distinct([numPartitions]))

Return a new dataset that contains the distinct elements of the source dataset.

sc.parallelize(Seq(1,2,3,4,5,5,6,5,5,4,3))
 .distinct.collect
   .foreach(println)
   
/*
4
6
2
1
3
5
*/

groupByKey([numPartitions])

When called on a dataset of (K, V) pairs, returns a dataset of (K, Iterable) 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 numPartitions argument to set a different number of tasks.

sc.parallelize(Seq(1,2,3,4,5,5,6,5,5,4,3))
  .map(x=>(x,1))
  .groupByKey
  .collect.foreach(print)

/*
(4,CompactBuffer(1, 1))(6,CompactBuffer(1))(2,CompactBuffer(1))(1,CompactBuffer(1))(3,CompactBuffer(1, 1))(5,CompactBuffer(1, 1, 1, 1))
*/

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 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.

sc.parallelize(Seq(1,2,3,4,5,5,6,5,5,4,3))
   .map(x=>(x,1)).reduceByKey((a,b)=>a+b)
   .collect.foreach(println)
   
//or

sc.parallelize(Seq(1,2,3,4,5,5,6,5,5,4,3))
   .map(x=>(x,1)).reduceByKey(_+_)
   .collect.foreach(println)

/*
(4,2)
(6,1)
(2,1)
(1,1)
(3,2)
(5,4)
*/

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.

As you can see, it takes 4 arguments:

1st argument if 0, it is aggregation for sum; if Double.MaxValue, it is aggregation for minimum; if Double.MinValue, it is aggregation for maximum.

2nd argument is reduce operation within partition

3rd argument is comnining reduce operation across partitions

4th argument is optional, limit to number of Partitions

sc.parallelize(Seq(1,2,3,4,5,5,6,5,5,4,3))
   .map(x=>(x,1)).aggregateByKey(0)((a,b)=>a+b,(c,d)=>c+d)
   .collect.foreach(println)
   
//or

sc.parallelize(Seq(1,2,3,4,5,5,6,5,5,4,3))
   .map(x=>(x,1)).aggregateByKey(0)(_+_,_+_)
   .collect.foreach(println)
   
/*
(4,2)
(6,1)
(2,1)
(1,1)
(3,2)
(5,4)
*/

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 through leftOuterJoin, rightOuterJoin, and fullOuterJoin.

val emp = sc.parallelize(Seq(("david",10), ("jack",20)
                 ,("mary",30)))
val dept = sc.parallelize(Seq(("hr",10) 
        , ("accounting",20), ("sales",30)))
val emp_dept = emp.map(t => (t._2, t._1))
val dept_dept = dept.map(t => (t._2,t._1))

emp_dept.join(dept_dept).collect.foreach(println)

/*
(30,(mary,sales))
(20,(jack,accounting))
(10,(david,hr))
*/

emp_dept.fullOuterJoin(dept_dept).collect.foreach(println)
/*
(30,(Some(mary),Some(sales)))
(20,(Some(jack),Some(accounting)))
(10,(Some(david),Some(hr)))
*/

emp_dept.leftOuterJoin(dept_dept).collect.foreach(println)

/*
(30,(mary,Some(sales)))
(20,(jack,Some(accounting)))
(10,(david,Some(hr)))
*/

emp_dept.rightOuterJoin(dept_dept).collect.foreach(println)
/*
(30,(Some(mary),sales))
(20,(Some(jack),accounting))
(10,(Some(david),hr))
*/

cogroup(otherDataset, [numPartitions])

When called on datasets of type (K, V) and (K, W), returns a dataset of (K, (Iterable, Iterable)) tuples. This operation is also called groupWith.

val emp = sc.parallelize(Seq(("david",10)
   , ("jack",20), ("mary",30)))
val dept = sc.parallelize(Seq(("hr",10)
   , ("accounting",20), ("sales",30)))
val emp_dept = emp.map(t => (t._2, t._1))
val dept_dept = dept.map(t => (t._2,t._1))
emp_dept.cogroup(dept_dept)
   .collect.foreach(println)
/*
(30,(CompactBuffer(mary),CompactBuffer(sales)))
(20,(CompactBuffer(jack),CompactBuffer(accounting)))
(10,(CompactBuffer(david),CompactBuffer(hr)))
*/

cartesian(otherDataset)

When called on datasets of types T and U, returns a dataset of (T, U) pairs (all pairs of elements).

sc.parallelize(Seq(1,2,3))
   .cartesian(sc.parallelize(Seq(6,7)))
   .collect.foreach(println)

/*
(1,6)
(1,7)
(2,6)
(3,6)
(2,7)
(3,7)
*/

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.

sc.parallelize(Seq(1,2,3)).pipe("more")
.foreach(println)

/*
2
3
1
*/

coalesce(numPartitions)

Decrease the number of partitions in the RDD to numPartitions. Useful for running operations more efficiently after filtering down a large dataset.

val rdd=sc.parallelize(Seq(0 until 99),4)
rdd.partitions.size
//4
rdd.coalesce(2).partitions.size
//2

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.

sc.parallelize(Seq(1,2,3,4,5,5,6,5,5,4,3)).repartition(3)
.collect
.foreach(println)

/*
3
6
4
1
4
5
3
2
5
5
5
*/

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.

 val rdd=sc.parallelize(Seq(40,10,30,20,50))
    .zipWithIndex()
 rdd.collect
 //res17: Array[(Int, Long)] = Array((40,0), (10,1), (30,2), (20,3), (50,4))
 //Notice unsorted pair
 import org.apache.spark.HashPartitioner
 rdd.repartitionAndSortWithinPartitions
     (new HashPartitioner(1)).collect
 //Sorted
 //res16: Array[(Int, Long)] = Array((10,1), (20,3), (30,2), (40,0), (50,4))
PreviousWorking with key value pairNextRDD Action Functions

Last updated 4 years ago

Was this helpful?