Anda di halaman 1dari 118

Hadoop

Weekend

CETAX - All Rights Reserved


AGENDA DO EVENTO

PARTE 1 – BIG DATA PARTE 3 – INGESTÃO DE DADOS


 Conceitos e Fundamentos  Sqoop
 Ferramentas e Arquitetura  Pig
 Aplicações de Big Data  Hive

PARTE 2 – HADOOP PARTE 4 – PROCESSANDO DADOS


 Arquitetura Hadoop  Hive
 HDFS – Map Reduce  Spark
 YARN
 Blocks
 Comandos HDFS

CETAX - All Rights Reserved


APRESENTAÇÃO CETAX

• A Cetax é uma empresa de consultoria e treinamento especializada em


sistemas de Business Intelligence e Data Warehouse.

• Existe desde 2000 trabalhando exclusivamente com BI e DW.

• Nossos treinamentos são exclusivos sem cursos semelhantes no Brasil

• Outros cursos são ministrados em parcerias com outras empresas do


mercado ou mesmo profissionais que possuem experiência diferenciada

• Parceria Hortonworks (Hadoop), Talend (ETL), Tibco (Analytics)

CETAX - All Rights Reserved


APRESENTAÇÃO - INSTRUTOR

MARCO ANTONIO GARCIA


• 20 anos de experiência em TI, sendo 15 exclusivamente com Inteligência - Business
Intelligence e Data Warehouse.

• MBA pela FGV, Formado pela FATEC em Processamento de Dados.

• Certificado pelo Kimball University nos EUA, onde teve aula pessoalmente com
Ralph Kimball, um dos principais gurus do data Warehouse, treinamentos
realizados no TDWI, maior entidade de pesquisa de Data Warehouses do mundo.

• Vivência profissional em diversos projetos, passando por Bancos e Financeiras,


Construção, Serviços, Varejo, Marketing e outros.

CETAX - All Rights Reserved


A PALAVRA DO MOMENTO

CETAX - All Rights Reserved


LITERATURA DISPONÍVEL - BRASIL

CETAX - All Rights Reserved


LITERATURA DISPONÍVEL - EUA

CETAX - All Rights Reserved


BIG DATA = GRANDES DADOS?

• Muitas definições podem cercar o assunto :


– Alto Volume.
– Alta Velocidade.
– Diversas Fontes.

• Uma combinação de tudo isso e muito mais.

• Assim como BI, é um termo “guarda-chuva”.

CETAX - All Rights Reserved


MUITOS DADOS GRANDES

• Além dos sistemas utilizados em empresas de todos os portes, temos milhares


de outros dispositivos que geram dados diariamente :
– Em 2010 existiam 5 bilhões de celulares no mundo.
– Um avião Boeing pode gerar até 20 TB/hora para seus engenheiros
examinar em tempo real.
– Em pouco tempo teremos muito mais equipamentos ligados a internet
gerando informações para análise “internet das coisas”

CETAX - All Rights Reserved


BIG DATA = BIG BUSINESS

• Big Data = Big Business

• Todos os negócios de tecnologia serão


beneficiados pelo Big Data

CETAX - All Rights Reserved


3 Vs – UMA DEFINIÇÃO

• Volume – o volume crescente de dados em todas as áreas e empresas, Mb ->


Gb -> Tb -> Pb

• Velocidade – o tempo necessário para disponibilizar os dados para análise é


cada vez menor

• Variedade – a variedade de dados é cada vez maior, sensores, imagens, dados


não estruturados ou semi estruturados.

CETAX - All Rights Reserved


3 Vs – DETALHES

CETAX - All Rights Reserved


5 Vs – UMA DEFINIÇÃO

• VOLUME

• VELOCIDADE

• VARIEDADE

• VIRTUDE

• VALOR

CETAX - All Rights Reserved


10 Vs – É NECESSÁRIO?

• VAST - VASTO, AMPLO


• VOLUME - ALTO VOLUME
• VIGOROSITY - VIGOR
• VERIFIED - VERIFICADOS
• VEXINGLY - “ATORMENTADOR”
• VARIABLE - VARIAVEIS
• VERBOSE - “ELOQUENTE”
• VALUABLE - VALIOSOS
• VISUALIZED - VISUALIZADOS
• VELOCITY - VELOCIDADE

CETAX - All Rights Reserved


