tutorial en apache spark - clasificando tweets en realtime

43
Tutorial en Apache Spark Clasificando Tweets en Realtime Gustavo Arjones [email protected] @arjones

Upload: socialmetrix

Post on 05-Jul-2015

1.897 views

Category:

Technology


3 download

DESCRIPTION

Apache Spark [1] es un nuevo framework de procesamiento distribuido para big data, escrito en Scala con wrappers para Python, que viene generando mucha atención de la comunidad por su potencia, simplicidad de uso y velocidad de procesamiento. Ya siendo llamado como el remplazo de Apache Hadoop. Socialmetrix desarrolla soluciones en este framework para generar reportes y dashboards de información a partir de los datos extraídos de redes sociales. Los participantes de este tutorial van aprender a levantar información de Twitter usando Spark Streaming, Desarrollar algoritmos para calcular hashtags más frecuentes, usuarios más activos en batch processing aplicarlos en realtime a los nuevos tweets que lleguen a través del stream.

TRANSCRIPT

Page 1: Tutorial en Apache Spark - Clasificando tweets en realtime

Tutorial en Apache Spark Clasificando Tweets en Realtime Gustavo Arjones [email protected] @arjones

Page 2: Tutorial en Apache Spark - Clasificando tweets en realtime

AGENDA

•  Qué es Apache Spark?

•  Introducción a Scala

•  Crear un pipeline con Apache Spark (Word Count)

•  Cargar JSON de Tweets (Statuses)

•  Crear un programa que consume del stream (simulado)

•  Obtener los lenguajes de programación más hablados

•  Por usuario, por url, por localización

Page 3: Tutorial en Apache Spark - Clasificando tweets en realtime

Qué es Apache Spark?

Page 4: Tutorial en Apache Spark - Clasificando tweets en realtime

Qué es Spark? Apache Spark™ is a fast and general engine for large-scale data processing. •  Procesamiento In-memory (preferentemente)

•  Framework de Procesamiento Unificado

•  Para Ingenieros & Data Scientists

Page 5: Tutorial en Apache Spark - Clasificando tweets en realtime

Principales Pilares Task Scheduler •  Prepara los jobs a través de DAG (Directed acyclic graph) •  Concatena funciones para ejecutar los stages •  Cache-aware; considera utilización & localización de datos

(data locality) •  Partitioning-aware para reducir shuffles por la red

RDD (Resilient Distributed Datasets) •   Estructura de datos Inmutable (In-memory) •  Tolerante a fallas (Se rearma en caso de falla) •  Estructura de datos que puede ser operada en paralelo • Rica interfaz de Transformations & Actions

Page 6: Tutorial en Apache Spark - Clasificando tweets en realtime

Plataforma Unificada

Page 7: Tutorial en Apache Spark - Clasificando tweets en realtime

Hands On!

Page 8: Tutorial en Apache Spark - Clasificando tweets en realtime

Para que los ejercicios sean realizados dentro del tiempo establecido para el laboratorio los datasets son chicos.

Las soluciones que desarrollamos acá pueden escalar para cientos de servidores y Terabytes de datos

Las técnicas se aplican a mayor Volumen y Velocidad: Internet Of Things (IoT), Logs, games, mobile, etc

DISCLAIMER

Page 9: Tutorial en Apache Spark - Clasificando tweets en realtime

Introducción a #Scala

Page 10: Tutorial en Apache Spark - Clasificando tweets en realtime

Declarando Variables

val    à  declara  variables  inmutables  (final  en  Java)  

Page 11: Tutorial en Apache Spark - Clasificando tweets en realtime

Declarando Función Crear una función que calcule el valor al cubo

def  à  declara  función  

scala> cube(10) res0: Int = 1000

Page 12: Tutorial en Apache Spark - Clasificando tweets en realtime

Usar MAP NOTA: Es una función, no la estructura de datos! Aplicar la función cube() a la lista de números myNumbers

scala> myNumbers.map(cube(_)) scala> myNumbers.map(cube)

Page 13: Tutorial en Apache Spark - Clasificando tweets en realtime

Usar Map and Tuples Tuples son estructura auxiliares que permiten llevar multiplos valores sin necesidad de crear clases (VO)

scala> myNumbers.map(n => (n, cube(n))) res1: List[(Int, Int)] = List((1,1), (2,8), (5,125), (4,64), (7,343), (3,27)) scala> myNumbers.map(n => (n, cube(n))).foreach(println) (1,1) (2,8) (5,125) (4,64) (7,343) (3,27)

Page 14: Tutorial en Apache Spark - Clasificando tweets en realtime

Usar Filter Aplicar Filter a la lista myNumbers dejando solo impares

scala> myNumbers.filter(n => (n % 2) == 1) res6: List[Int] = List(1, 5, 7, 3)

scala> myNumbers.filter(_ % 2 == 1) res6: List[Int] = List(1, 5, 7, 3)

Page 15: Tutorial en Apache Spark - Clasificando tweets en realtime

Usar Reduce Sumar todos los elementos de la lista

scala> myNumbers.reduce((x, y) => x + y) res10: Int = 22 scala> myNumbers.reduce(_ + _)

Page 16: Tutorial en Apache Spark - Clasificando tweets en realtime

CHALLENGE Sumar todos los números pares en el rango de 0-99

scala> numbers.filter(_ % 2 == 0).reduce(_ + _) res2: Int = 2450

