SlideShare a Scribd company logo
1 of 29
Download to read offline
Caso práctico con Hadoop: Un
buscador vertical escalable	
Iván de Prado Alonso, Cofundador de Datasalt	
Twitter: @ivanprado
Contenidos	

§  El problema	
§  La solución obvia	
§  Cuando la solución obvia falla…	
§  … Hadoop viene al rescate	
§  Ventajas y Desventajas	
§  Mejoras
¿Qué es un buscador vertical?	
Proveedor 1

                      Buscador Vertical


              Feed
                                               ue   das
                                          Búsq




Proveedor 2

                                           Búsq
                                                  ueda
                 ed                                       s
               Fe
Algunos de ellos
Arquitectura “obvia”
                                 	
                 Lo primero que llega a la cabeza



   Feed

                     Existe?
                  Ha cambiado?
                Inserta/actualiza   Base de Datos
Descargar y
 Procesar
              Inserta/actualiza



                                       Indice       Search Page
                                    Lucene/Solr
Funcionamiento	

§  Descarga del feed	
§  Para cada registro en el feed	
  •  Comprobar si ya lo tenemos en la BD	
  •  Si ya existe y ha cambiado, actualizar	
     ª la BD	
     ª El índice	
  •  Si no existe, insertar en	
     ª la BD	
     ª el índice
Funcionamiento (II)
                            	
§  La BD proporciona	
  •  Un sistema para comprobar la existencia o no
     de un registro (evitar duplicados)	
  •  Gestión de los datos vía SQL	
§  Lucene/Solr proporciona	
  •    Alta velocidad de búsqueda	
  •    Búsquedas por campos estructurados	
  •    Búsquedas textuales	
  •    Faceting
Pero si todo va bien…	


                                                                       Feed           Feed
                 Feed                 Feed
 Feed                                                           Feed

                                                         Feed                                Feed
                               Feed                                                  Feed
        Feed
                                             Feed                             Feed
                               Feed
Feed
                 Feed Feed                                Feed Feed
                                                       Feed                          Feed
                                      Feed                                                   Feed
                                                                                     Feed
                    Feed
                                                    Feed
                                                Feed                             Feed
                        Feed                                                                        Feed
Feed      Feed                                                  Feed
                                         Feed                                        Feed
Atasco Monumental
“Swiss army knife of the 21st
                                            century”	
                                                         	
Media Guardian Innovation Awards
                                                                                          	




http://www.guardian.co.uk/technology/2011/mar/25/media-guardian-innovation-awards-apache-hadoop
Hadoop	
    “The Apache Hadoop
     software library is a
 framework that allows for
the distributed processing
  of large data sets across
clusters of computers using
   a simple programming
           model”  	
               De la página de Hadoop
Sistema de Ficheros
                         	

§  Sistema de ficheros distribuido (HDFS)	
  •  Bloques grandes: 64 Mb	
  •  Tolerante a Fallos (replicación)	
  •  Habitualmente ristras de pares [clave,
     valor]
MapReduce	
§  Dos funciones (Map y Reduce)	
   •  Map(k, v) : [z,w]*	
   •  Reduce(k, v*) : [z, w]*	
§  Ejemplo: contar palabras	
   •  Map([documento, null]) -> [palabra, 1]*	
   •  Reduce(palabra, 1*) -> [palabra, total]	
§  MapReduce y SQL	
   •  SELECT palabra, count(*) GROUP BY palabra	
§  Ejecución distribuida en un cluster con
    escalabilidad horizontal
Vale, mola mucho, pero…
¿cómo soluciona esto mi
       problema?
Y es que…	


§ Hadoop no es una DB	
§ Hadoop “aparentemente” sólo
   procesa datos	
§ Hadoop no permite “lookups”	
    Hadoop supone un cambio de paradigma
                               	
             que cuesta asimilar