BIG DATA – DEFINIÇÃO SIMPLES

• Big Data representa um conjunto de dados que não pode mais ser
facilmente gerenciado ou analisado com as ferramentas atuais de
dados, métodos ou arquitetura disponível até então.

CETAX - All Rights Reserved


E ENTÃO?

• E então ?

• Quais softwares serão utilizados ?

• Quais devo aprender ?

CETAX - All Rights Reserved


CETAX - All Rights Reserved
CETAX - All Rights Reserved
DATA IS THE NEW OIL!

• “Dados são o novo Petróleo”

• No ano de 2012 a

• Como petróleo, precisam ser refinados !

CETAX - All Rights Reserved


FONTES PARA O BIG DATA

• Web log
• Click stream
• Sensor data
• Email
• Call center voice logs
• Images/video
• Dados RFID
• Dados de Localização e Geográficos
• Dados adquiridos no mercado

CETAX - All Rights Reserved


CURVA DE ADOÇÃO DO BIG DATA

CETAX - All Rights Reserved


EXEMPLOS POR SETOR

• Serviços de Informação – Imagens de Satélites


• Varejo – Otimização de Preço, Inteligência de Vídeo
• Utilities/Utilidades – Consumo em tempo real
• Propaganda – Content Targeting OnLine
• Seguros – Detecção de Fraudes
• Saúde – Diagnósticos e Detecção.
• Manufatura – Controle de Qualidade, Controle de Máquinas

CETAX - All Rights Reserved


APLICAÇÕES POSSÍVEIS – BIG DATA

• Machine Learning
• Sentiments
• Text Processing
• Image Processing
• Video Analytics
• Log Parsing
• Collaborative Filtering
• Context Search
• Email & Content

CETAX - All Rights Reserved


APLICAÇÕES POSSÍVEIS – BIG DATA

• Machine Learning :
– Aprendizado de Maquina

– Sistemas que podem aprender com os dados e tomar decisões


de acordo com modelos previamente estudados.

– Existem diversos algoritimos que podem ser aplicados em


Machine Learning.

CETAX - All Rights Reserved


APLICAÇÕES POSSÍVEIS – BIG DATA

• Sentiments :
– Sentimentos ou Análise de Sentimentos

– Também conhecida como Mineração de Opinião ou Opnion


Mining

– São algoritimos utilizados para identificar o “sentimento”


através de uma informação textual.

CETAX - All Rights Reserved


APLICAÇÕES POSSÍVEIS – BIG DATA

• Text Processing:
– Processamento de Textos

– Pode ser utilizado para identificação, reconhecimento ou


análise de dados através de textos processados.

– Pode ser usado na identificação de comportamentos ou


sentimentos

CETAX - All Rights Reserved


APLICAÇÕES POSSÍVEIS – BIG DATA

• Image Processing / Video Analytics:


– Imagens e Videos podem ser analisados em ferramentas de Big
Data.

– As imagens podem ser decompostas e atraves de processos de


reconhecimento, identificar pessoas, padroes suspeitos ou
mesmo padroes que possam ser analíticos.

– Os videos podem ser decompostos em uma série de imagens e


essas imagens processadas.

CETAX - All Rights Reserved


APLICAÇÕES POSSÍVEIS – BIG DATA

• Log Parsing
• Collaborative Filtering
• Context Search
• Email & Content

CETAX - All Rights Reserved


REQUERIMENTOS DO BIG DATA

• Load ( Carga )
• Structure ( Estrutura )
• Response ( Resposta )
• Complex Workload ( Processamentos Complexos )
• Economics ( Retorno ao Investimento )

CETAX - All Rights Reserved


DADOS POR VALIDADE PARA BIG DATA

CETAX - All Rights Reserved


COMO ATENDEMOS HOJE?

• Bancos de Dados Relacionais


• Ferramentas de ETL
• Ferramentas de BI

• Mas esse é o melhor ferramental?

• Com certeza não !

CETAX - All Rights Reserved


QUAL O IMPACTO DE TUDO ISSO NO DW ATUAL?

• Novos Tipos de Dados


• Novos Volumes
• Novas Análises
• Novas Cargas de Processamento
• Novos Métodos

Tudo isso = Menos Performance !

CETAX - All Rights Reserved


INOVAÇÕES SÃO NECESSÁRIAS

