SlideShare uma empresa Scribd logo
1 de 28
Baixar para ler offline
Data processing with Spark
in R & Python
Maloy Manna
linkedin.com/in/maloy @itsmaloy biguru.wordpress.com
Abstract
With ever increasing adoption by vendors and enterprises, Spark is fast
becoming the de facto big data platform.
As a general purpose data processing engine, Spark can be used in both R and
Python programs.
In this webinar, we’ll see how to use Spark to process data from various
sources in R and Python and how new tools like Spark SQL and data frames
make it easy to perform structured data processing.
Speaker profile
Maloy Manna
Data science engineering
AXA Data Innovation Lab
• Building data driven products and services for over 15 years
• Worked in Thomson Reuters, Infosys, TCS and data science startup Saama
linkedin.com/in/maloy @itsmaloy biguru.wordpress.com
Agenda
• Overview of Spark
• Data processing operations
• RDD operations
– Transformations, Actions
• Spark SQL
– DataFrames
– DataFrame operations
• Spark R
• Useful Tips
• References
Overview of Spark
• Fast, general-purpose engine for large-scale data
processing
• Smarter than Hadoop in utilizing memory
• Faster than MapReduce in memory & on disk
• Can run on Hadoop, or standalone; can access data in
HDFS, Cassandra, Hive / any Hadoop data source
• Provides high-level APIs in Scala, Java, Python & R
• Supports high-level tools like Spark SQL for structured
data processing
Using Spark for data science & big data
• Data science lifecycle
• 50% – 80% of time spent in data preparation stage
• Automation is key to efficiency
• R & Python already have packages & libraries for data processing
• Apache Spark adds more power to R & Python big data wrangling
Data processing
Getting data to the right format for analysis:
• Data manipulations
• Data tidying
• Data visualization
reshaping formatting
cleaning Transformations
munging Wrangling carpentry
manipulation cleaning
processing
Data processing - operations
• Reshaping data
Change layout (rows/columns “shape”) of dataset
• Subset data
Select rows or columns
• Group data
Group data by categories, summarize values
• Make new variables
Compute and append new columns, drop old columns
• Combine data sets
Joins, append rows/columns, set operations
• Driver program runs main function
• RDD (resilient distributed datasets) and shared
variables help in parallel execution
• Cluster manager distributes code and manages data in
RDDs
Spark for data processing
Installing and using Spark
• Install pre-compiled package
http://spark.apache.org/downloads.html
• Build from source code
http://spark.apache.org/docs/latest/building-spark.html
• Run Spark on Amazon EC2 or use Databricks Spark notebooks (Python / R)
http://spark.apache.org/docs/latest/ec2-scripts.html | www.databricks.com/registration
• Run as Docker image
https://hub.docker.com/r/sequenceiq/spark/
• Download pre-compiled release version
• Choose “pre-built for Hadoop 2.6 and later”
• Unpack/untar package
• Try out the Python interactive shell
bin/pyspark
• Ensure JAVA_HOME is set
bin/sparkR
Installing Spark
Using Spark in Python
• Import Spark classes
• Create SparkContext object (driver program) and
initialize it
• In practice, use the spark-submit script to launch
applications on a cluster, using configurable
options and including dependencies
• Once a SparkContext is available, it can be used
to build RDDs.
RDD: Transformations & Actions
• RDD is immutable, distributed data structure
– Each RDD is split into multiple partitions
• Can be created in 2 ways:
– Loading external dataset or
– Distributing a collection of objects in driver
• RDDs support 2 different types of operations:
– Transformations (construct new RDD)
– Actions (compute result based on RDD)
RDD: Transformations & Actions
Transformations
 No (lazy) evaluations
 New RDD returned
 Examples:
⁻ map
⁻ filter
⁻ flatMap
⁻ groupByKey
⁻ reduceByKey
⁻ aggregateByKey
⁻ union
⁻ join
⁻ coalesce
Actions
 Evaluations done
 New value returned
 Examples:
