SlideShare una empresa de Scribd logo
1 de 53
Descargar para leer sin conexión
13 Junio 2016
Fun[ctional] Spark
with Scala
Quienes somos
Fun[ctional] Spark with Scala
José Carlos García Serrano Arquitecto Big Data en Stratio.
Granadino e ingeniero por la ETSII, master de Big
Data en la UTad, certificado en Spark y AWS
Amante de las nuevas tecnologías y de las
arquitecturas basadas en Big Data
FanBoy de cosas como:
● Scala
● Spark
● Akka
● MongoDB
● Cassandra
Pero todos tenemos un pasado:
● Delphi
● C++
● BBDD SQL
● Hadoop
Quienes somos
Fun[ctional] Spark with Scala
David Vallejo Navarro Desarrollador Scala en Stratio.
Trabajando con Scala desde 2012 (si...cuando nadie
sabía qué era eso de Scala)
Actualmente cursando un máster en Investigación
informática.
He trabajado en:
● DSLs para la creación de aplicaciones
sociales
● Sistemas distribuidos
● Aplicaciones WEB
● Migración de antiguas arquitecturas a Scala
● Y ahora, Big Data!
Ah! Y tengo un blog de Scala: www.scalera.es
José Carlos García Serrano
Arquitecto Big Data
jcgarcia@stratio.com
CONTACTO
ÍNDICE
INTRODUCCIÓN1
2
3
VENTAJAS DE SCALA EN SPARK
DESVENTAJAS DE SCALA EN SPARK4
David Vallejo Navarro
Desarrollador Big Data
dvallejo@stratio.com
SCALA AVANZADO CON SPARK
1 INTRODUCCIÓN
Fun[ctional] Spark with Scala
¿Qué es Scala?
2003 - Martin Odersky, estando borracho, ve un
anuncio de mantequilla de cacahuete Reese sobre
el chocolate y tiene una idea. Crea Scala, un
lenguaje que unifica las construcciones de los
lenguajes funcionales y los orientados a objetos.
Consigue cabrear a los partidarios de ambos tipos
de lenguaje que declaran al unísono la jihad.
Incomplete, and Mostly Wrong History of Programming Languages por James Iry
Fun[ctional] Spark with Scala
¿Qué es Scala?
CARACTERÍSTICAS PRINCIPALES
CORRE EN LA JVM1
2
3
MULTIPARADIGMA
TIPADO ESTÁTICO
INFERENCIA DE TIPOS4
5 HERENCIA MÚLTIPLE
Fun[ctional] Spark with Scala
Scala en Noviembre de 2014
72.992 miembros
319 meetups
72.992 miembros
319 meetups
Fun[ctional] Spark with Scala
Scala en Junio de 2016 (1 año y 7 meses después)
233.375 miembros
570 meetups
Fun[ctional] Spark with Scala
Algunas empresas que usan Scala
Fun[ctional] Spark with Scala
Spark Scala
+ =
2 VENTAJAS DE
SCALA EN
SPARK
Fun[ctional] Spark with Scala
2. VENTAJAS
2.1 Ventajas de usar Scala
• Uso de JVM
-> Librerías - Polimorfismo - Gestión
• Estáticamente tipado
-> Optimización del uso de memoria y de los algoritmos aplicados
• Modularidad
-> Grandes proyectos entendibles por humanos
• Sintaxis simple y rápido desarrollo
-> Programación funcional, poco código y simplicidad
• Multi-threading y concurrencia
-> Akka y la programación funcional son nuestros amigos
Fun[ctional] Spark with Scala
Los inicios como padawan scalero son duros y no puros ...
Fun[ctional] Spark with Scala
2. VENTAJAS
Java??
Ventajas
• trait JavaNoMola {
val advantages : Seq[String] = ???
}
Desventajas
• No data-centric language
• Líneas de código infinitas
• Difícil uso de colecciones
• Var = efectos de lado
• Concurrencia descontrolada
Python??
Ventajas
• Data-centric language
• Fácil uso de colecciones
Desventajas
• Tipado dinámico
• Compilado mejor que interpretado
Performance - Errores
• No es modular
• Mala integración con Hadoop
• Api limitada de Streaming
Y por qué no en C ...
Fun[ctional] Spark with Scala
2. VENTAJAS
Fun[ctional] Spark with Scala
2. VENTAJAS
Probablemente en un futuro veremos a Spark como la colección de
elementos distribuidos de Scala
Fun[ctional] Spark with Scala
2. VENTAJAS
2.2 Ventajas de usar Scala en Spark
• Escrito en Scala
• RDD es una colección distribuida, funciones conocidas map, flatMap, groupBy, foreach, etc …
• Lambda va de serie
• RDD tipados -> Datasets tipados y no tipados
• Poco código para realizar ETLs y apps sencillas
• Datos inmutables
• Efectos de lado minimizados (Closure)
• Evaluación perezosa (Lazy)
Fun[ctional] Spark with Scala
2. VENTAJAS
Funciones conocidas por cualquier escalero ...
def flatMap[U: ClassTag](f: T => TraversableOnce[U]): RDD[U] = withScope {
val cleanF = sc.clean(f)
new MapPartitionsRDD[U, T](this, (context, pid, iter) => iter.flatMap(cleanF))
}
private[spark] class MapPartitionsRDD[U: ClassTag, T: ClassTag](
var prev: RDD[T],
f: (TaskContext, Int, Iterator[T]) => Iterator[U], // (TaskContext, partition index, iterator)
preservesPartitioning: Boolean = false)
extends RDD[U](prev) {
override def compute(split: Partition, context: TaskContext): Iterator[U] =
f(context, split.index, firstParent[T].iterator(split, context))
Fun[ctional] Spark with Scala
Fun[ctional] Spark with Scala
2. VENTAJAS
val textFile = sc.textFile("hdfs://...")
val counts = textFile.flatMap(line => line.split(" "))
.map(word => (word, 1))
.reduceByKey(_ + _)
JavaRDD<String> textFile = sc.textFile("hdfs://...");
JavaRDD<String> words = textFile.flatMap(new FlatMapFunction<String, String>() {
public Iterable<String> call(String s) { return Arrays.asList(s.split(" ")); }
});
JavaPairRDD<String, Integer> pairs = words.mapToPair(new PairFunction<String, String, Integer>() {
public Tuple2<String, Integer> call(String s) { return new Tuple2<String, Integer>(s, 1); }
});
JavaPairRDD<String, Integer> counts = pairs.reduceByKey(new Function2<Integer, Integer, Integer>() {
public Integer call(Integer a, Integer b) { return a + b; }
});
Java
Típico word count, pero refleja la realidad … Scala vs Java vs Python
Scala Python
text_file = sc.textFile("hdfs://...")
counts = text_file.flatMap(lambda line: line.split(" ")) 
.map(lambda word: (word, 1)) 
.reduceByKey(lambda a, b: a + b)
Fun[ctional] Spark with Scala
Fun[ctional] Spark with Scala
2. VENTAJAS
Nuestra querida inmutabilidad ...
• Mutabilidad y concurrencia no mola -> Efectos de lado
• Al ser inmutable un RDD puede ser recreado en cualquier momento
• Difícil mantenimiento de datos que mutan -> update de memoria y disco -> Pésimo performance
• Queremos programación funcional y transformaciones que son funciones
Fun[ctional] Spark with Scala
2. VENTAJAS
Lazy?? mismo concepto de una variable lazy de scala pero en RDD
• Todas las transformaciones se van añadiendo al DAG de operaciones
• Solo son ejecutadas cuando realizamos una acción
• Se computan las transformaciones de las que depende la acción
• Las que no dependan de la acción no son computadas
Odersky querría este concepto para sus colecciones ;)
Fun[ctional] Spark with Scala
def collect(): Array[T] = withScope {
val results = sc.runJob(this, (iter: Iterator[T]) => iter.toArray)
Array.concat(results: _*)
}
def map[U: ClassTag](f: T => U): RDD[U] = withScope {
val cleanF = sc.clean(f)
new MapPartitionsRDD[U, T](this, (context, pid, iter) => iter.
map(cleanF))
}
def runJob[T, U: ClassTag](
rdd: RDD[T],
func: (TaskContext, Iterator[T]) => U,
partitions: Seq[Int],
resultHandler: (Int, U) => Unit): Unit = {
if (stopped.get()) {
throw new IllegalStateException("SparkContext has been shutdown")
}
val callSite = getCallSite
val cleanedFunc = clean(func)
logInfo("Starting job: " + callSite.shortForm)
if (conf.getBoolean("spark.logLineage", false)) {
logInfo("RDD's recursive dependencies:n" + rdd.toDebugString)
}
dagScheduler.runJob(rdd, cleanedFunc, partitions, callSite, resultHandler, localProperties.get)
progressBar.foreach(_.finishAll())
rdd.doCheckpoint()
Fun[ctional] Spark with Scala
2. VENTAJAS
2.3 Optimizaciones en Scala
Tungsten
● Serialización
● DataSets
DataFrames
● UDFs más eficientes que en Python
MLlib
● Coste adicional de convertir Python objects a Scala objects
Recordemos el meetup de Fun[ctional] Spark with Scala ...
Fun[ctional] Spark with Scala
2. VENTAJAS
Y antes de spark 1.6 ...
Fun[ctional] Spark with Scala
2. VENTAJAS
desde Spark 1.4 tungsten ya optimizaba algunas funciones de
DataFrames de Scala
3 SCALA
AVANZADO
CON SPARK
Fun[ctional] Spark with Scala
3. Scala avanzado
Fun[ctional] Spark with Scala
3.1 Implícitos
def mean(xs: RDD[Int]): Double =
xs.sum / xs.count
mean(rdd)
Queremos calcular la media de un RDD:
Fun[ctional] Spark with Scala
3.1 Implícitos
Implícitos: partes de código que se ejecutan sin ser llamados
Fun[ctional] Spark with Scala
3.1 Implícitos
implicit val timeout = 5000
def tryConnection(dbUri: String)(implicit timeout: Int) = ???
tryConnection("127.0.0.1/8080")
case class Point(x: Int, y: Int)
implicit def tupleToPoint(tuple: (Int, Int)): Point = Point(tuple._1, tuple._2)
def sumPoints(p1: Point, p2: Point) = Point(p1.x + p2.x, p1.y + p2.y)
sumPoints(Point(1, 2), (3, 4))
Valores implícitos
Funciones implícitas
Fun[ctional] Spark with Scala
3.1 Implícitos
implicit class RichSparkRDD(rdd: RDD[Int]) {
def mean: Double = rdd.sum / rdd.count
}
rdd.mean //new RichSparkRDD(rdd).mean
Podemos utilizar una implicit class para expandir funcionalidad:
Fun[ctional] Spark with Scala
3.2 Funciones de orden superior
Funciones que reciben funciones y/o devuelven funciones
Fun[ctional] Spark with Scala
3.2 Funciones de orden superior
type Term = Int
type Result = Int
type Operation = (Term, Term) => Result
def add: Operation = (n1, n2) => n1 + n2
def sub: Operation = (n1, n2) => n1 - n2
def calculate(n1: Term, n2: Term)(f: Operation): Result = f(n1, n2)
calculate(2, 5)(add)
calculate(1, 6)((n1, n2) => n1 * n2)
Construyendo una calculadora
Fun[ctional] Spark with Scala
3.2 Funciones de orden superior
def withSparkContext[T](name: String)(blockCode: SparkContext => T): T = {
val sparkConf = new SparkConf().setAppName(name).setMaster("local[4]")
val sc = new SparkContext(sparkConf)
val result = blockCode(sc)
sc.stop()
result
}
¿Y en Spark…?
withSparkContext("Meetup SDK") { sc =>
val myRDD = sc.parallelize(List(1, 2, 3, 4))
// ...
}
Fun[ctional] Spark with Scala
3.3 For comprehension
Map, flatMap, syntactic sugar ….
Fun[ctional] Spark with Scala
3.3 For comprehension
Métodos map y flatMap
val myRDD = sc.parallelize(List(1, 2, 3, 4))
myRDD map (_ + 1) //RDD(2, 3, 4, 5)
myRDD flatMap (i => List(i - 1, i + 1)) // RDD(0, 2, 1, 3, 2, 4, 3, 5)
Fun[ctional] Spark with Scala
3.3 For comprehension
Iterando sobre una colección de tweets
case class Tweet(id: Int, content: String, retweets: Int, user: String)
case class VipUserFactor(id: Int, factor: Double)
tweets.flatMap ( tweet =>
vipUsers.filter(_.id == tweet.id).map ( vipUser =>
tweet.retweets * vipUser.factor
)
)
Fun[ctional] Spark with Scala
3.3 For comprehension
Syntactic sugar al rescate!
case class Tweet(id: Int, content: String, retweets: Int, user: String)
case class VipUserFactor(id: Int, factor: Double)
for {
tweet <- tweets
vipUser <- vipUsers
if tweet.id == vipUser.id
} yield tweet.retweets * vipUser.factor
Fun[ctional] Spark with Scala
3.4 Type Classes
Patrón de diseño que nos permite extender funcionalidad a distintos
tipos al vuelo usando implícitos
trait MyCollection[T[Int]] {
def sum(coll: T[Int]): Double
def size(coll: T[Int]): Long
}
Fun[ctional] Spark with Scala
3.4 Type Classes
Quiero testear mi core con listas en memoria
implicit object RDDAsCollection extends MyCollection[RDD] {
def sum(coll: RDD[Int]) = coll.sum
def size(coll: RDD[Int]) = coll.count
}
implicit object ListAsCollection extends MyCollection[List] {
def sum(coll: List[Int]) = coll.sum
def size(coll: List[Int]) = coll.size
}
Fun[ctional] Spark with Scala
3.4 Type Classes
Quiero testear mi core con listas en memoria
implicit class RichMyCollection[T[_]](coll: T[Int])(implicit ev: MyCollection[T]) {
def mean = ev.sum(coll) / ev.size(coll)
}
List(1, 2, 3).mean
rdd.mean
4 DESVENTAJAS
DE SCALA
EN SPARK
Fun[ctional] Spark with Scala
Fun[ctional] Spark with Scala
4. DESVENTAJAS
Desventajas de usar Scala en Spark
• Curva de aprendizaje para desarrolladores
• Curva de aprendizaje para Data Scientists en Machine Learning
• Costoso en tiempo para realizar PoC
• Código Javero
• Performance en la JVM (recordemos el anterior meetup)
• + Algoritmos implementados en Python - Algoritmos MLlib distribuidos
Fun[ctional] Spark with Scala
4. DESVENTAJAS
override def hasNext: Boolean = {
if (!finished) {
if (!gotNext) {
nextValue = getNext()
if (finished) {
closeIfNeeded()
}
gotNext = true
}
}
!finished
}
override def next(): U = {
if (!hasNext) {
throw new NoSuchElementException("End of stream")
}
gotNext = false
nextValue
}
}
private[spark] abstract class NextIterator[U] extends Iterator[U] {
private var gotNext = false
private var nextValue: U = _
private var closed = false
protected var finished = false
def closeIfNeeded() {
if (!closed) {
closed = true
close()
}
}
Código Spark = Java Style
Fun[ctional] Spark with Scala
Haría vomitar al mismísimo Odersky ...
Fun[ctional] Spark with Scala
4. DESVENTAJAS
JVM
• Los objetos de Java consumen más memoria de la que deberían
“abcd” 4 bytes en Nativo UTF-8 y 48 bytes en Java
• El GC de Java tiende a sobre trabajar y no tiene suficiente info.
Fun[ctional] Spark with Scala
4. DESVENTAJAS
Difícil de aprender??
Coursera Scala Specialization
Scalera
Scala Center
BIG DATA
CHILD`S PLAY
Gracias!!
Stratio busca Talento
Contacto:
jcgarcia@stratio.com
es.linkedin.com/in/gserranojc
dvallejo@stratio.com
es.linkedin.com/in/davidvallejonavarro
PREGUNTAS

Más contenido relacionado

La actualidad más candente

Resumen Muestreo
Resumen MuestreoResumen Muestreo
Resumen Muestreo
mkt6to
 
Clase Nº5 Programacion Lineal
Clase Nº5 Programacion LinealClase Nº5 Programacion Lineal
Clase Nº5 Programacion Lineal
jotape74
 
Capital de trabajo clase 1
Capital de trabajo clase 1Capital de trabajo clase 1
Capital de trabajo clase 1
jpsalced
 
Ejercicios metodo grafico
Ejercicios metodo graficoEjercicios metodo grafico
Ejercicios metodo grafico
DianitaMagaly
 
Compras, un enfoque estratégico
Compras, un enfoque estratégicoCompras, un enfoque estratégico
Compras, un enfoque estratégico
racamachop
 

La actualidad más candente (20)

costo de capital
costo de capitalcosto de capital
costo de capital
 
Razon por inversiones
Razon por inversionesRazon por inversiones
Razon por inversiones
 
Calculo De Costo De Capital
Calculo De Costo De CapitalCalculo De Costo De Capital
Calculo De Costo De Capital
 
Indices financieros
Indices financierosIndices financieros
Indices financieros
 
Resumen Muestreo
Resumen MuestreoResumen Muestreo
Resumen Muestreo
 
Modelo de transporte costo minimo
Modelo de transporte costo minimoModelo de transporte costo minimo
Modelo de transporte costo minimo
 
Clase Nº5 Programacion Lineal
Clase Nº5 Programacion LinealClase Nº5 Programacion Lineal
Clase Nº5 Programacion Lineal
 
Rotación de inventarios
Rotación de inventariosRotación de inventarios
Rotación de inventarios
 
Método grafico. Teoría y Práctica
Método grafico. Teoría y PrácticaMétodo grafico. Teoría y Práctica
Método grafico. Teoría y Práctica
 
Liquidez
LiquidezLiquidez
Liquidez
 
Politicas de dividendos
Politicas de dividendosPoliticas de dividendos
Politicas de dividendos
 
Capital de trabajo clase 1
Capital de trabajo clase 1Capital de trabajo clase 1
Capital de trabajo clase 1
 
Ejercicios metodo grafico
Ejercicios metodo graficoEjercicios metodo grafico
Ejercicios metodo grafico
 
Indicadores financieros
Indicadores financierosIndicadores financieros
Indicadores financieros
 
valoración de bonos
valoración de bonos valoración de bonos
valoración de bonos
 
Presupuesto segun su flexibilidad
Presupuesto segun su flexibilidadPresupuesto segun su flexibilidad
Presupuesto segun su flexibilidad
 
Ejercicio de demanda potencial
Ejercicio de demanda potencialEjercicio de demanda potencial
Ejercicio de demanda potencial
 
Ejercicios de capital de trabajo
Ejercicios de capital de trabajoEjercicios de capital de trabajo
Ejercicios de capital de trabajo
 
Compras, un enfoque estratégico
Compras, un enfoque estratégicoCompras, un enfoque estratégico
Compras, un enfoque estratégico
 
Rotacion cartera, ventas
Rotacion cartera, ventasRotacion cartera, ventas
Rotacion cartera, ventas
 

Destacado

Introduction to scala for a c programmer
Introduction to scala for a c programmerIntroduction to scala for a c programmer
Introduction to scala for a c programmer
Girish Kumar A L
 
Practical Aggregate Programming in Scala
Practical Aggregate Programming in ScalaPractical Aggregate Programming in Scala
Practical Aggregate Programming in Scala
Roberto Casadei
 

Destacado (20)

Spark streaming for the internet of flying things 20160510.pptx
Spark streaming for the internet of flying things 20160510.pptxSpark streaming for the internet of flying things 20160510.pptx
Spark streaming for the internet of flying things 20160510.pptx
 
Scala desde c# y JavaScript
Scala desde c# y JavaScriptScala desde c# y JavaScript
Scala desde c# y JavaScript
 
Scala: un vistazo general
Scala: un vistazo generalScala: un vistazo general
Scala: un vistazo general
 
Neo4j - A Graph Database
Neo4j - A Graph DatabaseNeo4j - A Graph Database
Neo4j - A Graph Database
 
Meetup Spark 2.0
Meetup Spark 2.0Meetup Spark 2.0
Meetup Spark 2.0
 
Zaharia spark-scala-days-2012
Zaharia spark-scala-days-2012Zaharia spark-scala-days-2012
Zaharia spark-scala-days-2012
 
Introduction to scala for a c programmer
Introduction to scala for a c programmerIntroduction to scala for a c programmer
Introduction to scala for a c programmer
 
Jump Start into Apache Spark (Seattle Spark Meetup)
Jump Start into Apache Spark (Seattle Spark Meetup)Jump Start into Apache Spark (Seattle Spark Meetup)
Jump Start into Apache Spark (Seattle Spark Meetup)
 
Baño
BañoBaño
Baño
 
Apache hive
Apache hiveApache hive
Apache hive
 
Java 8 and beyond, a scala story
Java 8 and beyond, a scala storyJava 8 and beyond, a scala story
Java 8 and beyond, a scala story
 
Practical Aggregate Programming in Scala
Practical Aggregate Programming in ScalaPractical Aggregate Programming in Scala
Practical Aggregate Programming in Scala
 
Performance Optimization Case Study: Shattering Hadoop's Sort Record with Spa...
Performance Optimization Case Study: Shattering Hadoop's Sort Record with Spa...Performance Optimization Case Study: Shattering Hadoop's Sort Record with Spa...
Performance Optimization Case Study: Shattering Hadoop's Sort Record with Spa...
 
Six years of Scala and counting
Six years of Scala and countingSix years of Scala and counting
Six years of Scala and counting
 
Scala in Practice
Scala in PracticeScala in Practice
Scala in Practice
 
Python to scala
Python to scalaPython to scala
Python to scala
 
Scala - A Scalable Language
Scala - A Scalable LanguageScala - A Scalable Language
Scala - A Scalable Language
 
Indexed Hive
Indexed HiveIndexed Hive
Indexed Hive
 
Scala: Pattern matching, Concepts and Implementations
Scala: Pattern matching, Concepts and ImplementationsScala: Pattern matching, Concepts and Implementations
Scala: Pattern matching, Concepts and Implementations
 
Reactive Access to MongoDB from Scala
Reactive Access to MongoDB from ScalaReactive Access to MongoDB from Scala
Reactive Access to MongoDB from Scala
 

Similar a Fun[ctional] spark with scala

Similar a Fun[ctional] spark with scala (20)

Spark Hands-on
Spark Hands-onSpark Hands-on
Spark Hands-on
 
Tutorial en Apache Spark - Clasificando tweets en realtime
Tutorial en Apache Spark - Clasificando tweets en realtimeTutorial en Apache Spark - Clasificando tweets en realtime
Tutorial en Apache Spark - Clasificando tweets en realtime
 
Meetup Spark y la Combinación de sus Distintos Módulos
Meetup Spark y la Combinación de sus Distintos MódulosMeetup Spark y la Combinación de sus Distintos Módulos
Meetup Spark y la Combinación de sus Distintos Módulos
 
Spark meetup barcelona
Spark meetup barcelonaSpark meetup barcelona
Spark meetup barcelona
 
Spark
SparkSpark
Spark
 
Resilient Distributed Dataset - Analisis paper
Resilient  Distributed Dataset - Analisis paper Resilient  Distributed Dataset - Analisis paper
Resilient Distributed Dataset - Analisis paper
 
Primeros pasos con Apache Spark - Madrid Meetup
Primeros pasos con Apache Spark - Madrid MeetupPrimeros pasos con Apache Spark - Madrid Meetup
Primeros pasos con Apache Spark - Madrid Meetup
 
Primeros pasos con Spark - Spark Meetup Madrid 30-09-2014
Primeros pasos con Spark - Spark Meetup Madrid 30-09-2014Primeros pasos con Spark - Spark Meetup Madrid 30-09-2014
Primeros pasos con Spark - Spark Meetup Madrid 30-09-2014
 
Computación distribuida usando Python
Computación distribuida usando PythonComputación distribuida usando Python
Computación distribuida usando Python
 
Meetup Real Time Aggregations Spark Streaming + Spark Sql
Meetup Real Time Aggregations  Spark Streaming + Spark SqlMeetup Real Time Aggregations  Spark Streaming + Spark Sql
Meetup Real Time Aggregations Spark Streaming + Spark Sql
 
Introducción a Apache Spark
Introducción a Apache SparkIntroducción a Apache Spark
Introducción a Apache Spark
 
Introduccion a Apache Spark
Introduccion a Apache SparkIntroduccion a Apache Spark
Introduccion a Apache Spark
 
Parallel Programming
Parallel ProgrammingParallel Programming
Parallel Programming
 
Codemotion 2016 - d3.js un taller divertido y difícil
Codemotion 2016 - d3.js un taller divertido y difícilCodemotion 2016 - d3.js un taller divertido y difícil
Codemotion 2016 - d3.js un taller divertido y difícil
 
Análisis de datos con Apache Spark
Análisis de datos con Apache SparkAnálisis de datos con Apache Spark
Análisis de datos con Apache Spark
 
Introducción a Celery y las colas de tareas asíncronas
Introducción a Celery y las colas de tareas asíncronasIntroducción a Celery y las colas de tareas asíncronas
Introducción a Celery y las colas de tareas asíncronas
 
Meetup: Cómo monitorizar y optimizar procesos de Spark usando la Spark Web - ...
Meetup: Cómo monitorizar y optimizar procesos de Spark usando la Spark Web - ...Meetup: Cómo monitorizar y optimizar procesos de Spark usando la Spark Web - ...
Meetup: Cómo monitorizar y optimizar procesos de Spark usando la Spark Web - ...
 
Spark web meetup
Spark web meetupSpark web meetup
Spark web meetup
 
Procesamiento de datos a gran escala con Apache Spark
Procesamiento de datos a gran escala con Apache SparkProcesamiento de datos a gran escala con Apache Spark
Procesamiento de datos a gran escala con Apache Spark
 
Apache spark meetup
Apache spark meetupApache spark meetup
Apache spark meetup
 

Último

Reporte de incidencia delictiva Silao marzo 2024
Reporte de incidencia delictiva Silao marzo 2024Reporte de incidencia delictiva Silao marzo 2024
Reporte de incidencia delictiva Silao marzo 2024
OBSERVATORIOREGIONAL
 
REPORTE DE HOMICIDIO DOLOSO IRAPUATO ABRIL 2024
REPORTE DE HOMICIDIO DOLOSO IRAPUATO ABRIL 2024REPORTE DE HOMICIDIO DOLOSO IRAPUATO ABRIL 2024
REPORTE DE HOMICIDIO DOLOSO IRAPUATO ABRIL 2024
IrapuatoCmovamos
 
Reporte de incidencia delictiva de Romita marzo 2024
Reporte de incidencia delictiva de Romita marzo 2024Reporte de incidencia delictiva de Romita marzo 2024
Reporte de incidencia delictiva de Romita marzo 2024
OBSERVATORIOREGIONAL
 
Anclaje Grupo 5..pptx de todo tipo de anclaje
Anclaje Grupo 5..pptx de todo tipo de anclajeAnclaje Grupo 5..pptx de todo tipo de anclaje
Anclaje Grupo 5..pptx de todo tipo de anclaje
klebersky23
 
METODOLOGÍA 5S - PRESENTACION DE INICIO DEL PROYECTO
METODOLOGÍA 5S - PRESENTACION DE INICIO DEL PROYECTOMETODOLOGÍA 5S - PRESENTACION DE INICIO DEL PROYECTO
METODOLOGÍA 5S - PRESENTACION DE INICIO DEL PROYECTO
JoselynGoeTmara
 
Proyectos de investigacion en ciencias sociales 6to - maipue (2).pdf
Proyectos de investigacion en ciencias sociales 6to - maipue (2).pdfProyectos de investigacion en ciencias sociales 6to - maipue (2).pdf
Proyectos de investigacion en ciencias sociales 6to - maipue (2).pdf
nicolas24233
 
2. POLITICAS Y LEGISLACION EDUCATIVA.pptx
2. POLITICAS Y LEGISLACION EDUCATIVA.pptx2. POLITICAS Y LEGISLACION EDUCATIVA.pptx
2. POLITICAS Y LEGISLACION EDUCATIVA.pptx
camilasto28
 
La Inteligencia Artificial -AnaliticayDatos-BeatrizGarcia-Abril2024-D.pdf
La Inteligencia Artificial -AnaliticayDatos-BeatrizGarcia-Abril2024-D.pdfLa Inteligencia Artificial -AnaliticayDatos-BeatrizGarcia-Abril2024-D.pdf
La Inteligencia Artificial -AnaliticayDatos-BeatrizGarcia-Abril2024-D.pdf
analiticaydatos
 

Último (17)

Reporte de incidencia delictiva Silao marzo 2024
Reporte de incidencia delictiva Silao marzo 2024Reporte de incidencia delictiva Silao marzo 2024
Reporte de incidencia delictiva Silao marzo 2024
 
Problemas de programación lineal entera.pptx
Problemas de programación lineal entera.pptxProblemas de programación lineal entera.pptx
Problemas de programación lineal entera.pptx
 
REPORTE DE HOMICIDIO DOLOSO IRAPUATO ABRIL 2024
REPORTE DE HOMICIDIO DOLOSO IRAPUATO ABRIL 2024REPORTE DE HOMICIDIO DOLOSO IRAPUATO ABRIL 2024
REPORTE DE HOMICIDIO DOLOSO IRAPUATO ABRIL 2024
 
REGISTRO CONTABLE DE CONTABILIDAD 2022..
REGISTRO CONTABLE DE CONTABILIDAD 2022..REGISTRO CONTABLE DE CONTABILIDAD 2022..
REGISTRO CONTABLE DE CONTABILIDAD 2022..
 
Reporte de incidencia delictiva de Romita marzo 2024
Reporte de incidencia delictiva de Romita marzo 2024Reporte de incidencia delictiva de Romita marzo 2024
Reporte de incidencia delictiva de Romita marzo 2024
 
Mapa concepto sobre la contabilidad de costos
Mapa concepto sobre la contabilidad de costosMapa concepto sobre la contabilidad de costos
Mapa concepto sobre la contabilidad de costos
 
5558423-peru-evolucion-de-la-pobreza-monetaria-2014-2023(2).pdf
5558423-peru-evolucion-de-la-pobreza-monetaria-2014-2023(2).pdf5558423-peru-evolucion-de-la-pobreza-monetaria-2014-2023(2).pdf
5558423-peru-evolucion-de-la-pobreza-monetaria-2014-2023(2).pdf
 
Anclaje Grupo 5..pptx de todo tipo de anclaje
Anclaje Grupo 5..pptx de todo tipo de anclajeAnclaje Grupo 5..pptx de todo tipo de anclaje
Anclaje Grupo 5..pptx de todo tipo de anclaje
 
Pineda - Metodologia de la investigacion manual para el desarrollo de persona...
Pineda - Metodologia de la investigacion manual para el desarrollo de persona...Pineda - Metodologia de la investigacion manual para el desarrollo de persona...
Pineda - Metodologia de la investigacion manual para el desarrollo de persona...
 
METODOLOGÍA 5S - PRESENTACION DE INICIO DEL PROYECTO
METODOLOGÍA 5S - PRESENTACION DE INICIO DEL PROYECTOMETODOLOGÍA 5S - PRESENTACION DE INICIO DEL PROYECTO
METODOLOGÍA 5S - PRESENTACION DE INICIO DEL PROYECTO
 
4° UNIDAD DE APRENDIZAJE 2 MAYO 2024.docx
4°  UNIDAD DE APRENDIZAJE 2 MAYO  2024.docx4°  UNIDAD DE APRENDIZAJE 2 MAYO  2024.docx
4° UNIDAD DE APRENDIZAJE 2 MAYO 2024.docx
 
PRESENTACION SOBRE LA HOJA DE CALCULO ⠀⠀
PRESENTACION SOBRE LA HOJA DE CALCULO ⠀⠀PRESENTACION SOBRE LA HOJA DE CALCULO ⠀⠀
PRESENTACION SOBRE LA HOJA DE CALCULO ⠀⠀
 
Proyectos de investigacion en ciencias sociales 6to - maipue (2).pdf
Proyectos de investigacion en ciencias sociales 6to - maipue (2).pdfProyectos de investigacion en ciencias sociales 6to - maipue (2).pdf
Proyectos de investigacion en ciencias sociales 6to - maipue (2).pdf
 
2. POLITICAS Y LEGISLACION EDUCATIVA.pptx
2. POLITICAS Y LEGISLACION EDUCATIVA.pptx2. POLITICAS Y LEGISLACION EDUCATIVA.pptx
2. POLITICAS Y LEGISLACION EDUCATIVA.pptx
 
La Inteligencia Artificial -AnaliticayDatos-BeatrizGarcia-Abril2024-D.pdf
La Inteligencia Artificial -AnaliticayDatos-BeatrizGarcia-Abril2024-D.pdfLa Inteligencia Artificial -AnaliticayDatos-BeatrizGarcia-Abril2024-D.pdf
La Inteligencia Artificial -AnaliticayDatos-BeatrizGarcia-Abril2024-D.pdf
 
Asignatura-Optativa-Sociologia-CS-3BGU.pdf
Asignatura-Optativa-Sociologia-CS-3BGU.pdfAsignatura-Optativa-Sociologia-CS-3BGU.pdf
Asignatura-Optativa-Sociologia-CS-3BGU.pdf
 
Crecimiento del PIB real revisado sexenios neoliberales y nueva era del sober...
Crecimiento del PIB real revisado sexenios neoliberales y nueva era del sober...Crecimiento del PIB real revisado sexenios neoliberales y nueva era del sober...
Crecimiento del PIB real revisado sexenios neoliberales y nueva era del sober...
 

Fun[ctional] spark with scala

  • 1. 13 Junio 2016 Fun[ctional] Spark with Scala
  • 2. Quienes somos Fun[ctional] Spark with Scala José Carlos García Serrano Arquitecto Big Data en Stratio. Granadino e ingeniero por la ETSII, master de Big Data en la UTad, certificado en Spark y AWS Amante de las nuevas tecnologías y de las arquitecturas basadas en Big Data FanBoy de cosas como: ● Scala ● Spark ● Akka ● MongoDB ● Cassandra Pero todos tenemos un pasado: ● Delphi ● C++ ● BBDD SQL ● Hadoop
  • 3. Quienes somos Fun[ctional] Spark with Scala David Vallejo Navarro Desarrollador Scala en Stratio. Trabajando con Scala desde 2012 (si...cuando nadie sabía qué era eso de Scala) Actualmente cursando un máster en Investigación informática. He trabajado en: ● DSLs para la creación de aplicaciones sociales ● Sistemas distribuidos ● Aplicaciones WEB ● Migración de antiguas arquitecturas a Scala ● Y ahora, Big Data! Ah! Y tengo un blog de Scala: www.scalera.es
  • 4. José Carlos García Serrano Arquitecto Big Data jcgarcia@stratio.com CONTACTO ÍNDICE INTRODUCCIÓN1 2 3 VENTAJAS DE SCALA EN SPARK DESVENTAJAS DE SCALA EN SPARK4 David Vallejo Navarro Desarrollador Big Data dvallejo@stratio.com SCALA AVANZADO CON SPARK
  • 6. Fun[ctional] Spark with Scala ¿Qué es Scala? 2003 - Martin Odersky, estando borracho, ve un anuncio de mantequilla de cacahuete Reese sobre el chocolate y tiene una idea. Crea Scala, un lenguaje que unifica las construcciones de los lenguajes funcionales y los orientados a objetos. Consigue cabrear a los partidarios de ambos tipos de lenguaje que declaran al unísono la jihad. Incomplete, and Mostly Wrong History of Programming Languages por James Iry
  • 7. Fun[ctional] Spark with Scala ¿Qué es Scala? CARACTERÍSTICAS PRINCIPALES CORRE EN LA JVM1 2 3 MULTIPARADIGMA TIPADO ESTÁTICO INFERENCIA DE TIPOS4 5 HERENCIA MÚLTIPLE
  • 8. Fun[ctional] Spark with Scala Scala en Noviembre de 2014 72.992 miembros 319 meetups
  • 9. 72.992 miembros 319 meetups Fun[ctional] Spark with Scala Scala en Junio de 2016 (1 año y 7 meses después) 233.375 miembros 570 meetups
  • 10. Fun[ctional] Spark with Scala Algunas empresas que usan Scala
  • 11. Fun[ctional] Spark with Scala Spark Scala + =
  • 13. Fun[ctional] Spark with Scala 2. VENTAJAS 2.1 Ventajas de usar Scala • Uso de JVM -> Librerías - Polimorfismo - Gestión • Estáticamente tipado -> Optimización del uso de memoria y de los algoritmos aplicados • Modularidad -> Grandes proyectos entendibles por humanos • Sintaxis simple y rápido desarrollo -> Programación funcional, poco código y simplicidad • Multi-threading y concurrencia -> Akka y la programación funcional son nuestros amigos
  • 14. Fun[ctional] Spark with Scala Los inicios como padawan scalero son duros y no puros ...
  • 15. Fun[ctional] Spark with Scala 2. VENTAJAS Java?? Ventajas • trait JavaNoMola { val advantages : Seq[String] = ??? } Desventajas • No data-centric language • Líneas de código infinitas • Difícil uso de colecciones • Var = efectos de lado • Concurrencia descontrolada Python?? Ventajas • Data-centric language • Fácil uso de colecciones Desventajas • Tipado dinámico • Compilado mejor que interpretado Performance - Errores • No es modular • Mala integración con Hadoop • Api limitada de Streaming Y por qué no en C ...
  • 16. Fun[ctional] Spark with Scala 2. VENTAJAS
  • 17. Fun[ctional] Spark with Scala 2. VENTAJAS Probablemente en un futuro veremos a Spark como la colección de elementos distribuidos de Scala
  • 18. Fun[ctional] Spark with Scala 2. VENTAJAS 2.2 Ventajas de usar Scala en Spark • Escrito en Scala • RDD es una colección distribuida, funciones conocidas map, flatMap, groupBy, foreach, etc … • Lambda va de serie • RDD tipados -> Datasets tipados y no tipados • Poco código para realizar ETLs y apps sencillas • Datos inmutables • Efectos de lado minimizados (Closure) • Evaluación perezosa (Lazy)
  • 19. Fun[ctional] Spark with Scala 2. VENTAJAS Funciones conocidas por cualquier escalero ... def flatMap[U: ClassTag](f: T => TraversableOnce[U]): RDD[U] = withScope { val cleanF = sc.clean(f) new MapPartitionsRDD[U, T](this, (context, pid, iter) => iter.flatMap(cleanF)) } private[spark] class MapPartitionsRDD[U: ClassTag, T: ClassTag]( var prev: RDD[T], f: (TaskContext, Int, Iterator[T]) => Iterator[U], // (TaskContext, partition index, iterator) preservesPartitioning: Boolean = false) extends RDD[U](prev) { override def compute(split: Partition, context: TaskContext): Iterator[U] = f(context, split.index, firstParent[T].iterator(split, context))
  • 21. Fun[ctional] Spark with Scala 2. VENTAJAS val textFile = sc.textFile("hdfs://...") val counts = textFile.flatMap(line => line.split(" ")) .map(word => (word, 1)) .reduceByKey(_ + _) JavaRDD<String> textFile = sc.textFile("hdfs://..."); JavaRDD<String> words = textFile.flatMap(new FlatMapFunction<String, String>() { public Iterable<String> call(String s) { return Arrays.asList(s.split(" ")); } }); JavaPairRDD<String, Integer> pairs = words.mapToPair(new PairFunction<String, String, Integer>() { public Tuple2<String, Integer> call(String s) { return new Tuple2<String, Integer>(s, 1); } }); JavaPairRDD<String, Integer> counts = pairs.reduceByKey(new Function2<Integer, Integer, Integer>() { public Integer call(Integer a, Integer b) { return a + b; } }); Java Típico word count, pero refleja la realidad … Scala vs Java vs Python Scala Python text_file = sc.textFile("hdfs://...") counts = text_file.flatMap(lambda line: line.split(" ")) .map(lambda word: (word, 1)) .reduceByKey(lambda a, b: a + b)
  • 23. Fun[ctional] Spark with Scala 2. VENTAJAS Nuestra querida inmutabilidad ... • Mutabilidad y concurrencia no mola -> Efectos de lado • Al ser inmutable un RDD puede ser recreado en cualquier momento • Difícil mantenimiento de datos que mutan -> update de memoria y disco -> Pésimo performance • Queremos programación funcional y transformaciones que son funciones
  • 24. Fun[ctional] Spark with Scala 2. VENTAJAS Lazy?? mismo concepto de una variable lazy de scala pero en RDD • Todas las transformaciones se van añadiendo al DAG de operaciones • Solo son ejecutadas cuando realizamos una acción • Se computan las transformaciones de las que depende la acción • Las que no dependan de la acción no son computadas Odersky querría este concepto para sus colecciones ;)
  • 25. Fun[ctional] Spark with Scala def collect(): Array[T] = withScope { val results = sc.runJob(this, (iter: Iterator[T]) => iter.toArray) Array.concat(results: _*) } def map[U: ClassTag](f: T => U): RDD[U] = withScope { val cleanF = sc.clean(f) new MapPartitionsRDD[U, T](this, (context, pid, iter) => iter. map(cleanF)) } def runJob[T, U: ClassTag]( rdd: RDD[T], func: (TaskContext, Iterator[T]) => U, partitions: Seq[Int], resultHandler: (Int, U) => Unit): Unit = { if (stopped.get()) { throw new IllegalStateException("SparkContext has been shutdown") } val callSite = getCallSite val cleanedFunc = clean(func) logInfo("Starting job: " + callSite.shortForm) if (conf.getBoolean("spark.logLineage", false)) { logInfo("RDD's recursive dependencies:n" + rdd.toDebugString) } dagScheduler.runJob(rdd, cleanedFunc, partitions, callSite, resultHandler, localProperties.get) progressBar.foreach(_.finishAll()) rdd.doCheckpoint()
  • 26. Fun[ctional] Spark with Scala 2. VENTAJAS 2.3 Optimizaciones en Scala Tungsten ● Serialización ● DataSets DataFrames ● UDFs más eficientes que en Python MLlib ● Coste adicional de convertir Python objects a Scala objects Recordemos el meetup de Fun[ctional] Spark with Scala ...
  • 27. Fun[ctional] Spark with Scala 2. VENTAJAS Y antes de spark 1.6 ...
  • 28. Fun[ctional] Spark with Scala 2. VENTAJAS desde Spark 1.4 tungsten ya optimizaba algunas funciones de DataFrames de Scala
  • 30. Fun[ctional] Spark with Scala 3. Scala avanzado
  • 31. Fun[ctional] Spark with Scala 3.1 Implícitos def mean(xs: RDD[Int]): Double = xs.sum / xs.count mean(rdd) Queremos calcular la media de un RDD:
  • 32. Fun[ctional] Spark with Scala 3.1 Implícitos Implícitos: partes de código que se ejecutan sin ser llamados
  • 33. Fun[ctional] Spark with Scala 3.1 Implícitos implicit val timeout = 5000 def tryConnection(dbUri: String)(implicit timeout: Int) = ??? tryConnection("127.0.0.1/8080") case class Point(x: Int, y: Int) implicit def tupleToPoint(tuple: (Int, Int)): Point = Point(tuple._1, tuple._2) def sumPoints(p1: Point, p2: Point) = Point(p1.x + p2.x, p1.y + p2.y) sumPoints(Point(1, 2), (3, 4)) Valores implícitos Funciones implícitas
  • 34. Fun[ctional] Spark with Scala 3.1 Implícitos implicit class RichSparkRDD(rdd: RDD[Int]) { def mean: Double = rdd.sum / rdd.count } rdd.mean //new RichSparkRDD(rdd).mean Podemos utilizar una implicit class para expandir funcionalidad:
  • 35. Fun[ctional] Spark with Scala 3.2 Funciones de orden superior Funciones que reciben funciones y/o devuelven funciones
  • 36. Fun[ctional] Spark with Scala 3.2 Funciones de orden superior type Term = Int type Result = Int type Operation = (Term, Term) => Result def add: Operation = (n1, n2) => n1 + n2 def sub: Operation = (n1, n2) => n1 - n2 def calculate(n1: Term, n2: Term)(f: Operation): Result = f(n1, n2) calculate(2, 5)(add) calculate(1, 6)((n1, n2) => n1 * n2) Construyendo una calculadora
  • 37. Fun[ctional] Spark with Scala 3.2 Funciones de orden superior def withSparkContext[T](name: String)(blockCode: SparkContext => T): T = { val sparkConf = new SparkConf().setAppName(name).setMaster("local[4]") val sc = new SparkContext(sparkConf) val result = blockCode(sc) sc.stop() result } ¿Y en Spark…? withSparkContext("Meetup SDK") { sc => val myRDD = sc.parallelize(List(1, 2, 3, 4)) // ... }
  • 38. Fun[ctional] Spark with Scala 3.3 For comprehension Map, flatMap, syntactic sugar ….
  • 39. Fun[ctional] Spark with Scala 3.3 For comprehension Métodos map y flatMap val myRDD = sc.parallelize(List(1, 2, 3, 4)) myRDD map (_ + 1) //RDD(2, 3, 4, 5) myRDD flatMap (i => List(i - 1, i + 1)) // RDD(0, 2, 1, 3, 2, 4, 3, 5)
  • 40. Fun[ctional] Spark with Scala 3.3 For comprehension Iterando sobre una colección de tweets case class Tweet(id: Int, content: String, retweets: Int, user: String) case class VipUserFactor(id: Int, factor: Double) tweets.flatMap ( tweet => vipUsers.filter(_.id == tweet.id).map ( vipUser => tweet.retweets * vipUser.factor ) )
  • 41. Fun[ctional] Spark with Scala 3.3 For comprehension Syntactic sugar al rescate! case class Tweet(id: Int, content: String, retweets: Int, user: String) case class VipUserFactor(id: Int, factor: Double) for { tweet <- tweets vipUser <- vipUsers if tweet.id == vipUser.id } yield tweet.retweets * vipUser.factor
  • 42. Fun[ctional] Spark with Scala 3.4 Type Classes Patrón de diseño que nos permite extender funcionalidad a distintos tipos al vuelo usando implícitos
  • 43. trait MyCollection[T[Int]] { def sum(coll: T[Int]): Double def size(coll: T[Int]): Long } Fun[ctional] Spark with Scala 3.4 Type Classes Quiero testear mi core con listas en memoria implicit object RDDAsCollection extends MyCollection[RDD] { def sum(coll: RDD[Int]) = coll.sum def size(coll: RDD[Int]) = coll.count } implicit object ListAsCollection extends MyCollection[List] { def sum(coll: List[Int]) = coll.sum def size(coll: List[Int]) = coll.size }
  • 44. Fun[ctional] Spark with Scala 3.4 Type Classes Quiero testear mi core con listas en memoria implicit class RichMyCollection[T[_]](coll: T[Int])(implicit ev: MyCollection[T]) { def mean = ev.sum(coll) / ev.size(coll) } List(1, 2, 3).mean rdd.mean
  • 47. Fun[ctional] Spark with Scala 4. DESVENTAJAS Desventajas de usar Scala en Spark • Curva de aprendizaje para desarrolladores • Curva de aprendizaje para Data Scientists en Machine Learning • Costoso en tiempo para realizar PoC • Código Javero • Performance en la JVM (recordemos el anterior meetup) • + Algoritmos implementados en Python - Algoritmos MLlib distribuidos
  • 48. Fun[ctional] Spark with Scala 4. DESVENTAJAS override def hasNext: Boolean = { if (!finished) { if (!gotNext) { nextValue = getNext() if (finished) { closeIfNeeded() } gotNext = true } } !finished } override def next(): U = { if (!hasNext) { throw new NoSuchElementException("End of stream") } gotNext = false nextValue } } private[spark] abstract class NextIterator[U] extends Iterator[U] { private var gotNext = false private var nextValue: U = _ private var closed = false protected var finished = false def closeIfNeeded() { if (!closed) { closed = true close() } } Código Spark = Java Style
  • 49. Fun[ctional] Spark with Scala Haría vomitar al mismísimo Odersky ...
  • 50. Fun[ctional] Spark with Scala 4. DESVENTAJAS JVM • Los objetos de Java consumen más memoria de la que deberían “abcd” 4 bytes en Nativo UTF-8 y 48 bytes en Java • El GC de Java tiende a sobre trabajar y no tiene suficiente info.
  • 51. Fun[ctional] Spark with Scala 4. DESVENTAJAS Difícil de aprender?? Coursera Scala Specialization Scalera Scala Center
  • 52. BIG DATA CHILD`S PLAY Gracias!! Stratio busca Talento Contacto: jcgarcia@stratio.com es.linkedin.com/in/gserranojc dvallejo@stratio.com es.linkedin.com/in/davidvallejonavarro