Categorias Novas Tecnologias


Infra Estrutura Big Data e Data Warehouse Appliances
Tecnologias In-Memory
SSD Storage
Fast Networks
Cloud Computing
Tecnologias Móveis
Softwares In-Memory Databases
Hadoop, Cassandra e NoSQL Databases
Colunar DBMS
ETLs com integração Hadoop – Informatica, Talend, etc.
Algoritimos Mahout
Arquiteturas Pré- IBM, Teradata, Kognitio, EMC, Cloudera, HortonWorks, Cirro,
Configuradas Intel, Cisco UCS, Pivotal, Oracle , MapR

CETAX - All Rights Reserved


NOSQL

• NoSQL = Not Only SQL


• Baseado no Teorema CAP
• Consistency
• Availability
• Partition Tolerance
• Usualmente não requer tabelas fixas no schema nem sempre usa o
conceito de join
• Todos NoSQL “relaxa” uma ou mais as propriedades do ACID

CETAX - All Rights Reserved


TEOREMA CAP

• Consistency: todos os nodes vem os mesmos dados ao mesmo


tempo

• Availability: Garantia que cada request receba uma resposta de


dados

• Partition Tolerance: O sistema continua funcionando mesmo com


alguma perda de partição ou partes do sistema

CETAX - All Rights Reserved


NOSQL

• Alguma variações de NoSQL Databases :


• XML ( myXMLB, Tamino, Sedna )

• Wide Column (Cassandra, Hbase, Big Table)

• Key/Value (Redis, Memcached comBerkley DB)

• Graph ( neo4j, InfoGrid )

• Document Store ( CouchDB, MongoDB )

CETAX - All Rights Reserved


PANORAMA DE BANCO DE DADOS

CETAX - All Rights Reserved


UMA APOSTA? HADOOP!

CETAX - All Rights Reserved


HADOOP 1 x HADOOP 2 (YARN)

YARN é uma re-arquitetura do Hadoop, que permite multiplas aplicações


rodarem na mesma plataforma.

HADOOP 1.x HADOOP 2.x


MapReduce Others
(data processing) (data processing)
MapReduce
(cluster resource management YARN
& data processing) (cluster resource management)

HDFS HDFS
(redundant, reliable storage) (redundant, reliable storage)

CETAX - All Rights Reserved


HADOOP SURGE COMO ALTERNATIVA

• Criado dentro do Yahoo em 2005.

• O nome Hadoop não é um acrônimo, é o nome do Elefante de


brinquedo do filho de Doug Cutting.

• O Hadoop tem como base um file system para armazenamento


rápido e barato de dados !

• Tem como objetivo o processamento de grandes datasets de dados


com modelos simples de programação

CETAX - All Rights Reserved


PLAYERS DE MARCADO

• Apache Software Foundation • Oracle Big Data Appliance


• Cloudera • Intel Hadoop Distribution
• HortonWorks • MapR
• MongoDB • Datastax
• IBM Big Insights • Rainstor
• EMC Pivotal • QueryIO
• Teradata Aster

CETAX - All Rights Reserved


CIÊNCIA DE DADOS

• Estudo disciplinado dos dados e informações inerentes ao negócio e


todas as visões que podem cercar um determinado assunto.
• Ciência que estuda as informações, seu processo de captura,
transformação, geração e análise de dados.
• A Ciência de dados envolve diversas disciplinas como :
• Computação
• Estatística
• Matemática
• Conhecimento do Negócio

CETAX - All Rights Reserved


CIÊNCIA DE DADOS

CETAX - All Rights Reserved


REQUISITOS ESPERADOS DO CIENTISTA DE DADOS

CETAX - All Rights Reserved


DEFINIÇÃO – CIENTISTA DE DADOS

• Profissional Multidisciplinar responsável por transformar dados em


informações ou produtos de informações dentro de uma corporação.

• Deve ser responsável pela formulação dos problemas, escolha de


modelos de simulação e estatística e entrega dos produtos de dados.

CETAX - All Rights Reserved


DATA SCIENTIST x BUSINESS ANALYST x DATA ANALYST

• Data Scientist – Participa da formulação do problema, hipóteses de


resolução e análise de resultados.

• Business Analyst – Analisa os dados gerados em relação ao negócio


ou empresa avaliada

• Data Analyst – responsável por analisar os dados disponibilizados em