⁻ reduce
⁻ collect
⁻ count
⁻ first
⁻ take
⁻ countByKey
⁻ foreach
⁻ saveAsTextFile
⁻ saveAsSequenceFile
Create RDDs
• Creating distributed datasets
– From any storage source supported by Hadoop
• Use SparkContext methods:
– Support directories, compressed files, wildcards
Loading data
• Loading text files
• Loading unstructured JSON files
• Loading sequence files
Loading data
• Loading csv files
• Loading csv files in full
Saving data
• Saving text files
• Saving unstructured JSON files
• Saving csv files
Spark SQL
• Spark’s interface for working with structured
and semi-structured data
• Can load data from JSON, Hive, Parquet
• Can query using SQL
• Can be combined with regular code e.g.
Python / Java inside Spark application
• Provides “DataFrames” (SchemaRDD < v1.3)
• Like RDDs, DataFrames are evaluated “lazily”
Using Spark SQL
• HiveContext (or SQLContext for a stripped-
down version) based on SparkContext
• Construct a SQLContext:
• Basic query:
Spark SQL: DataFrames
• Spark SQL provides DataFrames as programming
abstractions
• A DataFrame is a distributed collection of data
organized into named columns
• Conceptually equivalent to relational table
• Familiar syntax (R dplyr / Pandas) but scales to PBs
• Entry-point remains SQLContext
Spark SQL: DataFrame Operations
• Selecting rows, columns
• Grouping / aggregation
• Running SQL queries
• Window functions
• Reading JSON data into dataframe in Python
• Reading JSON data into dataframe in R
DataFrames – Data Operations
• Generic load/save
– Python
– R
• Default data source parquet
– Can be changed by manually specifying format
DataFrames – Saving data
SparkR
• R package providing light-weight front-end to
use Apache Spark from R
• Entry point in SparkContext
• With SQLContext, dataframes can be created
from local R data frames, Hive tables or other
Spark data sources
• Introduced with Spark 1.4
SparkR: Creating DataFrames
• From local data frames
• From data sources like JSON
• From Hive tables
Useful tips
• Use Spark SQL dataframes to write less code.
Easier to avoid closure problems.
• Be aware of closure issues while working in
cluster mode. Use accumulator variables instead
of locally defined methods
• Utilize Spark SQL capability to automatically infer
schema of JSON datasets
SQLContext.read.json
• Other than using command-line, IDEs like IntelliJ
IDEA community edition can be used for free
References
• Spark pages: http://spark.apache.org/
• Databricks blog: https://databricks.com/blog
• Spark summit: https://spark-summit.org/
• Additional Spark packages at: http://spark-packages.org/
• Example scripts:
• https://github.com/apache/spark/blob/master/examples/src/main/pytho
n/sql.py
• https://github.com/apache/spark/blob/master/examples/src/main/r/data
-manipulation.R
• https://github.com/apache/spark/blob/master/examples/src/main/r/data
frame.R
• API docs: http://spark.apache.org/docs/latest/api/python/index.html
• http://spark.apache.org/docs/latest/api/R/index.html
• Using SparkR in Rstudio: http://www.r-bloggers.com/how-to-use-sparkr-
within-rstudio/

Mais conteúdo relacionado

Mais procurados

Apache Spark Based Reliable Data Ingestion in Datalake with Gagan Agrawal
Apache Spark Based Reliable Data Ingestion in Datalake with Gagan AgrawalApache Spark Based Reliable Data Ingestion in Datalake with Gagan Agrawal
Apache Spark Based Reliable Data Ingestion in Datalake with Gagan Agrawal
Databricks
 

Mais procurados (20)

Hoodie: How (And Why) We built an analytical datastore on Spark
Hoodie: How (And Why) We built an analytical datastore on SparkHoodie: How (And Why) We built an analytical datastore on Spark
Hoodie: How (And Why) We built an analytical datastore on Spark
 
Apache Spark Streaming
Apache Spark StreamingApache Spark Streaming
Apache Spark Streaming
 
A Thorough Comparison of Delta Lake, Iceberg and Hudi
A Thorough Comparison of Delta Lake, Iceberg and HudiA Thorough Comparison of Delta Lake, Iceberg and Hudi
A Thorough Comparison of Delta Lake, Iceberg and Hudi
 
Managing ADLS gen2 using Apache Spark
Managing ADLS gen2 using Apache SparkManaging ADLS gen2 using Apache Spark
Managing ADLS gen2 using Apache Spark
 
