SlideShare une entreprise Scribd logo
1  sur  53
Télécharger pour lire hors ligne
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

Contenu connexe

En vedette

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.pptxPablo Francisco Pérez Hidalgo
 
Scala: un vistazo general
Scala: un vistazo generalScala: un vistazo general
Scala: un vistazo generalMiguel Pastor
 
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 programmerGirish Kumar A L
 
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)Denny Lee
 
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 storyittaiz
 
Practical Aggregate Programming in Scala
Practical Aggregate Programming in ScalaPractical Aggregate Programming in Scala
Practical Aggregate Programming in ScalaRoberto Casadei
 
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...Databricks
 
Six years of Scala and counting
Six years of Scala and countingSix years of Scala and counting
Six years of Scala and countingManuel Bernhardt
 
Scala - A Scalable Language
Scala - A Scalable LanguageScala - A Scalable Language
Scala - A Scalable LanguageMario Gleichmann
 
Scala: Pattern matching, Concepts and Implementations
Scala: Pattern matching, Concepts and ImplementationsScala: Pattern matching, Concepts and Implementations
Scala: Pattern matching, Concepts and ImplementationsMICHRAFY MUSTAFA
 
Reactive Access to MongoDB from Scala
Reactive Access to MongoDB from ScalaReactive Access to MongoDB from Scala
Reactive Access to MongoDB from ScalaHermann Hueck
 