busca de solução para o problemas enfrentados

CETAX - All Rights Reserved


QUERO TRABALHAR COM BIG DATA

• Para trabalhar com Big Data acreditamos que o melhor caminho seria
conhecer as ferramentas utilizadas
• Ter perfil misto : técnico e negócios
• Conhecer de Business Inteligence e Data Warehouse
• Entender os processos da empresa
• Conhecer estatística e matemática

CETAX - All Rights Reserved


PAPEIS E FUNÇÕES

• Vemos 3 papéis claros:


• Cientista ou Analista de Dados

• Desenvolvedor

• Administrador

CETAX - All Rights Reserved


ANALISTA DE DADOS

• Responsável por atender as demandas das áreas de negócio ou


planejamento da empresa.
• Participa da formulação dos problemas e respostas.
• Nível mais próximo ao negócio
• Deve conhecer as ferramentas de consulta e acesso aos dados.
• Deveria conhecer estatística

CETAX - All Rights Reserved


DESENVOLVEDOR

• Responsável por Desenvolver os processos necessários para geração


dos dados.
• Processos de Captura, Transformação e Carga de Dados.
• Deve conhecer tecnicamente as ferramentas envolvidadas
• Deve conhecer sobre programação
• Será responsável pelo desenvolvimento de novas rotinas e processos.

CETAX - All Rights Reserved


ADMINISTRADOR

• Responsável por manter os ambientes e ferramentas funcionando da


melhor maneira.
• Deve conhecer sobre os sistemas operacionais utilizados,
principalmente Linux.
• Deve conhecer sobre arquitetura de hardware e redes para garantir a
melhor performance.
• Deve conhecer sobre os processos de Tunning das ferramentas.

CETAX - All Rights Reserved


CONHECIMENTOS TÉCNICOS PARA TRABALHAR COM BIG DATA

• Programação – as ferramentas ainda são pouco automatizadas na


geração de código.

• Linux – a maioria dos softwares rodam em Linux, é necessário


conhecer comandos básicos para execução de processos.
• Modelagem de Dados

CETAX - All Rights Reserved


CONHECIMENTOS TÉCNICOS PARA TRABALHAR COM BIG DATA

• Conhecer sobre o negócio ou sobre os processos da empresa.

• Conhecer ou ter noções mínimas de estatística e matemática


aplicada a dados.

CETAX - All Rights Reserved


Hadoop Weekend

PARTE 2 – ENTENDENDO HADOOP


ARMAZENAMENTO E PROCESSAMENTO

CETAX - All Rights Reserved


Atividade
Configurar acessos as VM’s
( utilizar Apêndice do Caderno do Aluno )

CETAX - All Rights Reserved


Exercício 1
Colocando a VM no ar e conhecendo suas
principais estruturas

CETAX - All Rights Reserved


Core
NameNode
HDFS
Worker Node
/directory/structure/in/
DataNode
HDFS
NodeManage
r
YARN
+ memory.txt
ResourceManager
YARN

Disk, CPU, Memory Resource management +


scheduling
Hadoop NN
daemon
User RM

application

CETAX - All Rights Reserved


WHAT IS HDFS?

“I have a 200 TB file


that I need to store.”

“Wow - that is big data! I


will need to distribute
that across a cluster.”

“Sounds risky! What


Hadoop Client happens if a drive
fails?” HDFS

“No need to worry! I am


designed for failover.”

CETAX - All Rights Reserved


THE NameNode

1. When the NameNode starts, it reads 2. The transactions in edits are merged with
fsimage and edits files from disk. fsimage, and edits is emptied.

3. A client application creates a new file in


HDFS.
fsimage edits hadoop fs -put foo.log
hdfs snapshots hdfs journals bar/foo.log

4. The NameNode logs that


transaction in the edits file.
NameNode

CETAX - All Rights Reserved


THE NameNodes

NameNode

“Hey DataNode1, “I’m here too! And


“I’m still here! This is Replicate block 123 to here is my latest
my latest heartbeat.” DataNode 3.” heartbeat.”

DataNode 1 DataNode 2 DataNode 3 DataNode 4

123 123 123

CETAX - All Rights Reserved


1. Client sends a request to the
NameNode to add a file to
HDFS.
NameNode
2. NameNode gives client a
lease to the file path.