Apache Spark 101
Apache Spark 101Apache Spark 101
Apache Spark 101
 
Spark SQL
Spark SQLSpark SQL
Spark SQL
 
Spark SQL Beyond Official Documentation
Spark SQL Beyond Official DocumentationSpark SQL Beyond Official Documentation
Spark SQL Beyond Official Documentation
 
Hoodie - DataEngConf 2017
Hoodie - DataEngConf 2017Hoodie - DataEngConf 2017
Hoodie - DataEngConf 2017
 
Hoodie: Incremental processing on hadoop
Hoodie: Incremental processing on hadoopHoodie: Incremental processing on hadoop
Hoodie: Incremental processing on hadoop
 
Apache spark - Architecture , Overview & libraries
Apache spark - Architecture , Overview & librariesApache spark - Architecture , Overview & libraries
Apache spark - Architecture , Overview & libraries
 
Apache Spark PDF
Apache Spark PDFApache Spark PDF
Apache Spark PDF
 
HKOSCon18 - Chetan Khatri - Scaling TB's of Data with Apache Spark and Scala ...
HKOSCon18 - Chetan Khatri - Scaling TB's of Data with Apache Spark and Scala ...HKOSCon18 - Chetan Khatri - Scaling TB's of Data with Apache Spark and Scala ...
HKOSCon18 - Chetan Khatri - Scaling TB's of Data with Apache Spark and Scala ...
 
Apache Spark Based Reliable Data Ingestion in Datalake with Gagan Agrawal
Apache Spark Based Reliable Data Ingestion in Datalake with Gagan AgrawalApache Spark Based Reliable Data Ingestion in Datalake with Gagan Agrawal
Apache Spark Based Reliable Data Ingestion in Datalake with Gagan Agrawal
 
Introduction to Apache Spark
Introduction to Apache SparkIntroduction to Apache Spark
Introduction to Apache Spark
 
Spark Core
Spark CoreSpark Core
Spark Core
 
Introduction to apache spark
Introduction to apache sparkIntroduction to apache spark
Introduction to apache spark
 
Meetup Oracle Database BCN: 2.1 Data Management Trends
Meetup Oracle Database BCN: 2.1 Data Management TrendsMeetup Oracle Database BCN: 2.1 Data Management Trends
Meetup Oracle Database BCN: 2.1 Data Management Trends
 
Introduction to Apache Spark
Introduction to Apache Spark Introduction to Apache Spark
Introduction to Apache Spark
 
Lighting up Big Data Analytics with Apache Spark in Azure
Lighting up Big Data Analytics with Apache Spark in AzureLighting up Big Data Analytics with Apache Spark in Azure
Lighting up Big Data Analytics with Apache Spark in Azure
 
Introduction to SparkR
Introduction to SparkRIntroduction to SparkR
Introduction to SparkR
 

Semelhante a Data processing with spark in r &amp; python

Extending Apache Spark SQL Data Source APIs with Join Push Down with Ioana De...
Extending Apache Spark SQL Data Source APIs with Join Push Down with Ioana De...Extending Apache Spark SQL Data Source APIs with Join Push Down with Ioana De...
Extending Apache Spark SQL Data Source APIs with Join Push Down with Ioana De...
Databricks
 
Apache Spark for RDBMS Practitioners: How I Learned to Stop Worrying and Lov...
 Apache Spark for RDBMS Practitioners: How I Learned to Stop Worrying and Lov... Apache Spark for RDBMS Practitioners: How I Learned to Stop Worrying and Lov...
Apache Spark for RDBMS Practitioners: How I Learned to Stop Worrying and Lov...
Databricks
 

Semelhante a Data processing with spark in r &amp; python (20)

Apache Spark on HDinsight Training
Apache Spark on HDinsight TrainingApache Spark on HDinsight Training
Apache Spark on HDinsight Training
 
Big_data_analytics_NoSql_Module-4_Session
Big_data_analytics_NoSql_Module-4_SessionBig_data_analytics_NoSql_Module-4_Session
Big_data_analytics_NoSql_Module-4_Session
 