Arquitectura
Filosofía	
§  Reprocesarlo todo siempre. ¡TODO!	
§  ¿Por qué?	
     •  Más tolerante a fallos	
     •  Más flexible	
     •  Más eficiente. Ej:	
       ª    Con un HD de 7200 RPM	
               –  Random IOPS – 100 	
               –  Lectura secuencial – 40 MB/s	
               –  Tamaño de registro: 5 Kb	
       ª    … con que un 1,25% de los registros cambien, es más rápido reescribirlo
             todo que hacer accesos aleatorios de actualización.	
               –  100 MB, 20.000 registros	
                    »  Lectura secuencial: 2,5 sg	
                    »  Lectura aleatoria: 200 sg
Fetcher
                                       	
    Se descarga los feeds y los almacena en el HDFS	

§  MapReduce	
   •  Input: [feed_url, null]*	
            Reducer Task


   •  Mapper: identidad	
   •  Reducer(feed_url,                     Reducer Task

      null*)	
                                             HDFS


       ª  Descargar el feed y
                                            Reducer Task
         subirlo a un
         directorio en el HDFS
Processor
                          	
  Parsea los feeds, los convierte en documentos y los
                        deduplica	
§  MapReduce	
  •  Input: [ruta_feed, null]*	
  •  Map(ruta_feed, null) : [id, documento]*	
     ª Parsea el feed y lo convierte en una serie de
       documentos	
  •  Reducer(id, [documento]*): [id, documento]	
     ª Recibe una lista de documentos y se queda con el
        más reciente (deduplicación)	
     ª Necesidad de un identificador único global
        (idProveedor + idInterno)	
  •  Output: [id, documento]*
Processor (II)
                              	

§  Posible problema:	
   •  Feeds de tamaño muy grande	
      ª No escala, pues no se puede dividir el trabajo	

§  Solución	
   •  Escribir un InputFormat que sea capaz de
      dividir cada feed en cachos procesables
      más pequeños
Serialización	

§  Writables	
   •  Serialización nativa de Hadoop	
   •  De muy bajo nivel	
   •  Tipos básicos: IntWritable, Text, etc.	
§  Otras	
   •  Thrift, Avro, Protostuff	
   •  Compatibilidad hacia atrás.
Indexer
                                 	
                                               Solr en producción




                                  Despliegue
                                      en
Reducer Task                       caliente
                                                Indice - Shard 1
               Indice - Shard 1

                                                                    Servidor Web
                                  Despliegue
Reducer Task                          en
                                   caliente
                                                Indice - Shard 2
               Indice - Shard 2

Reducer Task
                                  Despliegue
                                                                    Servidor Web
                                      en
                                   caliente
                                                Indice - Shard 3
               Indice - Shard 3
Indexer (II)
                                    	
§  SOLR-1301	
   •    https://issues.apache.org/jira/browse/SOLR-1301	
   •    SolrOutputFormat	
   •    1 índice por cada reducer	
   •    Se usa el Partitioner para controlar dónde colocar
        cada documento	
§  Otra opción	
   •  Escribir tu propio código de indexación	
         ª  Creando un nuevo output format	
         ª  Indexado a nivel de reducer. En cada llamada al reducer:	
             –  Abres un índice	
             –  Escribes todos los registros recibidos	
             –  Cierras el índice
Búsqueda y Particionado	
§  Posible particionado	
   •  Horizontal	
      ª Las búsquedas implican todos los shards	
   •  Vertical: por tipo de anuncio, país, etc.	
      ª Las búsquedas se pueden restringir al shard
        implicado	
§  Solr para servir los índices. Posibilidades	
      ª Solr no federado	
          –  En caso de particionamiento vertical	
      ª Distributed Solr	
      ª Solr Cloud
Reconciliado	

                                              Reconciliado                               Siguientes
                     Del Fetcher                                                           pasos
                                                                        Documentos
                                                                        reconciliados
                                      Fichero de la última ejecución



§  ¿Cómo registrar cambios?	
    •    Cambios en el precio, características, etc	