TIP: scala> val numbers = Range(0, 100) numbers: scala.collection.immutable.Range = Range(0, 1, ..)

Page 17: Tutorial en Apache Spark - Clasificando tweets en realtime

Creando el primero pipeline con Apache Spark Código Fuente: https://github.com/socialmetrix/wisit14

Page 18: Tutorial en Apache Spark - Clasificando tweets en realtime

Contar Palabras

Page 19: Tutorial en Apache Spark - Clasificando tweets en realtime

data/don-­‐quijote.txt.gz  

Page 20: Tutorial en Apache Spark - Clasificando tweets en realtime

data/don-­‐quijote.txt.gz  

Page 21: Tutorial en Apache Spark - Clasificando tweets en realtime

data/don-­‐quijote.txt.gz  

Page 22: Tutorial en Apache Spark - Clasificando tweets en realtime

data/don-­‐quijote.txt.gz  

Page 23: Tutorial en Apache Spark - Clasificando tweets en realtime

data/don-­‐quijote.txt.gz  

Page 24: Tutorial en Apache Spark - Clasificando tweets en realtime

data/don-­‐quijote.txt.gz  

Page 25: Tutorial en Apache Spark - Clasificando tweets en realtime

data/don-­‐quijote.txt.gz  

Page 26: Tutorial en Apache Spark - Clasificando tweets en realtime

Apache Spark es Lazy!

Viste que no pasó nada hasta la última linea?

Nada es procesado entre Transformaciones. Solo se ejecuta cuando se realiza una Acción (top)

Page 27: Tutorial en Apache Spark - Clasificando tweets en realtime

API muy expresiva, mucho más operaciones!

Ver: https://spark.apache.org/docs/latest/api/scala/#org.apache.spark.rdd.RDD

Page 28: Tutorial en Apache Spark - Clasificando tweets en realtime

CHALLENGE El resultado no es muy interesante, porque las principales palabras son stopwords, remueverlas para dar mayor significado

Page 29: Tutorial en Apache Spark - Clasificando tweets en realtime

Manipulando Tweets

Page 30: Tutorial en Apache Spark - Clasificando tweets en realtime

Propuesta Crear un listado de los lenguajes más tweetados, similar al listado de lenguajes que crea Github

http://adambard.com/blog/top-github-languages-2014/

Page 31: Tutorial en Apache Spark - Clasificando tweets en realtime

Consideraciones

•  Dataset contiene un JSON por linea (one-liner)

•  Hay que interpretar JSON

•  Pueden haber erroes en los JSON –  Lineas vacias

–  Lineas malformadas / Diferentes schemas

Page 32: Tutorial en Apache Spark - Clasificando tweets en realtime
Page 33: Tutorial en Apache Spark - Clasificando tweets en realtime

Obtener las TOP HASHTAGS (batch mode) Ver archivo ./src/main/scala/smx/sql/TopHashtags.scala Compilar y Ejecutar ./sbt/sbt assembly spark-submit \ --class smx.sql.TopHashtags \ target/scala-2.10/wisit2014-spark-assembly-0.0.1.jar \ data/tweets-20141126-sample.json

Page 34: Tutorial en Apache Spark - Clasificando tweets en realtime

Procesando tweets en Real-time

Page 35: Tutorial en Apache Spark - Clasificando tweets en realtime

Stream es una secuencia de RDD

Page 36: Tutorial en Apache Spark - Clasificando tweets en realtime

Streaming Ver archivos ./src/main/scala/smx/utils/SocketServer.scala Iniciar SocketServer (simula Twitter Streaming) java \ -cp target/scala-2.10/wisit2014-spark-assembly-0.0.1.jar \ smx.utils.SocketServer \ data/tweets-20141126-sample.json

Page 37: Tutorial en Apache Spark - Clasificando tweets en realtime

Streaming (cont.) Ver archivo ./src/main/scala/smx/stream/StreamProcessor.scala Iniciar Streaming Processor spark-submit \ --class smx.stream.StreamProcessor \ target/scala-2.10/wisit2014-spark-assembly-0.0.1.jar

Page 38: Tutorial en Apache Spark - Clasificando tweets en realtime

h)p://localhost:4040/  

Page 39: Tutorial en Apache Spark - Clasificando tweets en realtime

CHALLENGE Cambiar de Hashtags para TOP Usuarios

TIP: El usuario es user.screen_name en el JSON

Page 40: Tutorial en Apache Spark - Clasificando tweets en realtime

Usando SparkStreaming con Twitter (necesita conexión de internet) Training Oficial 2014 Stream Processing with Spark Streaming https://databricks-training.s3.amazonaws.com/realtime-processing-with-spark-streaming.html

Page 41: Tutorial en Apache Spark - Clasificando tweets en realtime

Donde aprender más?

Page 42: Tutorial en Apache Spark - Clasificando tweets en realtime

Mucha documentación disponible https://spark.apache.org/documentation.html http://spark-summit.org/2014/training http://arjon.es/tag/spark/ http://www.slideshare.net/frodriguezolivera/apache-spark-41601032 First Steps to Scala http://www.artima.com/scalazine/articles/steps.html

http://shop.oreilly.com/product/0636920028512.do

Page 43: Tutorial en Apache Spark - Clasificando tweets en realtime

Gracias & Obrigado!

Gustavo Arjones [email protected] @arjones

[email protected]