Processing Large Data with Apache Spark -- HasGeek
Processing Large Data with Apache Spark -- HasGeekProcessing Large Data with Apache Spark -- HasGeek
Processing Large Data with Apache Spark -- HasGeek
 
Extending Apache Spark SQL Data Source APIs with Join Push Down with Ioana De...
Extending Apache Spark SQL Data Source APIs with Join Push Down with Ioana De...Extending Apache Spark SQL Data Source APIs with Join Push Down with Ioana De...
Extending Apache Spark SQL Data Source APIs with Join Push Down with Ioana De...
 
Large Scale Data Analytics with Spark and Cassandra on the DSE Platform
Large Scale Data Analytics with Spark and Cassandra on the DSE PlatformLarge Scale Data Analytics with Spark and Cassandra on the DSE Platform
Large Scale Data Analytics with Spark and Cassandra on the DSE Platform
 
Big data processing with Apache Spark and Oracle Database
Big data processing with Apache Spark and Oracle DatabaseBig data processing with Apache Spark and Oracle Database
Big data processing with Apache Spark and Oracle Database
 
Unit II Real Time Data Processing tools.pptx
Unit II Real Time Data Processing tools.pptxUnit II Real Time Data Processing tools.pptx
Unit II Real Time Data Processing tools.pptx
 
Apache spark its place within a big data stack
Apache spark  its place within a big data stackApache spark  its place within a big data stack
Apache spark its place within a big data stack
 
Big Data training
Big Data trainingBig Data training
Big Data training
 
Apache Spark for RDBMS Practitioners: How I Learned to Stop Worrying and Lov...
 Apache Spark for RDBMS Practitioners: How I Learned to Stop Worrying and Lov... Apache Spark for RDBMS Practitioners: How I Learned to Stop Worrying and Lov...
Apache Spark for RDBMS Practitioners: How I Learned to Stop Worrying and Lov...
 
Apache Spark - Lightning Fast Cluster Computing - Hyderabad Scalability Meetup
Apache Spark - Lightning Fast Cluster Computing - Hyderabad Scalability MeetupApache Spark - Lightning Fast Cluster Computing - Hyderabad Scalability Meetup
Apache Spark - Lightning Fast Cluster Computing - Hyderabad Scalability Meetup
 
Dec6 meetup spark presentation
Dec6 meetup spark presentationDec6 meetup spark presentation
Dec6 meetup spark presentation
 
Large Scale Machine learning with Spark
Large Scale Machine learning with SparkLarge Scale Machine learning with Spark
Large Scale Machine learning with Spark
 
Big Data Processing with Apache Spark 2014
Big Data Processing with Apache Spark 2014Big Data Processing with Apache Spark 2014
Big Data Processing with Apache Spark 2014
 
2014-10-20 Large-Scale Machine Learning with Apache Spark at Internet of Thin...
2014-10-20 Large-Scale Machine Learning with Apache Spark at Internet of Thin...2014-10-20 Large-Scale Machine Learning with Apache Spark at Internet of Thin...
2014-10-20 Large-Scale Machine Learning with Apache Spark at Internet of Thin...
 
Jump Start on Apache Spark 2.2 with Databricks
Jump Start on Apache Spark 2.2 with DatabricksJump Start on Apache Spark 2.2 with Databricks
Jump Start on Apache Spark 2.2 with Databricks
 
APACHE SPARK.pptx
APACHE SPARK.pptxAPACHE SPARK.pptx
APACHE SPARK.pptx
 
Paris Data Geek - Spark Streaming
Paris Data Geek - Spark Streaming Paris Data Geek - Spark Streaming
Paris Data Geek - Spark Streaming
 
Spark and Couchbase: Augmenting the Operational Database with Spark
Spark and Couchbase: Augmenting the Operational Database with SparkSpark and Couchbase: Augmenting the Operational Database with Spark
Spark and Couchbase: Augmenting the Operational Database with Spark
 
Intro to Apache Spark by CTO of Twingo
Intro to Apache Spark by CTO of TwingoIntro to Apache Spark by CTO of Twingo
Intro to Apache Spark by CTO of Twingo
 

Mais de Maloy Manna, PMP®

Mais de Maloy Manna, PMP® (9)

From Big Data to AI
From Big Data to AIFrom Big Data to AI
From Big Data to AI
 