§  Reconciliando.	
    •    MapReduce:	
           ª    Input: [id, documento]*	
                    –  De la anterior ejecución	
                    –  De la ejecución actual	
           ª    Map: identidad	
           ª    Reduce(id, [documento]*) : [id, documento]	
                    –    Te llegan todos los documentos con el mismo ID	
                    –    Comparas los registros nuevos con los viejos	
                    –    Almacenas en el nuevo objeto la información relevante (ej, si ha subido o bajado el precio)	
                    –    Emites un solo documento.	
§  Esto es el patrón más parecido a una BD que se puede ver en Hadoop
Ventajas de la arquitectura	
§  Escala horizontalmente	
    •  Si se programa adecuadamente	
§  Alta tolerancia a fallos y bugs	
    •  Siempre se reprocesa todo	
§  Flexible	
    •  Por su alto desacople, es fácil hacer grandes cambios	
§  Alto desacople	
    •  Los índices son la única interacción entre los
       servidores web y el back-end	
    •  Los servidores web pueden continuar funcionando
       aún en el caso de que el back-end esté roto.
Desventajas
                        	

§  Procesamiento por Lotes (batch
    oriented)	
  •  No es real-time ni “near” real-time	
  •  Ciclos de actualización de horas	
§  Paradigma de programación
    completamente diferente	
  •  Alta curva de aprendizaje
Mejoras
                                	
§  Sistema para las imágenes	
§  Detección difusa de duplicados	
§  Plasam:	
   •  Combinación de esta arquitectura con un sistema que
      actúe como by-pass para proveer actualizaciones
      “near real-time”	
      ª  Implementando un by-pass sobre los Solrs	
      ª  Sistema para mantener la coherencia de los datos	
          –  Sin saltos hacia atrás en el tiempo	
   •  Combina las ventajas de esta arquitectura, pero le
      dota de real-time	
   •  En Datasalt tenemos un prototipo que realiza esta
      función.
Gracias	
Ivan de Prado, 	
ivan@datasalt.com	
@ivanprado

More Related Content

Recently uploaded

International Women's Day Sucre 2024 (IWD)
International Women's Day Sucre 2024 (IWD)International Women's Day Sucre 2024 (IWD)
International Women's Day Sucre 2024 (IWD)GDGSucre
 
pruebas unitarias unitarias en java con JUNIT
pruebas unitarias unitarias en java con JUNITpruebas unitarias unitarias en java con JUNIT
pruebas unitarias unitarias en java con JUNITMaricarmen Sánchez Ruiz
 
Presentación guía sencilla en Microsoft Excel.pptx
Presentación guía sencilla en Microsoft Excel.pptxPresentación guía sencilla en Microsoft Excel.pptx
Presentación guía sencilla en Microsoft Excel.pptxLolaBunny11
 
Proyecto integrador. Las TIC en la sociedad S4.pptx
Proyecto integrador. Las TIC en la sociedad S4.pptxProyecto integrador. Las TIC en la sociedad S4.pptx
Proyecto integrador. Las TIC en la sociedad S4.pptx241521559
 
Global Azure Lima 2024 - Integración de Datos con Microsoft Fabric
Global Azure Lima 2024 - Integración de Datos con Microsoft FabricGlobal Azure Lima 2024 - Integración de Datos con Microsoft Fabric
Global Azure Lima 2024 - Integración de Datos con Microsoft FabricKeyla Dolores Méndez
 
Trabajo Mas Completo De Excel en clase tecnología
Trabajo Mas Completo De Excel en clase tecnologíaTrabajo Mas Completo De Excel en clase tecnología
Trabajo Mas Completo De Excel en clase tecnologíassuserf18419
 
Desarrollo Web Moderno con Svelte 2024.pdf
Desarrollo Web Moderno con Svelte 2024.pdfDesarrollo Web Moderno con Svelte 2024.pdf
Desarrollo Web Moderno con Svelte 2024.pdfJulian Lamprea
 