3. For every block, the client will request the NameNode to provide a new blockid
and a list of destination DataNodes.

4. The client will write the block directly to the first DataNode in the list.

DataNode 1 DataNode 2 DataNode 3

5. The first DataNode pipelines the replication to the next DataNode in the list.
CETAX - All Rights Reserved
Exercício 2
Entendendo HDFS e Bloco de Armazenamento

CETAX - All Rights Reserved


WHAT IS MAPREDUCE?

Break a large problem into sub-solutions


Read & ETL
Data Map Process
Data
Data
Shuffle & Sort
Data
Aggregation
Data Map Process Reduce Data
Data Process
Data
Data

Data Map Process


Data
Data
Reduce
Data Data
Process
Data Map Process
Data
Data
Data
Data
Data Map Process
Data
Data

CETAX - All Rights Reserved


WORDCOUNT IN MAPREDUCE
1 2
constitution.txt The mappers read the file’s The lines of text are split
blocks from HDFS line-by-line into words and output to
the reducers
HDFS We the people, in order to form a... <We, 1> <order, 1>
<the,1> <to,1>
<people,1> <form,1>
4 <in,1> <a,1>
The reducers add up the
“1’s” and output the word <We, (1,1,1,1)> 3
and its count The shuffle/sort phase
<the, (1,1,1,1,1,1,1,...)>
combines pairs with the
<people,(1,1,1,1,1)> same key
<We,4> <form, (1)>
<the,265>
HDFS <people,5>
<form,1>
CETAX - All Rights Reserved
Map Phase Shuffle/Sort Reduce Phase
DataNode DataNode

SELECT word, COUNT(*) GROUP BY (word)


FROM constitution
Mapper Hive/Pig compile as Reducer

Reduce side function


WHERE….
DataNode DataNode
Data is shuffled
across the network
Mapper
and sorted ORDER BY
JOIN
DataNode DISTINCT DataNode

Examples of more
Mapper Reduce side Reducer

functions
CETAX - All Rights Reserved
7
1 Input split Mapper output =
Reducer input
Spill files are
merged into a
6
single file

The InputFormat 5 Records are


generates <k1,v1> 2
pairs sorted and spilled
to disk when the
buffer reaches a
3 4
MapOutputBuffer threshold
Mapper
<k2,v2> <k2,v2>
<k2,v2> <k2,v2>
The map method
<k2,v2> <k2,v2>
outputs <k2,v2> <k2,v2> <k2,v2>
pairs <k2,v2> <k2,v2>
NodeManager

CETAX - All Rights Reserved


In-memory 2.
Mapper output = buffer
Spill files
Reducer input
3.
Merged
NodeManager
input NodeManager

4.
Mapper output = 5.
Reducer input Reducer HDFS

NodeManager In-memory
buffer
Spill files
Mapper output =
Reducer input Merged
1. The Reducer input NodeManager

NodeManager fetches the data


from the Mappers
Reducer HDFS
© Hortonworks Inc. 2013
LIFECYCLE OF A YARN APPLICATION

2
The AsM finds an appropriate
Client submits an 1
NodeManager
application
ResourceManager

AM asks RM for resources. RM 4 3


provides a list of Containers to NodeManager
AM NodeManager creates an
ApplicationMaster
5
ApplicationMaster
Containers execute their given
task on NodeManagers in the
cluster

CETAX - All Rights Reserved


A CLUSTER VIEW EXAMPLE
ResourceManager

Scheduler

AsM

Node 1 Node 2 Node 3


NodeManager NodeManager NodeManager

Container AM Container

Node 4 Node 5 Node 6


NodeManager NodeManager NodeManager

Container AM

Node 7 Node 8 Node 9


NodeManager NodeManager NodeManager
Container Container
Container

CETAX - All Rights Reserved


Exercício 3
Executando Wordcount com MapReduce

CETAX - All Rights Reserved


Hadoop Weekend

PARTE 3 – INTEGRAÇÃO DE DADOS

CETAX - All Rights Reserved


INTEGRAÇÃO DE DADOS

MapReduce

nfs gateway
Hadoop WebHDFS
hadoop fs -put
Vendor Connectors Hue Explorer

CETAX - All Rights Reserved


THE HADOOP CLIENT

• The put command to uploading data to HDFS


• Perfect for inputting local files into HDFS
– Useful in batch scripts
• Usage:
hadoop fs –put mylocalfile /some/hdfs/path