Pre processing big data
Pre processing big dataPre processing big data
Pre processing big data
 
Data Visualization in Data Science
Data Visualization in Data ScienceData Visualization in Data Science
Data Visualization in Data Science
 
Coursera Data Analysis and Statistical Inference 2014
Coursera Data Analysis and Statistical Inference 2014Coursera Data Analysis and Statistical Inference 2014
Coursera Data Analysis and Statistical Inference 2014
 
Coursera Getting and Cleaning Data 2014
Coursera Getting and Cleaning Data 2014Coursera Getting and Cleaning Data 2014
Coursera Getting and Cleaning Data 2014
 
Coursera Exploratory Data Analysis 2014
Coursera Exploratory Data Analysis 2014Coursera Exploratory Data Analysis 2014
Coursera Exploratory Data Analysis 2014
 
Scrum Certification - SFC
Scrum Certification - SFCScrum Certification - SFC
Scrum Certification - SFC
 
Coursera R Programming 2014
Coursera R Programming 2014Coursera R Programming 2014
Coursera R Programming 2014
 
Coursera The Data Scientist's Toolbox 2014
Coursera The Data Scientist's Toolbox 2014Coursera The Data Scientist's Toolbox 2014
Coursera The Data Scientist's Toolbox 2014
 

Último

Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
AnaAcapella
 

Último (20)

Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Magic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxMagic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptx
 