guía de registro de slideshare por Brayan Joseph
guía de registro de slideshare por Brayan Josephguía de registro de slideshare por Brayan Joseph
guía de registro de slideshare por Brayan JosephBRAYANJOSEPHPEREZGOM
 
POWER POINT YUCRAElabore una PRESENTACIÓN CORTA sobre el video película: La C...
POWER POINT YUCRAElabore una PRESENTACIÓN CORTA sobre el video película: La C...POWER POINT YUCRAElabore una PRESENTACIÓN CORTA sobre el video película: La C...
POWER POINT YUCRAElabore una PRESENTACIÓN CORTA sobre el video película: La C...silviayucra2
 
EPA-pdf resultado da prova presencial Uninove
EPA-pdf resultado da prova presencial UninoveEPA-pdf resultado da prova presencial Uninove
EPA-pdf resultado da prova presencial UninoveFagnerLisboa3
 

Recently uploaded (10)

International Women's Day Sucre 2024 (IWD)
International Women's Day Sucre 2024 (IWD)International Women's Day Sucre 2024 (IWD)
International Women's Day Sucre 2024 (IWD)
 
pruebas unitarias unitarias en java con JUNIT
pruebas unitarias unitarias en java con JUNITpruebas unitarias unitarias en java con JUNIT
pruebas unitarias unitarias en java con JUNIT
 
Presentación guía sencilla en Microsoft Excel.pptx
Presentación guía sencilla en Microsoft Excel.pptxPresentación guía sencilla en Microsoft Excel.pptx
Presentación guía sencilla en Microsoft Excel.pptx
 
Proyecto integrador. Las TIC en la sociedad S4.pptx
Proyecto integrador. Las TIC en la sociedad S4.pptxProyecto integrador. Las TIC en la sociedad S4.pptx
Proyecto integrador. Las TIC en la sociedad S4.pptx
 
Global Azure Lima 2024 - Integración de Datos con Microsoft Fabric
Global Azure Lima 2024 - Integración de Datos con Microsoft FabricGlobal Azure Lima 2024 - Integración de Datos con Microsoft Fabric
Global Azure Lima 2024 - Integración de Datos con Microsoft Fabric
 
Trabajo Mas Completo De Excel en clase tecnología
Trabajo Mas Completo De Excel en clase tecnologíaTrabajo Mas Completo De Excel en clase tecnología
Trabajo Mas Completo De Excel en clase tecnología
 
Desarrollo Web Moderno con Svelte 2024.pdf
Desarrollo Web Moderno con Svelte 2024.pdfDesarrollo Web Moderno con Svelte 2024.pdf
Desarrollo Web Moderno con Svelte 2024.pdf
 
guía de registro de slideshare por Brayan Joseph
guía de registro de slideshare por Brayan Josephguía de registro de slideshare por Brayan Joseph
guía de registro de slideshare por Brayan Joseph
 
POWER POINT YUCRAElabore una PRESENTACIÓN CORTA sobre el video película: La C...
POWER POINT YUCRAElabore una PRESENTACIÓN CORTA sobre el video película: La C...POWER POINT YUCRAElabore una PRESENTACIÓN CORTA sobre el video película: La C...
POWER POINT YUCRAElabore una PRESENTACIÓN CORTA sobre el video película: La C...
 
EPA-pdf resultado da prova presencial Uninove
EPA-pdf resultado da prova presencial UninoveEPA-pdf resultado da prova presencial Uninove
EPA-pdf resultado da prova presencial Uninove
 

Featured

Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Applitools
 

Featured (20)

Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
 