• POSIX utility commands such as ls, mv, cp, touch, cat, mkdir are also supported
• Full list of commands
hadoop fs

CETAX - All Rights Reserved


OVERVIEW OF SQOOP: DATABASE IMPORT/EXPORT

Relational Enterprise Document-based


Database Data Warehouse Systems

1. Client executes a sqoop 3. Plugins provide connectivity to various data


command sources

2. Sqoop executes the command Map Hadoop Cluster


as a MapReduce job on the tasks
cluster (using Map-only tasks)

CETAX - All Rights Reserved


Exercício 4
Carregando Dados com Sqoop

CETAX - All Rights Reserved


Hadoop Weekend

PARTE 4 – PROCESSAMENTO DE DADOS

CETAX - All Rights Reserved


HADOOP ECOSYSTEM: PIG

• An engine for executing programs on top of Hadoop


• It provides a language, Pig Latin, to specify these programs

CETAX - All Rights Reserved


WHY USE PIG?

• Maybe we want to join two datasets, from different sources, on a common


value, and want to filter, and sort, and get top 5

CETAX - All Rights Reserved


Exercício 5
Executando Scripts com Pig

CETAX - All Rights Reserved


HADOOP ECOSYSTEM: HIVE
Use existing SQL tools and existing SQL processes

Store and query all data in Hive

NN
Weblog
RM

Sensor

Operational/MPP

Mobile

CETAX - All Rights Reserved


WHAT IS HIVE?

• Data warehouse system for Hadoop


• Create schemas/table definitions that point to data in Hadoop
• Treat your data in Hadoop as tables
• SQL 92
• Interactive queries at scale

CETAX - All Rights Reserved


HIVEQL

SQL Datatypes SQL Semantics


INT SELECT, LOAD, INSERT from query
TINYINT/SMALLINT/BIGINT Expressions in WHERE and HAVING
BOOLEAN GROUP BY, ORDER BY, SORT BY
FLOAT CLUSTER BY, DISTRIBUTE BY
DOUBLE Sub-queries in FROM clause
STRING GROUP BY, ORDER BY
BINARY ROLLUP and CUBE
TIMESTAMP UNION
ARRAY, MAP, STRUCT, UNION LEFT, RIGHT and FULL INNER/OUTER JOIN
DECIMAL CROSS JOIN, LEFT SEMI JOIN
CHAR Windowing functions (OVER, RANK, etc.)
VARCHAR Sub-queries for IN/NOT IN, HAVING
DATE EXISTS / NOT EXISTS
INTERSECT, EXCEPT

CETAX - All Rights Reserved


HIVE ARCHITECTURE
Hive
MR/Tez
CLI 2 Compiler
Hive
SQL JDBC / HiveServer2 Hive Optimizer
1 ODBC

Web UI MetaStore Executor


(MySQL, Postgresql, Oracle)

Data-local processing 3
Hadoop
1 User issues SQL query
2 Hive parses and plans query MapReduce or Tez Job
Query converted to MapReduce
and executed on Hadoop
Data Data Data
3

CETAX - All Rights Reserved


HADOOP ECOSYSTEM: HCatalog

• Hive component
• Glue between Pig & Hive
– Schema visibility to
Pig Scripts & MapReduce
• REST API to
– Access Hive schemas
– Submit DDL
– Launch Hive queries
– Launch Pig jobs
– Launch MR
– Notifications to message broker

CETAX - All Rights Reserved


OVERVIEW OF THE HIVE ODBC DRIVER

BI Tools Analytics Reporting

Hive ODBC Driver

http://hortonworks.com/hdp/addons
CETAX - All Rights Reserved
Hadoop Weekend

PARTE 5 - INTRODUCING APACHE SPARK

CETAX - All Rights Reserved


WHAT IS APACHE SPARK?

• Apache open source project, originally developed at AmpLab at UC-Berkeley


– 2009: Research project; BDAS (Berkley Data Analysis Stack)
– Jun 2013: Accepted into Apache Incubator
– Feb 2014: Became a top-level Apache project
– Dec 2014: Included in HDP 2.2
• A general data processing engine, focused on in-memory distributed computing
use-cases
• APIs in Scala, Python and Java
– Recently API for R was introduced

CETAX - All Rights Reserved