En vedette (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
 

Similaire à Fun[ctional] spark with scala

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 realtimeSocialmetrix
 
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ódulosJorge Lopez-Malla
 
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 Meetupdhiguero
 
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-2014Stratio
 
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 SqlJosé Carlos García Serrano
 
Introducción a Apache Spark
Introducción a Apache SparkIntroducción a Apache Spark
Introducción a Apache SparkSocialmetrix
 
Introduccion a Apache Spark
Introduccion a Apache SparkIntroduccion a Apache Spark
Introduccion a Apache SparkGustavo Arjones
 
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ícilJavier Abadía
 
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 SparkEduardo Castro
 
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íncronasalbertoalcolea
 
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 - ...Stratio
 
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 SparkSoftware Guru
 

Similaire à 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
 
Resilient Distributed Dataset - Analisis paper
Resilient  Distributed Dataset - Analisis paper Resilient  Distributed Dataset - Analisis paper
Resilient Distributed Dataset - Analisis paper
 
Spark
SparkSpark
Spark
 
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
 

Dernier

COMUNICADO PARA TODO TIPO DE REUNIONES .
COMUNICADO PARA TODO TIPO DE REUNIONES .COMUNICADO PARA TODO TIPO DE REUNIONES .
COMUNICADO PARA TODO TIPO DE REUNIONES .GIANELAKAINACHALLCOJ2
 
EPIDEMIO CANCER PULMON resumen nnn.pptx
EPIDEMIO CANCER PULMON  resumen nnn.pptxEPIDEMIO CANCER PULMON  resumen nnn.pptx
EPIDEMIO CANCER PULMON resumen nnn.pptxJEFFERSONMEDRANOCHAV
 
decreto 2090 de 2003.pdf actividades de alto riesgo en Colombia
decreto 2090 de 2003.pdf actividades de alto riesgo en Colombiadecreto 2090 de 2003.pdf actividades de alto riesgo en Colombia
decreto 2090 de 2003.pdf actividades de alto riesgo en Colombiaveronicayarpaz
 
INFORME FINAL ESTADISTICA DESCRIPTIVA E INFERENCIAL
INFORME FINAL ESTADISTICA DESCRIPTIVA E INFERENCIALINFORME FINAL ESTADISTICA DESCRIPTIVA E INFERENCIAL
INFORME FINAL ESTADISTICA DESCRIPTIVA E INFERENCIALMANUELVILELA7
 
variables-estadisticas. Presentación powerpoint
variables-estadisticas. Presentación powerpointvariables-estadisticas. Presentación powerpoint
variables-estadisticas. Presentación powerpointaria66611782972
 
AMNIOS Y CORDON UMBILICAL en el 3 embarazo (1).docx
AMNIOS Y CORDON UMBILICAL en el 3 embarazo (1).docxAMNIOS Y CORDON UMBILICAL en el 3 embarazo (1).docx
AMNIOS Y CORDON UMBILICAL en el 3 embarazo (1).docxlm8322074
 
CUADRO COMPARATIVO DE ARCHIVOS Y CARPETAS.pptx
CUADRO COMPARATIVO DE ARCHIVOS Y CARPETAS.pptxCUADRO COMPARATIVO DE ARCHIVOS Y CARPETAS.pptx
CUADRO COMPARATIVO DE ARCHIVOS Y CARPETAS.pptxfatimacamilainjantem
 
Los países por porcentaje de población blanca europea en AL (2024).pdf
Los países por porcentaje de población blanca europea en AL (2024).pdfLos países por porcentaje de población blanca europea en AL (2024).pdf
Los países por porcentaje de población blanca europea en AL (2024).pdfJC Díaz Herrera
 
Sistema Nacional de Vigilancia en Salud Pública SIVIGILA
Sistema Nacional de Vigilancia en Salud Pública SIVIGILASistema Nacional de Vigilancia en Salud Pública SIVIGILA
Sistema Nacional de Vigilancia en Salud Pública SIVIGILAsofiagomez288291
 
P.P ANÁLISIS DE UN TEXTO BÍBLICO. TEMA 10.pptx
P.P ANÁLISIS DE UN TEXTO BÍBLICO. TEMA 10.pptxP.P ANÁLISIS DE UN TEXTO BÍBLICO. TEMA 10.pptx
P.P ANÁLISIS DE UN TEXTO BÍBLICO. TEMA 10.pptxJafetColli
 
Reservas de divisas y oro en México en sexenio de AMLO (2018-2024).pdf
Reservas de divisas y oro en México en sexenio de AMLO (2018-2024).pdfReservas de divisas y oro en México en sexenio de AMLO (2018-2024).pdf
Reservas de divisas y oro en México en sexenio de AMLO (2018-2024).pdfJC Díaz Herrera
 
CALENDARIZACIÓN ACTUALIZADA DEL 2024 alt.pdf
CALENDARIZACIÓN ACTUALIZADA DEL 2024 alt.pdfCALENDARIZACIÓN ACTUALIZADA DEL 2024 alt.pdf
CALENDARIZACIÓN ACTUALIZADA DEL 2024 alt.pdfPOULANDERSONDELGADOA2
 
Análisis del Modo y Efecto de Fallas AMEF.ppt
Análisis del Modo y Efecto de Fallas AMEF.pptAnálisis del Modo y Efecto de Fallas AMEF.ppt
Análisis del Modo y Efecto de Fallas AMEF.pptProduvisaCursos
 
PLAN ANUAL DE PROYECTO 2020. para mejorar
PLAN ANUAL DE PROYECTO 2020. para mejorarPLAN ANUAL DE PROYECTO 2020. para mejorar
PLAN ANUAL DE PROYECTO 2020. para mejorarCelesteRolon2
 
Alfredo Gabriel Rodriguez Yajure Tarea#1
Alfredo Gabriel Rodriguez Yajure Tarea#1Alfredo Gabriel Rodriguez Yajure Tarea#1
Alfredo Gabriel Rodriguez Yajure Tarea#1alfredo130306
 
Los más ricos administradores de fondo de cobertura (1968-2024).pdf
Los más ricos administradores de fondo de cobertura (1968-2024).pdfLos más ricos administradores de fondo de cobertura (1968-2024).pdf
Los más ricos administradores de fondo de cobertura (1968-2024).pdfJC Díaz Herrera
 
Principales Retos Demográficos de Puerto Rico
Principales Retos Demográficos de Puerto RicoPrincipales Retos Demográficos de Puerto Rico
Principales Retos Demográficos de Puerto RicoRaúl Figueroa
 
Los idiomas más hablados en el mundo (2024).pdf
Los idiomas más hablados en el mundo  (2024).pdfLos idiomas más hablados en el mundo  (2024).pdf
Los idiomas más hablados en el mundo (2024).pdfJC Díaz Herrera
 
Adultos Mayores más de 60 años como de la población total (2024).pdf
Adultos Mayores más de 60 años como  de la población total (2024).pdfAdultos Mayores más de 60 años como  de la población total (2024).pdf
Adultos Mayores más de 60 años como de la población total (2024).pdfJC Díaz Herrera
 
Investigacion cualitativa y cuantitativa....pdf
Investigacion cualitativa y cuantitativa....pdfInvestigacion cualitativa y cuantitativa....pdf
Investigacion cualitativa y cuantitativa....pdfalexanderleonyonange
 

Dernier (20)

COMUNICADO PARA TODO TIPO DE REUNIONES .
COMUNICADO PARA TODO TIPO DE REUNIONES .COMUNICADO PARA TODO TIPO DE REUNIONES .
COMUNICADO PARA TODO TIPO DE REUNIONES .
 
EPIDEMIO CANCER PULMON resumen nnn.pptx
EPIDEMIO CANCER PULMON  resumen nnn.pptxEPIDEMIO CANCER PULMON  resumen nnn.pptx
EPIDEMIO CANCER PULMON resumen nnn.pptx
 
decreto 2090 de 2003.pdf actividades de alto riesgo en Colombia
decreto 2090 de 2003.pdf actividades de alto riesgo en Colombiadecreto 2090 de 2003.pdf actividades de alto riesgo en Colombia
decreto 2090 de 2003.pdf actividades de alto riesgo en Colombia
 
INFORME FINAL ESTADISTICA DESCRIPTIVA E INFERENCIAL
INFORME FINAL ESTADISTICA DESCRIPTIVA E INFERENCIALINFORME FINAL ESTADISTICA DESCRIPTIVA E INFERENCIAL
INFORME FINAL ESTADISTICA DESCRIPTIVA E INFERENCIAL
 
variables-estadisticas. Presentación powerpoint
variables-estadisticas. Presentación powerpointvariables-estadisticas. Presentación powerpoint
variables-estadisticas. Presentación powerpoint
 
AMNIOS Y CORDON UMBILICAL en el 3 embarazo (1).docx
AMNIOS Y CORDON UMBILICAL en el 3 embarazo (1).docxAMNIOS Y CORDON UMBILICAL en el 3 embarazo (1).docx
AMNIOS Y CORDON UMBILICAL en el 3 embarazo (1).docx
 
CUADRO COMPARATIVO DE ARCHIVOS Y CARPETAS.pptx
CUADRO COMPARATIVO DE ARCHIVOS Y CARPETAS.pptxCUADRO COMPARATIVO DE ARCHIVOS Y CARPETAS.pptx
CUADRO COMPARATIVO DE ARCHIVOS Y CARPETAS.pptx
 
Los países por porcentaje de población blanca europea en AL (2024).pdf
Los países por porcentaje de población blanca europea en AL (2024).pdfLos países por porcentaje de población blanca europea en AL (2024).pdf
Los países por porcentaje de población blanca europea en AL (2024).pdf
 
Sistema Nacional de Vigilancia en Salud Pública SIVIGILA
Sistema Nacional de Vigilancia en Salud Pública SIVIGILASistema Nacional de Vigilancia en Salud Pública SIVIGILA
Sistema Nacional de Vigilancia en Salud Pública SIVIGILA
 
P.P ANÁLISIS DE UN TEXTO BÍBLICO. TEMA 10.pptx
P.P ANÁLISIS DE UN TEXTO BÍBLICO. TEMA 10.pptxP.P ANÁLISIS DE UN TEXTO BÍBLICO. TEMA 10.pptx
P.P ANÁLISIS DE UN TEXTO BÍBLICO. TEMA 10.pptx
 
Reservas de divisas y oro en México en sexenio de AMLO (2018-2024).pdf
Reservas de divisas y oro en México en sexenio de AMLO (2018-2024).pdfReservas de divisas y oro en México en sexenio de AMLO (2018-2024).pdf
Reservas de divisas y oro en México en sexenio de AMLO (2018-2024).pdf
 
CALENDARIZACIÓN ACTUALIZADA DEL 2024 alt.pdf
CALENDARIZACIÓN ACTUALIZADA DEL 2024 alt.pdfCALENDARIZACIÓN ACTUALIZADA DEL 2024 alt.pdf
CALENDARIZACIÓN ACTUALIZADA DEL 2024 alt.pdf
 
Análisis del Modo y Efecto de Fallas AMEF.ppt
Análisis del Modo y Efecto de Fallas AMEF.pptAnálisis del Modo y Efecto de Fallas AMEF.ppt
Análisis del Modo y Efecto de Fallas AMEF.ppt
 
PLAN ANUAL DE PROYECTO 2020. para mejorar
PLAN ANUAL DE PROYECTO 2020. para mejorarPLAN ANUAL DE PROYECTO 2020. para mejorar
PLAN ANUAL DE PROYECTO 2020. para mejorar
 
Alfredo Gabriel Rodriguez Yajure Tarea#1
Alfredo Gabriel Rodriguez Yajure Tarea#1Alfredo Gabriel Rodriguez Yajure Tarea#1
Alfredo Gabriel Rodriguez Yajure Tarea#1
 
Los más ricos administradores de fondo de cobertura (1968-2024).pdf
Los más ricos administradores de fondo de cobertura (1968-2024).pdfLos más ricos administradores de fondo de cobertura (1968-2024).pdf
Los más ricos administradores de fondo de cobertura (1968-2024).pdf
 
Principales Retos Demográficos de Puerto Rico
Principales Retos Demográficos de Puerto RicoPrincipales Retos Demográficos de Puerto Rico
Principales Retos Demográficos de Puerto Rico
 
Los idiomas más hablados en el mundo (2024).pdf
Los idiomas más hablados en el mundo  (2024).pdfLos idiomas más hablados en el mundo  (2024).pdf
Los idiomas más hablados en el mundo (2024).pdf
 
Adultos Mayores más de 60 años como de la población total (2024).pdf
Adultos Mayores más de 60 años como  de la población total (2024).pdfAdultos Mayores más de 60 años como  de la población total (2024).pdf
Adultos Mayores más de 60 años como de la población total (2024).pdf
 
Investigacion cualitativa y cuantitativa....pdf
Investigacion cualitativa y cuantitativa....pdfInvestigacion cualitativa y cuantitativa....pdf
Investigacion cualitativa y cuantitativa....pdf
 

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