Buscador vertical escalable con Hadoop

  • 1. Caso práctico con Hadoop: Un buscador vertical escalable Iván de Prado Alonso, Cofundador de Datasalt Twitter: @ivanprado
  • 2. Contenidos §  El problema §  La solución obvia §  Cuando la solución obvia falla… §  … Hadoop viene al rescate §  Ventajas y Desventajas §  Mejoras
  • 3. ¿Qué es un buscador vertical? Proveedor 1 Buscador Vertical Feed ue das Búsq Proveedor 2 Búsq ueda ed s Fe
  • 5. Arquitectura “obvia” Lo primero que llega a la cabeza Feed Existe? Ha cambiado? Inserta/actualiza Base de Datos Descargar y Procesar Inserta/actualiza Indice Search Page Lucene/Solr
  • 6. Funcionamiento §  Descarga del feed §  Para cada registro en el feed •  Comprobar si ya lo tenemos en la BD •  Si ya existe y ha cambiado, actualizar ª la BD ª El índice •  Si no existe, insertar en ª la BD ª el índice
  • 7. Funcionamiento (II) §  La BD proporciona •  Un sistema para comprobar la existencia o no de un registro (evitar duplicados) •  Gestión de los datos vía SQL §  Lucene/Solr proporciona •  Alta velocidad de búsqueda •  Búsquedas por campos estructurados •  Búsquedas textuales •  Faceting
  • 8. Pero si todo va bien… Feed Feed Feed Feed Feed Feed Feed Feed Feed Feed Feed Feed Feed Feed Feed Feed Feed Feed Feed Feed Feed Feed Feed Feed Feed Feed Feed Feed Feed Feed Feed Feed Feed Feed Feed
  • 10. “Swiss army knife of the 21st century” Media Guardian Innovation Awards http://www.guardian.co.uk/technology/2011/mar/25/media-guardian-innovation-awards-apache-hadoop
  • 11. Hadoop “The Apache Hadoop software library is a framework that allows for the distributed processing of large data sets across clusters of computers using a simple programming model” De la página de Hadoop
  • 12. Sistema de Ficheros §  Sistema de ficheros distribuido (HDFS) •  Bloques grandes: 64 Mb •  Tolerante a Fallos (replicación) •  Habitualmente ristras de pares [clave, valor]
  • 13. MapReduce §  Dos funciones (Map y Reduce) •  Map(k, v) : [z,w]* •  Reduce(k, v*) : [z, w]* §  Ejemplo: contar palabras •  Map([documento, null]) -> [palabra, 1]* •  Reduce(palabra, 1*) -> [palabra, total] §  MapReduce y SQL •  SELECT palabra, count(*) GROUP BY palabra §  Ejecución distribuida en un cluster con escalabilidad horizontal
  • 14. Vale, mola mucho, pero… ¿cómo soluciona esto mi problema?
  • 15. Y es que… § Hadoop no es una DB § Hadoop “aparentemente” sólo procesa datos § Hadoop no permite “lookups” Hadoop supone un cambio de paradigma que cuesta asimilar
  • 17. Filosofía §  Reprocesarlo todo siempre. ¡TODO! §  ¿Por qué? •  Más tolerante a fallos •  Más flexible •  Más eficiente. Ej: ª  Con un HD de 7200 RPM –  Random IOPS – 100 –  Lectura secuencial – 40 MB/s –  Tamaño de registro: 5 Kb ª  … con que un 1,25% de los registros cambien, es más rápido reescribirlo todo que hacer accesos aleatorios de actualización. –  100 MB, 20.000 registros »  Lectura secuencial: 2,5 sg »  Lectura aleatoria: 200 sg
  • 18. Fetcher Se descarga los feeds y los almacena en el HDFS §  MapReduce •  Input: [feed_url, null]* Reducer Task •  Mapper: identidad •  Reducer(feed_url, Reducer Task null*) HDFS ª  Descargar el feed y Reducer Task subirlo a un directorio en el HDFS
  • 19. Processor Parsea los feeds, los convierte en documentos y los deduplica §  MapReduce •  Input: [ruta_feed, null]* •  Map(ruta_feed, null) : [id, documento]* ª Parsea el feed y lo convierte en una serie de documentos •  Reducer(id, [documento]*): [id, documento] ª Recibe una lista de documentos y se queda con el más reciente (deduplicación) ª Necesidad de un identificador único global (idProveedor + idInterno) •  Output: [id, documento]*
  • 20. Processor (II) §  Posible problema: •  Feeds de tamaño muy grande ª No escala, pues no se puede dividir el trabajo §  Solución •  Escribir un InputFormat que sea capaz de dividir cada feed en cachos procesables más pequeños
  • 21. Serialización §  Writables •  Serialización nativa de Hadoop •  De muy bajo nivel •  Tipos básicos: IntWritable, Text, etc. §  Otras •  Thrift, Avro, Protostuff •  Compatibilidad hacia atrás.
  • 22. Indexer Solr en producción Despliegue en Reducer Task caliente Indice - Shard 1 Indice - Shard 1 Servidor Web Despliegue Reducer Task en caliente Indice - Shard 2 Indice - Shard 2 Reducer Task Despliegue Servidor Web en caliente Indice - Shard 3 Indice - Shard 3
  • 23. Indexer (II) §  SOLR-1301 •  https://issues.apache.org/jira/browse/SOLR-1301 •  SolrOutputFormat •  1 índice por cada reducer •  Se usa el Partitioner para controlar dónde colocar cada documento §  Otra opción •  Escribir tu propio código de indexación ª  Creando un nuevo output format ª  Indexado a nivel de reducer. En cada llamada al reducer: –  Abres un índice –  Escribes todos los registros recibidos –  Cierras el índice
  • 24. Búsqueda y Particionado §  Posible particionado •  Horizontal ª Las búsquedas implican todos los shards •  Vertical: por tipo de anuncio, país, etc. ª Las búsquedas se pueden restringir al shard implicado §  Solr para servir los índices. Posibilidades ª Solr no federado –  En caso de particionamiento vertical ª Distributed Solr ª Solr Cloud
  • 25. Reconciliado Reconciliado Siguientes Del Fetcher pasos Documentos reconciliados Fichero de la última ejecución §  ¿Cómo registrar cambios? •  Cambios en el precio, características, etc §  Reconciliando. •  MapReduce: ª  Input: [id, documento]* –  De la anterior ejecución –  De la ejecución actual ª  Map: identidad ª  Reduce(id, [documento]*) : [id, documento] –  Te llegan todos los documentos con el mismo ID –  Comparas los registros nuevos con los viejos –  Almacenas en el nuevo objeto la información relevante (ej, si ha subido o bajado el precio) –  Emites un solo documento. §  Esto es el patrón más parecido a una BD que se puede ver en Hadoop
  • 26. Ventajas de la arquitectura §  Escala horizontalmente •  Si se programa adecuadamente §  Alta tolerancia a fallos y bugs •  Siempre se reprocesa todo §  Flexible •  Por su alto desacople, es fácil hacer grandes cambios §  Alto desacople •  Los índices son la única interacción entre los servidores web y el back-end •  Los servidores web pueden continuar funcionando aún en el caso de que el back-end esté roto.
  • 27. Desventajas §  Procesamiento por Lotes (batch oriented) •  No es real-time ni “near” real-time •  Ciclos de actualización de horas §  Paradigma de programación completamente diferente •  Alta curva de aprendizaje
  • 28. Mejoras §  Sistema para las imágenes §  Detección difusa de duplicados §  Plasam: •  Combinación de esta arquitectura con un sistema que actúe como by-pass para proveer actualizaciones “near real-time” ª  Implementando un by-pass sobre los Solrs ª  Sistema para mantener la coherencia de los datos –  Sin saltos hacia atrás en el tiempo •  Combina las ventajas de esta arquitectura, pero le dota de real-time •  En Datasalt tenemos un prototipo que realiza esta función.
  • 29. Gracias Ivan de Prado, ivan@datasalt.com @ivanprado