THE SPARK ECOSYSTEM

CETAX - All Rights Reserved


WHY SPARK?

• Elegant Developer APIs: Data Frames/SQL, Machine Learning, Graph


algorithms and streaming
– Scala, Python, Java and R
– Single environment for importing, transforming, and exporting
data
• In-memory computation model
– Effective for iterative computations
• High level API
– Allows users to focus on the business logic and not internals

CETAX - All Rights Reserved


WHY SPARK CONT.

• Supports wide variety of workloads


– Mllib for Data Scientists
– Spark SQL for Data Analysts
– Spark Streaming for micro batch use cases
– Spark Core, SQL, Streaming, Mllib, and GraphX for Data Processing
Applications
• Integrated fully with Hadoop and an open source tool
• Faster than MapReduce

CETAX - All Rights Reserved


SPARK vs MAPREDUCE pyspark

• Higher level API


• In-memory data storage Java MapReduce

– Up to 100x performance
improvement

CETAX - All Rights Reserved


SPARK vs MAPREDUCE CONT

• Why is Spark faster?


– Caching data to memory can avoid extra reads from disk
– Scheduling of tasks from 15-20s to 15-20ms
– Resources are dedicated the entire life of the application
– Can link multiple maps and reduces together without having to
write intermediate data to HDFS
– Every reduce doesn’t require a map

CETAX - All Rights Reserved


Hadoop Weekend

PARTE 6 - PROGRAMMING WITH APACHE SPARK

CETAX - All Rights Reserved


HOW TO START USING APACHE SPARK?

• The Spark Shell provides an interactive way to learn Spark, explore


data, and debug applications
• Available for python and scala
– pyspark
– spark-shell
• REPL

CETAX - All Rights Reserved


THE SPARK CONTEXT

• Main entry point for Spark applications


• All Spark applications require one
• The SparkContext has a few responsibilities
– Represent the connection to a Cluster
– Used to create RDDs, accumulator and broadcast variables on
the cluster
• The REPLs automatically create one for you
– In Spark 1.3 and on, the shell creates a SQL context too

CETAX - All Rights Reserved


WORKING WITH THE SPARK CONTEXT

Attributes:
• sc.appName: Spark application name
• sc.master: Spark Master (local, yarn-client, etc)
• sc.version: Version of Spark being used
Functions:
• sc.parallelize(): create an RDD from local data
• sc.textFile(): create RDD from a text file in HDFS
• sc.stop(): stop the spark context

CETAX - All Rights Reserved


THE RESILIENT DISTRIBUTED DATASET

• An Immutable collection of objects (or records) that can be


operated on in parallel
– Resilient: can be recreated from parent RDDs - An RDD keeps its
lineage information
– Distributed: partitions of data are distributed across nodes in
the cluster
– Dataset: a set of data that can be accessed
– Each RDD is composed of 1 or more partitions - The user can
control the number of partitions - More partitions => more
parallelism
CETAX - All Rights Reserved
CREATE NA RDD

• Load data from a file (HDFS, S3, Local, etc)