Data processing with spark in r &amp; python

  • 1. Data processing with Spark in R & Python Maloy Manna linkedin.com/in/maloy @itsmaloy biguru.wordpress.com
  • 2. Abstract With ever increasing adoption by vendors and enterprises, Spark is fast becoming the de facto big data platform. As a general purpose data processing engine, Spark can be used in both R and Python programs. In this webinar, we’ll see how to use Spark to process data from various sources in R and Python and how new tools like Spark SQL and data frames make it easy to perform structured data processing.
  • 3. Speaker profile Maloy Manna Data science engineering AXA Data Innovation Lab • Building data driven products and services for over 15 years • Worked in Thomson Reuters, Infosys, TCS and data science startup Saama linkedin.com/in/maloy @itsmaloy biguru.wordpress.com
  • 4. Agenda • Overview of Spark • Data processing operations • RDD operations – Transformations, Actions • Spark SQL – DataFrames – DataFrame operations • Spark R • Useful Tips • References
  • 5. Overview of Spark • Fast, general-purpose engine for large-scale data processing • Smarter than Hadoop in utilizing memory • Faster than MapReduce in memory & on disk • Can run on Hadoop, or standalone; can access data in HDFS, Cassandra, Hive / any Hadoop data source • Provides high-level APIs in Scala, Java, Python & R • Supports high-level tools like Spark SQL for structured data processing
  • 6. Using Spark for data science & big data • Data science lifecycle • 50% – 80% of time spent in data preparation stage • Automation is key to efficiency • R & Python already have packages & libraries for data processing • Apache Spark adds more power to R & Python big data wrangling
  • 7. Data processing Getting data to the right format for analysis: • Data manipulations • Data tidying • Data visualization reshaping formatting cleaning Transformations munging Wrangling carpentry manipulation cleaning processing
  • 8. Data processing - operations • Reshaping data Change layout (rows/columns “shape”) of dataset • Subset data Select rows or columns • Group data Group data by categories, summarize values • Make new variables Compute and append new columns, drop old columns • Combine data sets Joins, append rows/columns, set operations
  • 9. • Driver program runs main function • RDD (resilient distributed datasets) and shared variables help in parallel execution • Cluster manager distributes code and manages data in RDDs Spark for data processing
  • 10. Installing and using Spark • Install pre-compiled package http://spark.apache.org/downloads.html • Build from source code http://spark.apache.org/docs/latest/building-spark.html • Run Spark on Amazon EC2 or use Databricks Spark notebooks (Python / R) http://spark.apache.org/docs/latest/ec2-scripts.html | www.databricks.com/registration • Run as Docker image https://hub.docker.com/r/sequenceiq/spark/
  • 11. • Download pre-compiled release version • Choose “pre-built for Hadoop 2.6 and later” • Unpack/untar package • Try out the Python interactive shell bin/pyspark • Ensure JAVA_HOME is set bin/sparkR Installing Spark
  • 12. Using Spark in Python • Import Spark classes • Create SparkContext object (driver program) and initialize it • In practice, use the spark-submit script to launch applications on a cluster, using configurable options and including dependencies • Once a SparkContext is available, it can be used to build RDDs.
  • 13. RDD: Transformations & Actions • RDD is immutable, distributed data structure – Each RDD is split into multiple partitions • Can be created in 2 ways: – Loading external dataset or – Distributing a collection of objects in driver • RDDs support 2 different types of operations: – Transformations (construct new RDD) – Actions (compute result based on RDD)
  • 14. RDD: Transformations & Actions Transformations  No (lazy) evaluations  New RDD returned  Examples: ⁻ map ⁻ filter ⁻ flatMap ⁻ groupByKey ⁻ reduceByKey ⁻ aggregateByKey ⁻ union ⁻ join ⁻ coalesce Actions  Evaluations done  New value returned  Examples: ⁻ reduce ⁻ collect ⁻ count ⁻ first ⁻ take ⁻ countByKey ⁻ foreach ⁻ saveAsTextFile ⁻ saveAsSequenceFile
  • 15. Create RDDs • Creating distributed datasets – From any storage source supported by Hadoop • Use SparkContext methods: – Support directories, compressed files, wildcards
  • 16. Loading data • Loading text files • Loading unstructured JSON files • Loading sequence files
  • 17. Loading data • Loading csv files • Loading csv files in full
  • 18. Saving data • Saving text files • Saving unstructured JSON files • Saving csv files
  • 19. Spark SQL • Spark’s interface for working with structured and semi-structured data • Can load data from JSON, Hive, Parquet • Can query using SQL • Can be combined with regular code e.g. Python / Java inside Spark application • Provides “DataFrames” (SchemaRDD < v1.3) • Like RDDs, DataFrames are evaluated “lazily”
  • 20. Using Spark SQL • HiveContext (or SQLContext for a stripped- down version) based on SparkContext • Construct a SQLContext: • Basic query:
  • 21. Spark SQL: DataFrames • Spark SQL provides DataFrames as programming abstractions • A DataFrame is a distributed collection of data organized into named columns • Conceptually equivalent to relational table • Familiar syntax (R dplyr / Pandas) but scales to PBs • Entry-point remains SQLContext
  • 22. Spark SQL: DataFrame Operations • Selecting rows, columns • Grouping / aggregation • Running SQL queries • Window functions
  • 23. • Reading JSON data into dataframe in Python • Reading JSON data into dataframe in R DataFrames – Data Operations
  • 24. • Generic load/save – Python – R • Default data source parquet – Can be changed by manually specifying format DataFrames – Saving data
  • 25. SparkR • R package providing light-weight front-end to use Apache Spark from R • Entry point in SparkContext • With SQLContext, dataframes can be created from local R data frames, Hive tables or other Spark data sources • Introduced with Spark 1.4
  • 26. SparkR: Creating DataFrames • From local data frames • From data sources like JSON • From Hive tables
  • 27. Useful tips • Use Spark SQL dataframes to write less code. Easier to avoid closure problems. • Be aware of closure issues while working in cluster mode. Use accumulator variables instead of locally defined methods • Utilize Spark SQL capability to automatically infer schema of JSON datasets SQLContext.read.json • Other than using command-line, IDEs like IntelliJ IDEA community edition can be used for free
  • 28. References • Spark pages: http://spark.apache.org/ • Databricks blog: https://databricks.com/blog • Spark summit: https://spark-summit.org/ • Additional Spark packages at: http://spark-packages.org/ • Example scripts: • https://github.com/apache/spark/blob/master/examples/src/main/pytho n/sql.py • https://github.com/apache/spark/blob/master/examples/src/main/r/data -manipulation.R • https://github.com/apache/spark/blob/master/examples/src/main/r/data frame.R • API docs: http://spark.apache.org/docs/latest/api/python/index.html • http://spark.apache.org/docs/latest/api/R/index.html • Using SparkR in Rstudio: http://www.r-bloggers.com/how-to-use-sparkr- within-rstudio/