📔
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?

Build Twitter Scala API Library for Spark Streaming using sbt

If you need to import Twitter API library in Scala:

import org.apache.spark.streaming.twitter._

You will need to build the jar file and place the jar file in the classpath. In our case, default classpath is $SPARK_HOME/jars

To start with, know your Spark and Scala version, which can be found by running $SPARK_HOME/bin/spark-shell

$SPARK_HOME/bin/spark-shell
Setting default log level to "WARN".
To adjust logging level use sc.setLogLevel(newLevel). For SparkR, use setLogLevel(newLevel).
20/06/12 14:06:22 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
Spark context Web UI available at http://10.0.2.15:4040
Spark context available as 'sc' (master = local[*], app id = local-1591995983793).
Spark session available as 'spark'.
Welcome to
      ____              __
     / __/__  ___ _____/ /__
    _\ \/ _ \/ _ `/ __/  '_/
   /___/ .__/\_,_/_/ /_/\_\   version 2.2.1
      /_/

Using Scala version 2.11.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_171)
Type in expressions to have them evaluated.
Type :help for more information.

In this example, Spark version is 2.2.1, Scala version is 2.11.8

To build the "twitter jar" file, you need to manually create directory structure, let's call twitter for example, that contains subfolder project and src. Subfolder names are significant. The directory structure is like below:

(base) [hadoop@master twitter]$ tree -a
.
├── build.sbt
├── project
│   ├── assembly.sbt
│   └── build.properties
└── src
    └── main
        └── scala

Install tree command on Linux, here is CentOS, do below

sudo yum install tree -y

test tree command to see if it works

tree -d

There are 1 files from the root directory called build.sbt, you need to create:

vi build.sbt

// this file was written for spark 3.0.0-preview and scala 2.12.10
// George Jen
// Jen Tek LLC

version := "1"
name := "JentekLLC-spark-streaming-from-Twitter"
scalaVersion := "2.11.8"

libraryDependencies += "org.apache.spark" %% "spark-core" % "2.2.1" % "provided"
libraryDependencies += "org.apache.spark" %% "spark-streaming" % "2.2.1" % "provided"
libraryDependencies += "org.apache.spark" %% "spark-sql" % "2.2.1" % "provided"
libraryDependencies += "org.twitter4j" % "twitter4j-core" % "4.0.4"
libraryDependencies += "org.twitter4j" % "twitter4j-stream" % "4.0.4"
libraryDependencies += "org.apache.bahir" %% "spark-streaming-twitter" % "2.2.1"

assemblyMergeStrategy in assembly := {
  case PathList("org","aopalliance", xs @ _*) => MergeStrategy.last
  case PathList("javax", "inject", xs @ _*) => MergeStrategy.last
  case PathList("javax", "servlet", xs @ _*) => MergeStrategy.last
  case PathList("javax", "activation", xs @ _*) => MergeStrategy.last
  case PathList("org", "apache", xs @ _*) => MergeStrategy.last
  case PathList("com", "google", xs @ _*) => MergeStrategy.last
  case PathList("com", "esotericsoftware", xs @ _*) => MergeStrategy.last
  case PathList("com", "codahale", xs @ _*) => MergeStrategy.last
  case PathList("com", "yammer", xs @ _*) => MergeStrategy.last
  case "about.html" => MergeStrategy.rename
  case "META-INF/ECLIPSEF.RSA" => MergeStrategy.last
  case "META-INF/mailcap" => MergeStrategy.last
  case "META-INF/mimetypes.default" => MergeStrategy.last
  case "plugin.properties" => MergeStrategy.last
  case "log4j.properties" => MergeStrategy.last
  case x =>
    val oldStrategy = (assemblyMergeStrategy in assembly).value
    oldStrategy(x)
}

You need to set your Scala version, in my example, 2.11.8. Your one might be different.


scalaVersion := "2.11.8"

Then fill in your Spark version in these lines, mine is 2.2.1

libraryDependencies += "org.apache.spark" %% "spark-core" % "2.2.1" % "provided"

libraryDependencies += "org.apache.spark" %% "spark-streaming" % "2.2.1" % "provided"

libraryDependencies += "org.apache.spark" %% "spark-sql" % "2.2.1" % "provided"

libraryDependencies += "org.apache.bahir" %% "spark-streaming-twitter" % "2.2.1"

Also change the line spark-streaming-twitter to your Spark version, mine is 2.2.1

libraryDependencies += "org.apache.bahir" %% "spark-streaming-twitter" % "2.2.1"

Save and exit

Inside sub-folder project, there are 2 files: assembly.sbt and build.properties, you need to create both:

vi project/assembly.sbt

addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.14.10")

Save and exit

vi project/build.properties

sbt.version=1.3.6

Save and exit

You do not need place any source code file in src/main/scala folder in this excercise. We only need to download needed twitter jar files from Maven repository and assemble into one single combined jar file by sbt.

If you do not have sbt installed, you can get it at

Download the zip file, sbt-1.3.10.zip (note, the file name may be changing over the time). On linux, do below to download and install sbt:

mkdir ~/sbt
cd ~/sbt
wget https://piccolo.link/sbt-1.3.10.zip
unzip sbt-1.3.10.zip
sudo cp sbt/bin/* /usr/local/bin

Now, you should be able to build Twitter jar file using sbt

cd ~/twitter
#Test below to see you have the right 
#directory structure with right files

(base) [hadoop@master twitter]$ tree -a
.
├── build.sbt
├── project
│   ├── assembly.sbt
│   └── build.properties
└── src
    └── main
        └── scala

#Now you run sbt at the root of the directory
#that has the build.sbt file

You must run the sbt command below at the root level of the project folder, that has the file build.sbt

sbt assembly

The first time, it will takes a while and download lots of files, eventually, it will show below:

(base) [hadoop@master twitter]$ sbt assembly
[info] Loading settings for project twitter-build from assembly.sbt ...
[info] Loading project definition from /opt/hadoop/sbt/twitter/project
[info] Loading settings for project twitter from build.sbt ...
[info] Set current project to JentekLLC-spark-streaming-from-Twitter (in build file:/opt/hadoop/sbt/twitter/)
[info] Strategy 'discard' was applied to 12 files (Run the task at debug level to see details)
[info] Strategy 'last' was applied to a file (Run the task at debug level to see details)
[info] Strategy 'rename' was applied to 3 files (Run the task at debug level to see details)
[success] Total time: 8 s, completed Jun 12, 2020 3:47:03 PM

It produces a new directory called target, with subdirectory called scala-<version>, simply cd into it

(base) [hadoop@master twitter]$ ls
build.sbt  project  src  target
(base) [hadoop@master twitter]$ cd target
(base) [hadoop@master target]$ ls
scala-2.11  streams
(base) [hadoop@master target]$ cd scala*
(base) [hadoop@master scala-2.11]$ pwd
/opt/hadoop/sbt/twitter/target/scala-2.11

Now you should see twitter jar file produced

(base) [hadoop@master scala-2.11]$ ls
JentekLLC-spark-streaming-from-Twitter-assembly-1.jar  update

Then copy the jar file into $SPARK_HOME/jars/, which is the default classpath of Java library

cp JentekLLC-spark-streaming-from-Twitter-assembly-1.jar $SPARK_HOME/jars/

Then verify the file JentekLLC-spark-streaming-from-Twitter-assembly-1.jar in $SPARK_HOME/jars/

ls $SPARK_HOME/jars/Jentek*
/opt/spark/jars/JentekLLC-spark-streaming-from-Twitter-assembly-1.jar

Since we are going to load Twitter Tweets into Hive table, set the permission of HDFS /tmp/hive by:

hdfs dfs -chmod -R 777 /tmp/hive
hdfs dfs -ls /tmp/
drwx------   - hadoop supergroup          0 2020-05-09 14:16 /tmp/hadoop-yarn
drwxrwxrwx   - hadoop supergroup          0 2018-05-05 22:00 /tmp/hive

Assuming you have already started up Hadoop, Hive, Spark, and Jupyter-Notebook server in the virtualenv spark by conda activate spark. If not, visit the relevant session of this eBook if needing direction. Then launch your web browser, connect to Jupyter notebook server, start a new notebook in Scala Spylon kernel and run below code

You need to replace with your own Twitter consumer key, consumer secret, access token, access token secret. Additionally, it is likely you might need to replace the IP address of the machine that runs HIVE.

Note:

The notebook runs fines with Jupyter-notebook (server) runs on Linux, but however, on Mac, when creating a table on HIVE, following error will result, despite hive support has been enabled.

val spark = SparkSession.builder().config("spark.master", "local[2]").appName("interfacing spark sql to hive metastore through thrift url below").config("hive.metastore.uris", "thrift://localhost:9083").enableHiveSupport().getOrCreate()

But when running below create table statement

spark.sql("CREATE TABLE IF NOT EXISTS tweets (datetime STRING, text STRING) USING hive")

org.apache.spark.sql.AnalysisException: Hive support is required to CREATE Hive TABLE (AS SELECT);;
'CreateTable `tweets`, Ignore
  at org.apache.spark.sql.execution.datasources.HiveOnlyCheck$.$anonfun$apply$4(rules.scala:446)
  at org.apache.spark.sql.execution.datasources.HiveOnlyCheck$.$anonfun$apply$4$adapted(rules.scala:444)
  at org.apache.spark.sql.catalyst.trees.TreeNode.foreach(TreeNode.scala:144)
  at org.apache.spark.sql.execution.datasources.HiveOnlyCheck$.apply(rules.scala:444)
  at org.apache.spark.sql.execution.datasources.HiveOnlyCheck$.apply(rules.scala:442)
  at org.apache.spark.sql.catalyst.analysis.CheckAnalysis.$anonfun$checkAnalysis$38(CheckAnalysis.scala:574)
  at org.apache.spark.sql.catalyst.analysis.CheckAnalysis.$anonfun$checkAnalysis$38$adapted(CheckAnalysis.scala:574)

This is likely related to Jupyter notebook Spylon Kernel on MacOS only, because the same code runs fines on spark-shell on the same Mac without problem

scala> val spark = SparkSession.builder().config("spark.master", "local[2]").appName("interfacing spark sql to hive metastore through thrift url below").config("hive.metastore.uris", "thrift://localhost:9083").enableHiveSupport().getOrCreate()
spark: org.apache.spark.sql.SparkSession = org.apache.spark.sql.SparkSession@7273bb91

scala> import spark.implicits._
import spark.implicits._

scala> spark.sql("CREATE TABLE IF NOT EXISTS tweets (datetime STRING, text STRING) USING hive")
res19: org.apache.spark.sql.DataFrame = []

If you need direction, view my video presentation below in its entirety:

PreviousforeachRDD(func)NextSpark Streaming with Twitter, you can get public tweets by using Twitter API.

Last updated 4 years ago

Was this helpful?

https://www.scala-sbt.org/download.html
https://github.com/geyungjen/jentekllc/blob/master/Spark/Scala/STREAMING/twitter_streaming_project_code.ipynb
https://www.youtube.com/watch?v=XBfL6Jx4U2I&feature=youtu.be