– From a single file
rdd1 = sc.textFile(“file:/path/to/file.txt”)
rdd2 =
sc.textFile(“hdfs://namenode:8020/mydata/data.txt”)
– Also accepts a comma separated list of files, or a wildcard list of files
rdd3 = sc.textFile(“mydata/*.txt”)
rdd4 = sc.textFile(“data1.txt,data2.txt”)

CETAX - All Rights Reserved


ACTIONS – count()

• The count() action returns the number of elements in the RDD

data = [5, 12, -4 , 7, 20]


rdd = sc.parallelize(data)
rdd.count()

The output is: 5

CETAX - All Rights Reserved


SPARK ACTIONS: EXAMPLES

Dataset:[5, 12, -4 , 7, 20]

rdd.first(): 5

rdd.take(3): [5, 12, -4]

rdd.saveAsTextFile(“myfile”)

CETAX - All Rights Reserved


TRANSFORMATIONS: filter()

• Keep some elements based on a predicate

rdd=sc.parallelize([1, 2, 3, 4, 5])
rdd.filter( lambda x: x%2 == 0).collect()
[2, 4]

rdd.filter( lambda x: x<3).collect()


[1, 2]

CETAX - All Rights Reserved


Exercício 6
Iniciando com Apache Spark

CETAX - All Rights Reserved


Hadoop Weekend

PARTE 7 - SPARK SQL AND DATAFRAMES

CETAX - All Rights Reserved


SPARK SQL OVERVIEW

• A module built on top of Spark Core


• Provides a programming abstraction for distributed processing of
large-scale structured data in Spark
• Data is described as a DataFrame with rows, columns and a schema
• Data manipulation and access is available with two mechanisms
– SQL Queries
– DataFrames API

CETAX - All Rights Reserved


THE DATAFRAME ABSTRACTION

• A DataFrame is inspired by the dataframe concept in R (dplr,


Dataframe) or Python (pandas), but stored using RDDs underneath
in a distributed manner
• A DataFrame is organized into named columns
– Underneath: an RDD of “Row” objects
• The DataFrame API is available in Scala, Java, Python, and R

CETAX - All Rights Reserved


THE DATAFRAME VISUALLY

CETAX - All Rights Reserved


DATAFRAMES CAN COME FROM VARIOUS SOURCES

• DataFrames from HIVE data


– Reading/writing HIVE tables

• DataFrames from files:


– Built-in: JSON, JDBC, Parquet, HDFS
– External plug-in: CSV, HBASE, Avro, memsql, elasticsearch

CETAX - All Rights Reserved


EXAMPLE: USING THE DATAFRAMES API

from pyspark.sql import HiveContext


hc = HiveContext(sc)

hc.sql(“use demo”)
df1 = hc.table(“crimes”)
.select(“year”, “month”, “day”, “category”)
.filter(“year > 2014”).head(5)

CETAX - All Rights Reserved


SAME EXAMPLE, USING SQL SYNTAX

from pyspark.sql import HiveContext


hc = HiveContext(sc)

hc.sql(“use demo”)
df1 = hc.sql(“““
SELECT year, month, day, category
FROM crimes
WHERE year > 2014”””).head(5)

CETAX - All Rights Reserved


DATAFRAMES vs SPARK-CORE?

• Spark-SQL uses an optimization engine (Catalyst)


• Catalyst understands the structure of data & semantics of
operations and performs optimizations accordingly

CETAX - All Rights Reserved


CREATING A DATAFRAME: FROM A TABLE IN HIVE

• Load the entire table


df=hc.table(“patients”)

• Load using a SQL Query


df1 = hc.sql(“SELECT * from patients WHERE age>50”)
df2 = hc.sql(“““
SELECT col1 as timestamp, SUBSTR(date,1,4) as year,
event
FROM events
WHERE year > 2014”””)

CETAX - All Rights Reserved


CREATING A DATAFRAME: FROM A FILE

• From a JSON file


df = hc.read.json(“somefile.json”)
df = hc.read.format(“json”).load(“somefile.json”)

• From Parquet file


df = hc.read.parquet(“somefile.parquet”)

• From a CSV file:


df = hc.read.format(“com.databricks.spark.csv”)
.options(header=‘true’).load(“somefile.csv”)

CETAX - All Rights Reserved


EXEMPLE DATAFRAMES

CETAX - All Rights Reserved


DATAFRAME OPERATIONS: INSPECTING CONTENT (1)

• first() – return the first row


• take(n) – return n rows

df1.first()
Row(age=23, cid=u’104’, name=u’Bob’, state=u’nc’)

df1.take(2)
[Row(age=45, cid=u’104’, name=u’Ram’, state=u’fl’)
Row(age=15, cid=u’102’, name=u’Bob’, state=u’ny’)]

CETAX - All Rights Reserved


DATAFRAME OPERATIONS: INSPECTING CONTENT (2)

• limit(n): reduce the dataframe to n rows


– Result is still a dataframe, not a python result list
• show(n): prints the first n rows to the console

CETAX - All Rights Reserved


DATAFRAME OPERATIONS: REMOVING DUPLICATES

• Remove duplicate rows

df1.distinct().show()

• Removing duplicate rows by key

df1.drop_duplicates([“name”]).show()

CETAX - All Rights Reserved


Exercício 7
Explorando Spark SQL

CETAX - All Rights Reserved


FINALIZANDO

• Perguntas ?
• Não deixem de acessar nosso site e se cadastrem para
as promoções, vagas: www.cetax.com.br

MUITO OBRIGADO!

CETAX - All Rights Reserved

Anda mungkin juga menyukai