Chapter folders renamed

This commit is contained in:
Karan Solanki
2021-08-13 11:44:51 +05:30
parent d9f3f5b159
commit 1eb709f83a
211 changed files with 0 additions and 0 deletions
+22
View File
@@ -0,0 +1,22 @@
#casestudy1: Pi calculater
from operator import add
from random import random
from pyspark.sql import SparkSession
spark = SparkSession.builder.master("spark://192.168.64.2:7077") \
.appName("Pi claculator app") \
.getOrCreate()
partitions = 2
n = 10000000 * partitions
def f(_):
x = random() * 2 - 1
y = random() * 2 - 1
return 1 if x ** 2 + y ** 2 <= 1 else 0
count = spark.sparkContext.parallelize(range(1, n + 1), partitions).map(f).reduce(add)
print("Pi is roughly %f" % (4.0 * count / n))
+32
View File
@@ -0,0 +1,32 @@
#casestudy2.py: word count application
import matplotlib.pyplot as plt
from pyspark.sql import SparkSession
from wordcloud import WordCloud
spark = SparkSession.builder.master("local[*]")\
.appName("word cloud app")\
.getOrCreate()
wc_threshold = 1
wl_threshold = 3
textRDD = spark.sparkContext.textFile('wordcloud.txt',3)
flatRDD = textRDD.flatMap(lambda x: x.split(' '))
wcRDD = flatRDD.map(lambda word: (word, 1)).\
reduceByKey(lambda v1, v2: v1 + v2)
# filter out words with fewer than threshold occurrences
filteredRDD = wcRDD.filter(lambda pair: pair[1] >= wc_threshold)
filteredRDD2 = filteredRDD.filter(lambda pair:
len(pair[0]) > wl_threshold)
word_freq = dict(filteredRDD2.collect())
# Create the wordcloud object
wordcloud = WordCloud(width=480, height=480, margin=0).\
generate_from_frequencies(word_freq)
# Display the generated cloud image
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis("off")
plt.margins(x=0, y=0)
plt.show()
+97
View File
@@ -0,0 +1,97 @@
Spark Overview
Apache Spark is a unified analytics engine for large-scale data processing. It provides high-level APIs in Java, Scala, Python and R, and an optimized engine that supports general execution graphs. It also supports a rich set of higher-level tools including Spark SQL for SQL and structured data processing, MLlib for machine learning, GraphX for graph processing, and Structured Streaming for incremental computation and stream processing.
Security
Security in Spark is OFF by default. This could mean you are vulnerable to attack by default. Please see Spark Security before downloading and running Spark.
Downloading
Get Spark from the downloads page of the project website. This documentation is for Spark version 3.1.2. Spark uses Hadoops client libraries for HDFS and YARN. Downloads are pre-packaged for a handful of popular Hadoop versions. Users can also download a “Hadoop free” binary and run Spark with any Hadoop version by augmenting Sparks classpath. Scala and Java users can include Spark in their projects using its Maven coordinates and Python users can install Spark from PyPI.
If youd like to build Spark from source, visit Building Spark.
Spark runs on both Windows and UNIX-like systems (e.g. Linux, Mac OS), and it should run on any platform that runs a supported version of Java. This should include JVMs on x86_64 and ARM64. Its easy to run locally on one machine — all you need is to have java installed on your system PATH, or the JAVA_HOME environment variable pointing to a Java installation.
Spark runs on Java 8/11, Scala 2.12, Python 3.6+ and R 3.5+. Java 8 prior to version 8u92 support is deprecated as of Spark 3.0.0. For the Scala API, Spark 3.1.2 uses Scala 2.12. You will need to use a compatible Scala version (2.12.x).
For Python 3.9, Arrow optimization and pandas UDFs might not work due to the supported Python versions in Apache Arrow. Please refer to the latest Python Compatibility page. For Java 11, -Dio.netty.tryReflectionSetAccessible=true is required additionally for Apache Arrow library. This prevents java.lang.UnsupportedOperationException: sun.misc.Unsafe or java.nio.DirectByteBuffer.(long, int) not available when Apache Arrow uses Netty internally.
Running the Examples and Shell
Spark comes with several sample programs. Scala, Java, Python and R examples are in the examples/src/main directory. To run one of the Java or Scala sample programs, use bin/run-example <class> [params] in the top-level Spark directory. (Behind the scenes, this invokes the more general spark-submit script for launching applications). For example,
./bin/run-example SparkPi 10
You can also run Spark interactively through a modified version of the Scala shell. This is a great way to learn the framework.
./bin/spark-shell --master local[2]
The --master option specifies the master URL for a distributed cluster, or local to run locally with one thread, or local[N] to run locally with N threads. You should start by using local for testing. For a full list of options, run Spark shell with the --help option.
Spark also provides a Python API. To run Spark interactively in a Python interpreter, use bin/pyspark:
./bin/pyspark --master local[2]
Example applications are also provided in Python. For example,
./bin/spark-submit examples/src/main/python/pi.py 10
Spark also provides an R API since 1.4 (only DataFrames APIs included). To run Spark interactively in an R interpreter, use bin/sparkR:
./bin/sparkR --master local[2]
Example applications are also provided in R. For example,
./bin/spark-submit examples/src/main/r/dataframe.R
Launching on a Cluster
The Spark cluster mode overview explains the key concepts in running on a cluster. Spark can run both by itself, or over several existing cluster managers. It currently provides several options for deployment:
Standalone Deploy Mode: simplest way to deploy Spark on a private cluster
Apache Mesos
Hadoop YARN
Kubernetes
Where to Go from Here
Programming Guides:
Quick Start: a quick introduction to the Spark API; start here!
RDD Programming Guide: overview of Spark basics - RDDs (core but old API), accumulators, and broadcast variables
Spark SQL, Datasets, and DataFrames: processing structured data with relational queries (newer API than RDDs)
Structured Streaming: processing structured data streams with relation queries (using Datasets and DataFrames, newer API than DStreams)
Spark Streaming: processing data streams using DStreams (old API)
MLlib: applying machine learning algorithms
GraphX: processing graphs
SparkR: processing data with Spark in R
PySpark: processing data with Spark in Python
API Docs:
Spark Scala API (Scaladoc)
Spark Java API (Javadoc)
Spark Python API (Sphinx)
Spark R API (Roxygen2)
Spark SQL, Built-in Functions (MkDocs)
Deployment Guides:
Cluster Overview: overview of concepts and components when running on a cluster
Submitting Applications: packaging and deploying applications
Deployment modes:
Amazon EC2: scripts that let you launch a cluster on EC2 in about 5 minutes
Standalone Deploy Mode: launch a standalone cluster quickly without a third-party cluster manager
Mesos: deploy a private cluster using Apache Mesos
YARN: deploy Spark on top of Hadoop NextGen (YARN)
Kubernetes: deploy Spark on top of Kubernetes
Other Documents:
Configuration: customize Spark via its configuration system
Monitoring: track the behavior of your applications
Tuning Guide: best practices to optimize performance and memory use
Job Scheduling: scheduling resources across and within Spark applications
Security: Spark security support
Hardware Provisioning: recommendations for cluster hardware
Integration with other storage systems:
Cloud Infrastructures
OpenStack Swift
Migration Guide: Migration guides for Spark components
Building Spark: build Spark using the Maven system
Contributing to Spark
Third Party Projects: related third party Spark projects
External Resources:
Spark Homepage
Spark Community resources, including local meetups
StackOverflow tag apache-spark
Mailing Lists: ask questions about Spark here
AMP Camps: a series of training camps at UC Berkeley that featured talks and exercises about Spark, Spark Streaming, Mesos, and more. Videos, slides and exercises are available online for free.
Code Examples: more are also available in the examples subfolder of Spark (Scala, Java, Python, R)
+6
View File
@@ -0,0 +1,6 @@
firstname,middlename,lastname,department,gender,salary
James,,Bylsma,HR,M,40000
Kamal,Rahim,,HR,M,41000
Robert,,Zaine,Finance,M,35000
Sophia,Anne,Richer,Finance,F,4000
John,Will,Brown,Engineering,F,65000
1 firstname middlename lastname department gender salary
2 James Bylsma HR M 40000
3 Kamal Rahim HR M 41000
4 Robert Zaine Finance M 35000
5 Sophia Anne Richer Finance F 4000
6 John Will Brown Engineering F 65000
+24
View File
@@ -0,0 +1,24 @@
#dfcreate1.py: create a df from a collection
#please ignore next 2 statements if running directly in PySpark shell
import time
from pyspark.sql import SparkSession
spark = SparkSession.builder.master("local[*]")\
.appName("DataFrame Test app")\
.getOrCreate()
data = [('James','','Bylsma','HR','M',40000),
('Kamal','Rahim','','HR','M',41000),
('Robert','','Zaine','Finance','M',35000),
('Sophia','Anne','Richer','Finance','F',4000),
('John','Will','Brown','Engineering','F',65000)
]
columns = ["firstname","middlename","lastname",
"department","gender","salary"]
df = spark.createDataFrame(data=data, schema = columns)
print(df.printSchema())
print(df.show())
time.sleep(60)
+26
View File
@@ -0,0 +1,26 @@
#dfcreate2.py: create a df from a csv file
#please ignore next 2 statements if running directly in PySpark shell
import time
from pyspark.sql import SparkSession
from pyspark.sql.types import StructType, StructField, StringType, IntegerType
spark = SparkSession.builder.master("local[*]")\
.appName("DataFrame Test app")\
.getOrCreate()
schemas = StructType([ \
StructField("firstname",StringType(),True), \
StructField("middlename",StringType(),True), \
StructField("lastname",StringType(),True), \
StructField("department", StringType(), True), \
StructField("gender", StringType(), True), \
StructField("salary", IntegerType(), True) \
])
df = spark.read.csv('df2.csv', header=True, nullValue='NA', schema=schemas)
print(df.printSchema())
print(df.show())
time.sleep(60)
+43
View File
@@ -0,0 +1,43 @@
#dfcreate1.py: create a df from a collection
#please ignore next 2 statements if running directly in PySpark shell
import time
from pyspark.sql import SparkSession
from pyspark.sql.functions import regexp_replace, lit, when
spark = SparkSession.builder.master("local[*]")\
.appName("DataFrame Test app")\
.getOrCreate()
data = [('James','','Bylsma','HR','M',40000),
('Kamal','Rahim','','HR','M',41000),
('Robert','','Zaine','Finance','M',35000),
('Sophia','Anne','Richer','Finance','F',47000),
('John','Will','Brown','Engineering','F',65000)
]
columns = ["firstname","middlename","lastname",
"department","gender","salary"]
df = spark.createDataFrame(data=data, schema = columns)
#show two columns
print(df.select([df.firstname, df.salary]).show())
#replacing values of a columm
myDict = {'F':'Female','M':'Male'}
df2 = df.replace(myDict, subset=['gender'])
#Another way of replacing column values
#df1 = df.withColumn('gender',regexp_replace('gender','M', 'Male'))
#df2 = df1.withColumn('gender',regexp_replace('gender','F', 'Female'))
#adding a new colum Pay Level based on an existing column values
df3 = df2.withColumn("Pay Level",
when((df2.salary < 40000), lit("10")) \
.when((df.salary >= 40000) & (df.salary <= 50000), lit("11")) \
.otherwise(lit("12")) \
)
print(df3.show())
time.sleep(60)
+24
View File
@@ -0,0 +1,24 @@
#rddaction1.py: rdd action functions
#please ignore next 2 statements if running directly in PySpark shell
import time
from pyspark.sql import SparkSession
spark = SparkSession.builder.master("local[*]")\
.appName("RDD Test app")\
.getOrCreate()
data = [5, 4, 6, 3, 2, 8, 9, 2, 8, 7,
8, 4, 4, 8, 2, 7, 8, 9, 6, 9]
rdd1 = spark.sparkContext.parallelize(data)
print("RDD contents with partitions: "+rdd1.glom().collect())
print("Count by values: "+rdd1.countByValue())
print("reduce function"+rdd1.reduce(lambda a,b: a+b))
print("Sum of RDD contents"+rdd1.sum())
print(""+rdd1.top(5))
print(rdd1.count())
print(rdd1.max())
print(rdd1.min())
time.sleep(60)
+16
View File
@@ -0,0 +1,16 @@
#rddcreate.py: to create rdd from a collection and from a file
#please ignore next 2 statements if running directly in PySpark shell
from pyspark.sql import SparkSession
spark = SparkSession.builder.master("local[*]")\
.appName("RDD Test app")\
.getOrCreate()
data = [5, 4, 6, 3, 2, 8, 9, 2, 8, 7,
8, 4, 4, 8, 2, 7, 8, 9, 6, 9]
rdd1 = spark.sparkContext.parallelize(data)
print(rdd1.getNumPartitions())
rdd2 = spark.sparkContext.textFile('sample.txt')
print(rdd2.getNumPartitions())
+19
View File
@@ -0,0 +1,19 @@
#rddtransform1.py: rdd tranformation function
#please ignore next 2 statements if running directly in PySpark shell
import time
from pyspark.sql import SparkSession
spark = SparkSession.builder.master("local[*]")\
.appName("RDD Test app")\
.getOrCreate()
rdd1 = spark.sparkContext.textFile('sample.txt')
#print(rdd1.getNumPartitions())
rdd2 = rdd1.map(lambda lines: lines.lower())
rdd3 = rdd1.map(lambda lines: lines.upper())
print(rdd2.collect())
print(rdd3.collect())
time.sleep(60)
+13
View File
@@ -0,0 +1,13 @@
#rddtransform2.py: rdd tranformation function-map
#please ignore next 2 statements if running directly in PySpark shell
from pyspark.sql import SparkSession
spark = SparkSession.builder.master("local[*]")\
.appName("RDD Test app")\
.getOrCreate()
data = [5, 4, 6, 3, 2, 8, 9, 2, 8, 7,
8, 4, 4, 8, 2, 7, 8, 9, 6, 9]
rdd1 = spark.sparkContext.parallelize(data)
rdd2 = rdd1.filter(lambda x: x % 2 !=0 )
print(rdd2.collect())
+4
View File
@@ -0,0 +1,4 @@
Spark Read Text File | RDD | DataFrame — SparkByExampleshttps://sparkbyexamples.com spark spark-read-text-...
Complete example — txt files, for example, sparkContext.textFile() and sparkContext.wholeTextFiles() methods to read into RDD and spark.read.text() ...
Quick Start - Spark 2.2.1 Documentation - Apache Sparkhttps://spark.apache.org docs quick-start
scala> val textFile = spark.read.textFile("README.md") textFile: org.apache.spark.sql. ... For example, we can easily call functions declared elsewhere. We'll use ...
+34
View File
@@ -0,0 +1,34 @@
#dfcreate1.py: create a df from a collection
#please ignore next 2 statements if running directly in PySpark shell
import time
from pyspark.sql import SparkSession
from pyspark.sql.functions import regexp_replace, lit, when
spark = SparkSession.builder.master("local[*]")\
.appName("DataFrame Test app")\
.getOrCreate()
data = [('James','','Bylsma','HR','M',40000),
('Kamal','Rahim','','HR','M',41000),
('Robert','','Zaine','Finance','M',35000),
('Sophia','Anne','Richer','Finance','F',47000),
('John','Will','Brown','Engineering','F',65000)
]
columns = ["firstname","middlename","lastname",
"department","gender","salary"]
df = spark.createDataFrame(data=data, schema = columns)
df.createOrReplaceTempView("EMP_DATA")
df2 = spark.sql("SELECT * FROM EMP_DATA")
print(df2.show())
df3 = spark.sql("SELECT firstname, middlename, lastname, "
"salary FROM EMP_DATA WHERE SALARY > 45000")
print(df3.show())
df4 = spark.sql(("SELECT gender, count(*) from EMP_DATA group by gender"))
print(df4.show())