Docsity
Top Seller

Big Data Processing and Analytics, Appunti di Elementi di Informatica

Toggle sidebar
bg1
1
Big Data processing and analytics
Index
INTRODUCTION TO BIG DATA .................................................................................................................................. 1
SINGLE-NODE ARCHITECTURE ................................................................................................................................................. 1
CLUSTER ARCHITECTURE ....................................................................................................................................................... 1
BIG DATA ARCHITECTURES ....................................................................................................................................... 2
LAMBDA ARCHITECTURE ....................................................................................................................................................... 3
Data Processing Paths ................................................................................................................................................ 3
INTRODUCTION TO HADOOP AND MAPREDUCE ....................................................................................................... 4
MAPREDUCE ...................................................................................................................................................................... 6
Data structures ........................................................................................................................................................... 8
Algorithms .................................................................................................................................................................. 8
HOW TO WRITE MAPREDUCE PROGRAMS IN HADOOP ............................................................................................ 9
DATA TYPES ...................................................................................................................................................................... 10
INPUT FORMAT ................................................................................................................................................................. 10
OUTPUTFORMAT ............................................................................................................................................................... 11
DRIVER PROGRAM ............................................................................................................................................................. 12
MAPPER PROGRAM ........................................................................................................................................................... 13
REDUCER PROGRAM........................................................................................................................................................... 14
COMBINER ....................................................................................................................................................................... 15
PERSONALIZED DATA TYPES AND VALUES .............................................................................................................................. 16
SHARING PARAMETERS AMONG DRIVER, MAPPERS AND REDUCERS ............................................................................................. 17
COUNTERS ....................................................................................................................................................................... 18
MAP ONLY JOB .................................................................................................................................................................. 19
IN-MAPPER COMBINER ....................................................................................................................................................... 20
MAPREDUCE AND HADOOP: ADVANCED TOPICS .................................................................................................... 22
MULTIPLE INPUTS .............................................................................................................................................................. 22
DISTRIBUTED CACHE ........................................................................................................................................................... 22
MAPREDUCE PATTERNS ......................................................................................................................................... 23
SUMMARIZATION PATTERNS ................................................................................................................................................ 23
FILTERING PATTERNS .......................................................................................................................................................... 26
DATA ORGANIZATION PATTERNS ........................................................................................................................................... 28
Shuffling .................................................................................................................................................................... 28
METAPATTERNS ................................................................................................................................................................ 29
Job chaining .............................................................................................................................................................. 29
JOINPATTERNS .................................................................................................................................................................. 30
Reduce side natural join ............................................................................................................................................ 30
Map side natural join ................................................................................................................................................ 31
Theta-join, Semi-join, Outer-join ............................................................................................................................... 31
RELATIONAL ALGEBRA OPERATIONS AND MAPREDUCE.......................................................................................... 31
SELECTION ........................................................................................................................................................................ 32
PROJECTION ..................................................................................................................................................................... 32
UNION ............................................................................................................................................................................ 33
INTERSECTION ................................................................................................................................................................... 33
DIFFERENCE ...................................................................................................................................................................... 33
JOIN ................................................................................................................................................................................ 34
AGGREGATIONS AND GROUP BY ........................................................................................................................................... 34
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54
pf55
pf56
pf57
pf58
pf59
pf5a
pf5b
pf5c
pf5d
pf5e
pf5f
pf60
pf61
pf62
pf63
pf64

Anteprima parziale del testo

Scarica Big Data Processing and Analytics e più Appunti in PDF di Elementi di Informatica solo su Docsity!

Big Data processing and analytics

20 – (MAP ONLY JOB WITH MULTIPLE OUTPUTS) SPLIT THE READINGS OF A SET OF SENSORS BASED ON THE VALUE OF THE MEASUREMENT

47 ................................................................................................................................................................................ 211 48 ................................................................................................................................................................................ 211 49 ................................................................................................................................................................................ 212

  • INTRODUCTION TO BIG DATA Index
    • SINGLE-NODE ARCHITECTURE
    • CLUSTER ARCHITECTURE
  • BIG DATA ARCHITECTURES
    • LAMBDA ARCHITECTURE
      • Data Processing Paths
  • INTRODUCTION TO HADOOP AND MAPREDUCE
    • MAPREDUCE
      • Data structures
      • Algorithms
  • HOW TO WRITE MAPREDUCE PROGRAMS IN HADOOP
    • DATA TYPES......................................................................................................................................................................
    • INPUT FORMAT
    • OUTPUTFORMAT
    • DRIVER PROGRAM
    • MAPPER PROGRAM
    • REDUCER PROGRAM...........................................................................................................................................................
    • COMBINER
    • PERSONALIZED DATA TYPES AND VALUES
    • SHARING PARAMETERS AMONG DRIVER, MAPPERS AND REDUCERS
    • COUNTERS
    • MAP ONLY JOB
    • IN-MAPPER COMBINER
  • MAPREDUCE AND HADOOP: ADVANCED TOPICS
    • MULTIPLE INPUTS
    • DISTRIBUTED CACHE
  • MAPREDUCE PATTERNS
    • SUMMARIZATION PATTERNS
    • FILTERING PATTERNS
    • DATA ORGANIZATION PATTERNS
      • Shuffling
    • METAPATTERNS
      • Job chaining
    • JOINPATTERNS
      • Reduce side natural join............................................................................................................................................
      • Map side natural join
      • Theta-join, Semi-join, Outer-join
  • RELATIONAL ALGEBRA OPERATIONS AND MAPREDUCE..........................................................................................
    • SELECTION........................................................................................................................................................................
    • PROJECTION
    • UNION
    • INTERSECTION
    • DIFFERENCE
    • JOIN
    • AGGREGATIONS AND GROUP BY
  • INTRODUCTION TO SPARK
    • MOTIVATIONS...................................................................................................................................................................
      • Resilient Distributed Data sets (RDDs)
      • Computing Framework
      • MapReduce vs Spark
    • MAIN COMPONENTS
    • BASIC CONCEPTS
      • How RDDs Are Created in Spark
      • Transformations and Actions in Spark
      • Spark framework
    • SPARK PROGRAMS
      • Supported languages
      • Structure of Spark Programs
      • Local Execution
      • Spark official terminology
    • EXAMPLES
  • RDD-BASE PROGRAMMING
    • SPARK CONTEXT.................................................................................................................................................................
    • RDD BASICS
      • RDD creation
      • Save RDDS
      • Retrieve the content of RDDs and store it in local python variables
    • TRANSFORMATIONS AND ACTIONS
    • PASSING FUNCTION TO TRANSFORMATIONS AND ACTIONS
      • Lambda functions vs local defined functions
    • TRANSFORMATIONS
      • Basic Transformations
      • Filter
      • Map...........................................................................................................................................................................
      • FlatMap.....................................................................................................................................................................
      • Distinct
      • SortBy........................................................................................................................................................................
      • Sample
      • Set
      • Summary
    • ACTIONS
      • Basic Actions
      • Collect
      • Count.........................................................................................................................................................................
      • CountByValue
      • Take
      • First
      • Top
      • TakeOrdered
      • TakeSample...............................................................................................................................................................
      • Reduce
      • Fold
      • Aggregate
      • Summary
  • RDDS AND KEY-VALUE PAIRS
    • CREATING RDDS OF KEY-VALUE PAIRS....................................................................................................................................
      • RDDs of key-value pairs by using the Map transformation
      • RDDs of key-value pairs by using the flatMap transformation
      • RDDs of key-value pairs by using parallelize
    • TRANSFORMATIONS ON RDDS OF KEY-VALUE PAIRS
      • ReduceByKey
      • FoldByKey..................................................................................................................................................................
      • CombineByKey
      • Group by Key
      • MapValues
      • FlatMapValues
      • Keys
      • Values
      • SortByKey
      • Summary
    • TRANSFORMATIONS ON TWO RDDS OF KEY-VALUE PAIRS
      • SubtractByKey transformation..................................................................................................................................
      • (Inner) Join transformation
      • (Outer) Join transformations
      • CoGroup transformation
      • Summary
    • ACTIONS ON RDDS OF KEY-VALUE PAIRS
      • CountByKey
      • CollectAsMap
      • Lookup
      • Summary
  • RDDS OF NUMBERS
  • CACHE, ACCUMULATORS, BROADCAST VARIABLES.................................................................................................
    • PERSISTENCE AND CACHE
      • Remove data from cache
    • ACCUMULATORS................................................................................................................................................................
      • Personalized accumulators
    • BROADCAST VARIABLES
  • SPARK SQL AND DATAFRAMES...............................................................................................................................
    • DATAFRAMES
      • Creating DataFrames from csv files
      • Creating DataFrames from JSON files
      • Creating Data Frames from other data sources
      • Creating Data Frames from RDDs or Python lists
    • FROM DATA FRAME TO RDD
    • OPERATIONS ON DATAFRAMES
      • Show
      • printSchema
      • Count.........................................................................................................................................................................
      • Distinct
      • Select.........................................................................................................................................................................
      • SelectExpr..................................................................................................................................................................
      • WithColumnRenamed
      • Filter
      • Where
      • Join
    • AGGREGATE FUNCTIONS
      • groupBy and aggregated functions
      • Sort............................................................................................................................................................................
    • DATAFRAMES AND THE SQL LANGUAGE
    • SAVE DATA FRAMES
    • UDFS: USER DEFINED FUNCTIONS
    • SET METHODS
      • Set transformations
    • BROADCAST JOIN
    • EXECUTION PLAN
  • SPARK MLIB
    • DATA TYPES
      • Local vectors
    • MAIN CONCEPTS................................................................................................................................................................
      • Transformer
      • Estimator
      • Pipeline
    • DATA PREPROCESSING
      • Extracting, transforming and selecting features
      • Feature Transformations
      • Data normalization
  • CLASSIFICATION ALGORITHMS
    • STRUCTURED DATA CLASSIFICATION
      • Logistic regression and structured data..................................................................................................................
      • Training data
      • Unlabeled data
      • Prediction column
      • Pipelines
    • DECISION TREES AND STRUCTURED DATA
    • CATEGORICAL CLASS LABELS
    • TEXTUAL DATA MANAGEMENT AND CLASSIFICATION................................................................................................................
    • CLASSIFICATION: PERFORMANCE EVALUATION
    • CLASSIFICATION: PARAMETER TUNING
  • SPARK STREAMING
    • INTRODUCTION
      • Stream processing frameworks for Big Streaming Data Analytics
      • Input data processing and result guarantees
    • SPARK STREAMING
      • Spark Discretized Stream Processing
      • Fault tolerance
    • SPARK STREAMING PROGRAMS
      • Input Stream
      • TCP socket
      • HDFS folder
      • Other sources
      • Transformations......................................................................................................................................................
      • Start and run the computation
    • WINDOWED COMPUTATION
      • Transformations......................................................................................................................................................
      • Checkpoints
    • STATEFUL COMPUTATION
      • updateStateByKey transformation
    • TRANSFORM TRANSFORMATION
  • MAPREDUCE EXERCISES
    • 2 - WORD COUNT PROBLEM
    • 3 - PM10 POLLUTION ANALYSIS
    • 4 - PM10 POLLUTION ANALYSIS PER CITY ZONE
    • 5 - AVERAGE
    • 5 - WITH COMBINER AND PERSONALIZED DATA TYPE
    • 6 - MAX AND MIN
    • 6 - WITH COMBINER
    • 6 - WITH COMBINER AND PERSONALIZED DATA TYPE
    • 7 – INVERTED INDEX
    • 8 - (2 JOBS) TOTAL INCOME FOR EACH MONTH OF THE YEAR AND AVERAGE MONTHLY INCOME PER YEAR
    • 8 - SINGLEJOB
    • 9 - WORD COUNT PROBLEM WITH IN-MAPPER COMBINERS
    • 10 - (MAP ONLY JOB WITH COUNTER) TOTAL COUNT
    • 11 – (PERSONALIZED DATA TYPE AND IN-MAPPER COMBINER) AVERAGE
    • 12 – (MAP ONLY JOB WITH SHARED PARAMETERS) SELECT OUTLIERS
    • 13 - TOP 1 MOST PROFITABLE DATE
    • 13BIS – TOP 2 MOST PROFITABLE DATES
    • 14 – (DISTINCT PATTERN) DICTIONARY
    • 15 - DICTIONARY- MAPPING WORD – INTEGER
    • 17 – (MULTIPLE INPUTS) SELECT MAXIMUM TEMPERATURE FOR EACH DATE
    • 20BIS............................................................................................................................................................................
    • 21 - (MAP ONLY JOB WITH DISTRIBUTED CACHE) STOPWORD ELIMINATION PROBLEM
    • 22 – (SUMMARIZATION PATTERN) FRIENDS OF A SPECIFIC USER................................................................................................
    • 23 – (TWO JOBS) POTENTIAL FRIENDS OF A SPECIFIC USER
    • 23 – (ONE JOB AND ONE REDUCER)
    • 23 - (DISTRIBUTED CACHE)
    • 23BIS............................................................................................................................................................................
    • 24 - COMPUTE THE LIST OF FRIENDS FOR EACH USER
    • 25 - COMPUTE THE LIST OF POTENTIAL FRIENDS FOR EACH USER
    • 26 – (MAP ONLY JOB WITH DISTRIBUTED CACHE) WORD (STRING) TO INTEGER CONVERSION
    • 28 – (REDUCE SIDE JOIN) MAPPING QUESTION-ANSWER(S)....................................................................................................
    • 29 – (REDUCE SIDE JOIN) USER SELECTION
  • SPARK EXERCISES.................................................................................................................................................
    • 31 - LOG ANALYSIS
    • 32 - MAXIMUM VALUE
    • 33 – TOP-K MAXIMUM VALUES
    • 34 – READINGS ASSOCIATED WITH THE MAXIMUM VALUE
    • 35 – DATES ASSOCIATED WITH THE MAXIMUM VALUE
    • 36 - AVERAGE VALUE
    • 37 – MAXIMUM VALUES
    • 38 – POLLUTION ANALYSIS
    • 39 – CRITICAL DATES ANALYSIS
    • 39 BIS
    • 40 - ORDER SENSORS BY NUMBER OF CRITICAL DAYS
    • 41 - TOP-K MOST CRITICAL SENSORS
    • 42 – MAPPING QUESTION-ANSWER(S)
    • 43 - CRITICAL BIKE SHARING STATION ANALYSIS
    • 44 - MISLEADING PROFILE SELECTION
    • 45 – PROFILE UPDATE
    • 46 – TIME SERIES ANALYSIS
  • SPARKSQL EXERCISES
    • 50_NEW - MORE CRITICAL THAN NORMAL VALUES
  • LABS
    • LAB
    • LAB

As data volumes and user demands grow, scalability is required:

- Vertical scaling (scale up): adding more power/resources (CPU, RAM) to a single node (high-performing- servers). Downside: supercomputers become disproportionately expensive; cost of super-computers is not linear with respect to their resources. - Horizontal scaling (scale out): adding more low-cost nodes (commodity servers) to a system. Costs grow almost linearly with respect to the number of added nodes. Data center efficiency is a difficult problem to solve. For data-intensive workloads, a large number of commodity servers is preferred over a small number of high- performing servers. At the same cost, we can deploy a system that processes data more efficiently and is more fault tolerant. Horizontal scalability (scale out) is preferred for big data applications. However, it introduces the complexity of distributed computing → New systems hiding the complexity of the distributed part of the problem to developers are needed Key challenges in cluster computing include: - Distributed programming: dividing problems, parallelizing tasks, synchronizing processes, and scheduling distributed applications to maximize performance and reduce failures. - Distributed storage: ensuring persistence even if nodes fail. Redundancy helps but adds complexity. - Network bottlenecks: mitigated by reducing data transfers and bringing computation closer to data. Distributed computing is not new: since the 1960s there was High-Performance Computing, in the 1990s Grid Computing and distributed databases. However, Big Data volumes demand newer and more advanced solutions, as traditional techniques are no longer sufficient.

Big Data Architectures

A Big Data architecture is designed to handle ingestion, processing, and analysis of data that is too large or complex for traditional database systems. It usually covers multiple workloads:

- Batch processing of large “at rest” datasets, - Real-time processing of streaming data “in motion,” - Interactive data analysis, - Predictive analytics & Machine Learning to extract models and patterns. This architecture is useful when: - datasets are too large for traditional databases, - unstructured data must be transformed into useful information, - continuous data streams must be captured and analysed in real time or with low latency. The most widely used architecture is the Lambda Architecture , proposed by Nathan Marz in 2011. Before this, scalable systems like Hadoop (for large-scale batch processing) and NoSQL databases (e.g., Cassandra, Riak) emerged. Each solved specific problems but had trade-offs: - Hadoop: excellent for batch parallel processing, but high latency → unsuitable for real-time needs. - NoSQL databases: scalable but less flexible than SQL; mutable, hence more error prone. Individually, these tools are not universal solutions. But when integrated intelligently, they form scalable, fault-tolerant systems while keeping complexity manageable. This is the core idea behind the Lambda Architecture , which combines their strengths to provide a balanced and complete view of data.

Lambda Architecture

The Lambda Architecture is designed to process massive datasets by combining batch processing and stream processing. It balances three key aspects: latency, throughput, and fault tolerance.

- Batch processing ensures a complete and accurate view of historical data. It stores all the incoming data in its raw form and performs batch processing on the data. The result of this processing is stored as batch views. - Stream processing provides real-time insights from incoming data. This bath is designed for low latency, at the expense of accuracy. It relies on an append-only, immutable data model : new events are added in chronological order without modifying existing data, preserving a single “source of truth.” The architecture is fault-tolerant to both hardware and human errors, supports low-latency queries, fast updates, linear scalability by adding nodes, and extensibility for future functionalities. Queries are treated as functions on the entire dataset. Their key properties are: - Latency : the time it takes to run a query, - Freshness : how up-to-date results are, - Accuracy : often traded off for scalability and performance, sometimes allowing approximations.

Data Processing Paths

Lambda Architecture has two main layers: cold path (batch layer) and hot path (speed layer). All data entering the system is dispatched to both the batch layer and the speed layer for processing. The batch layer has two functions:

- managing the master dataset (an immutable, append-only set of raw data) - Performs batch computations to produce batch views (complete pre-computed results). The serving layer indexes the batch views so that they can be queried in low-latency, ad-hoc way. Merges historical (batch) and recent (real-time) results into unified, up-to-date views. When a query is executed, the final result is obtained by combining batch views (accurate but less fresh) with real-time views (fresh but less precise). The speed layer compensates for the high latency of updates to the serving layer and deals with recent data only. Any incoming query can be answered by merging results from batch views and real-time views. Processes the most recent data in real time or near real time, sacrifices some accuracy for low latency and provides immediate insights using streaming technologies.

To avoid these issues, it’s best to combine small files into larger ones before loading them into HDFS. Other solutions include using Hadoop Archives or container formats like SequenceFiles and Avro. By organizing data this way, Hadoop can manage it efficiently, ensuring better performance and scalability. Client applications interact with HDFS through dedicated APIs. When a client wants to access a file, it first communicates with the master node to discover which chunk servers hold the relevant pieces of data. Once this information is obtained, the client then connects directly to the corresponding chunk servers to read or write the data. Beyond the core Hadoop infrastructure, a variety of related projects and systems have been developed to extend its capabilities and target specific types of problems. Some key examples include:

- Hive : a distributed relational database built on top of MapReduce, which enables users to query data stored in HDFS using a SQL-like language. - HBase : a distributed, column-oriented database that leverages HDFS for persistent storage. - Pig : a high-level data flow language and execution environment, also based on MapReduce, designed for analyzing and processing very large datasets. → it is no longer available - Sqoop : a tool that facilitates efficient transfer of data between traditional relational databases (or flat files) and HDFS. - ZooKeeper : a distributed coordination service that provides essential primitives, such as distributed locks, to manage large-scale, distributed applications. Each of these systems is designed to solve a specific class of problems, making the Hadoop ecosystem both flexible and extensible. RESUME: Hadoop is a framework made to handle very large datasets by splitting them across many computers (a cluster). It’s great for data-intensive workloads, not for heavy calculations — that’s what high-performance computing (HPC) is for.

  1. MapReduce → the processing engine.
  • Splits the work into small parts (Map) and combines the results (Reduce).
  • Handles scheduling, synchronization, and failures automatically → fault-tolerant.
  • Developers only focus on what to do, not how it’s done.
  1. HDFS (Hadoop Distributed File System) → the storage layer
  • Stores big files across multiple machines.
  • Each file is divided into large blocks (64–128 MB).
  • Every block is replicated (usually 3 copies) to prevent data loss.
  • Designed for write-once, read-many patterns (no updates). Example: Given a large textual file of words count the number of times each distinct word appears in the file. The output is a list of pairs , counting the number of occurrences of each specific word in the input file. Case 1 : Entire file fits in main memory → A traditional single node approach is probably the most efficient solution in this case. The complexity and overheads of a distributed system affects the performance when files are “small”, that depends on the resources you have. Case 2 : File too large to fit in main memory → How can we split this problem in a set of (almost) independent sub-tasks, and execute them in parallel on a cluster of servers? Suppose that the cluster has 3 servers and the content of the input file is “Toy example file for Hadoop. Hadoop running example.” The input file is split into 2 chunks. The number of replicas is 1.
  1. The problem can be easily parallelized. Each server processes its chunk of data and counts the number of times each word appears in its own chunk. Each server can execute its sub-task independently from the other servers of the cluster → synchronization is not needed in this phase. The output generated from each chunk by each server represents a partial result.
  2. Each server sends its local (partial) list of pairs to a server that is in charge of aggregating all local results and computing the global result. The server in charge of computing the global result needs to receive all the local (partial) results to compute and emit the final list → a synchronization operation is needed in this phase Suppose that - The file size is 100 GB and the number of distinct words occurring in it is at most 1, - The cluster has 101 servers - The file is spread across 100 servers and each of these servers contains one (different) chunk of the input filei.e., the file is optimally spread across 100 servers (each server contains 1/100 of the file in its local hard drives) So, even if the input file is big on the network the output sent is smaller: is equal to the number of different servers. → Complexity: - Each server reads 1 GB of data from its local hard drive (it reads one chunk from HDFS) o Few seconds - Each local list consists of at most 1,000 pairs (because the number of distinct words is 1,000) o Few MBs - The maximum amount of data sent on the network is 100 x size of local list (number of servers x local list size) o Some MBs → Scalability: we can define scalability along two dimensions - In terms of data: given twice the amount of data, the word count algorithm takes approximately no more than twice as long to run. Each server processes 2 x data => 2 x execution time to compute local list - In terms of resources: given twice the number of servers, the word count algorithm takes approximately no more than half as long to run. Each server processes ½ x data => ½ x execution time to compute local list All the key-value pairs associated with the same key must be managed by one single server. The time needed to send local results to the node in charge of computing the final result and the computation of the final result are considered negligible in this running example. Frequently, this assumption is not true, but it depends on the complexity of the problem and on the ability of the developer to limit the amount of data sent on the network.

MapReduce

In Big Data systems, the idea is to scale out, not up. Instead of upgrading existing machines with more CPU power or memory, we increase the number of servers in the cluster. This approach allows for better scalability and cost efficiency. Another key concept is to move processing to the data, not the other way around.

All the phases can be paralyzed. For the map phase, if two pairs of the same word are sent to two different servers, then they are shuffled together with no problem. The Map phase can be viewed as a transformation over each element of a data set

- This transformation is a function m defined by developers - m is invoked one time for each input element - Each invocation of m happens in isolation - The application of m to each element of a data set can be parallelized in a straightforward manner. The Reduce phase can be viewed as an aggregate operation - The aggregate function is a function r defined by developers - r is invoked one time for each distinct key and aggregates all the values associated with it - Also the reduce phase can be performed in parallel and in isolation - Each group of key-value pairs with the same key can be processed in isolation The shuffle and sort phase is always the same i.e., group the output of the map phase by key - It does not need to be defined by developers - It is already provided by the Hadoop system

Data structures

Key-value pair is the basic data structure in MapReduce. Keys and values can be: integers, float, strings, … They can also be (almost) arbitrary data structures defined by the designer. Both input and output of a MapReduce program are lists of key-value pairs. Note that also the input is a list of key-value pairs. The design of MapReduce involves:

  1. Imposing the key-value structure on the input and output data sets; e.g., for a collection of Web pages, input keys may be URLs and values may be their HTML content
  2. The map and reduce functions are formally defined as follows: a. map: (k1, v1) → [(k2, v2)] Since the input data set is a list of key-value pairs, the argument of the map function is a key-value pair. Returns a list of key-value pairs for each input pair and the list can be empty; b. reduce: (k2, [v2]) → [(k3, v3)] Is invoked once for each distinct key, receives the complete list of values [v2] associated with a specific key k2 and returns a list of key-value pairs for each input; the list can be empty.

Algorithms

In many applications, the key part of the input data set is ignored i.e., usually the map function does not consider the key of its key-value pair argument e.g., word count problem. This means that in many cases, the original key in the input is not important. The map() function often uses only the value and ignores the key. Suppose the input looks like this: (0, "hello world") (1, "hello hadoop") to count words, we don’t care about the line number (the key). We only use the value (the text). So in this case, the key is ignored. Some specific applications exploit also the keys of the input data e.g., keys can be used to uniquely identify records/objects.

How to write MapReduce programs in Hadoop

When developing a Hadoop MapReduce application, designers and developers primarily focus on defining the Map and Reduce functions (i.e., the logic of map() and reduce()). They do not need to handle the complexity of distributed execution, such as managing the map, shuffle and sort, or reduce phases. The Hadoop framework takes care of coordinating the entire execution of the MapReduce program. This includes running the map and reduce phases in parallel, executing the shuffle and sort phase, scheduling subtasks, and ensuring synchronization between different parts of the workflow. MapReduce programs are usually written in Java and consist of three main components. Each component is implemented as a Java class, and the program uses instances (objects) of these classes to perform its tasks.

- Driver – coordinates the job and the workflow of the application. It is responsible for configuring the job, submitting the job to the Hadoop cluster and coordinating the workflow of the application. It contains the main() method , which is the entry point of the application and can accept command-line arguments. The Driver runs on the client machine, not on the cluster itself. The Driver class usually extends org.apache.hadoop.conf.Configured and implements the org.apache.hadoop.util.Tool interface. It is possible to write a Driver class without extending Configured or implementing Tool, but in that case, you must manually handle low-level details, such as parsing command-line arguments. The developer is responsible for implementing: - main() method – the entry point of the program, - run() method – which configures and launches the job. The run() method defines all the job settings, including: job name, input format and output format, mapper class (class name, input and output types), reducer class (class name, input and output types, number of reducers ); number of mapper is not said by the user but depend on the number of the input block; instead the number of reducers is said by the user and depends on the numbers of distinct key that you have. Not always to increase the number of reducers is the best solution. - Mapper – implements the map function. It processes each input (key, value) pair from the input file and emits a set of intermediate (key, value) pairs, which are temporarily stored on the local filesystem of the computing node (not HDFS). The map() method is invoked once for each input pair, and the Mapper runs on the cluster nodes. Input data is read as key-value pairs from HDFS. Intermediate results are transient: they stored temporarily on the local filesystem of the node producing or processing them. They are not stored in HDFS, and they exist only during computation. The shuffle and sort phase aggregates intermediate results into (key, [list of values]) pairs (One (key, [list of values]) for each distinct key), preparing them for the Reducer. The Mapper class extends org.apache.hadoop.mapreduce.Mapper, which is a generic class with four type parameters: Mapper Developers implement the map() method, which is automatically called by Hadoop for each input (key, value) pair. Inside map(), you can use standard Java code to process the input. To emit results, use: context.write(key, value); (to connect with the cluster) - Reducer – implements the reduce function. It processes each (key, [list of values]) pair generated after the shuffle and sort phase, produces a set of final key-value pairs, which are stored in HDFS as the output of the MapReduce job. The reduce() method is called once per distinct key, and the Reducer also runs on cluster nodes. The Reducer class extends org.apache.hadoop.mapreduce.Reducer, another generic class with four type parameters: Reducer Developers implement the reduce() method, which is automatically called for each (key, [list of values]) pair resulting from the shuffle and sort of the Mapper outputs. Inside reduce(), you process the values using standard Java code and emit results with context.write(key, value); To process data efficiently, Hadoop executes tasks in parallel: it creates one Mapper task for each input split and a user- specified number of Reducer tasks, where each Reducer is responsible for a subset of keys and processes all associated key-value pairs. Both Mappers and Reducers run on the nodes of the cluster, leveraging the distributed nature of Hadoop to scale processing across many servers.

  1. Reading and validating input data → Ensures the input files comply with the expected format.
  2. Splitting input files into Input Splits → Each Input Split represents a portion of the input file. Every Input Split is assigned to a single Mapper.
  3. Providing a RecordReader → Divides each Input Split into individual records, which are the (key, value) pairs processed by the Mapper. InputFormat identifies partitions of the data, forming Input Splits. Each Input Split corresponds to a portion of the input file, processed by one Mapper. Each split is further divided into records, and the Mapper processes one record at a time (i.e., one (key, value) pair). A set of predefined classes extending the InputFormat abstract class are available for standard input file formats:
  4. TextInputFormat → Designed for plain text files. Files are split into lines, using linefeed or carriage-return as the end- of-line marker. For each line, a (key, value) pair is emitted: o Key = position (offset) of the line in the file o Value = content of the line The keypart is a long writable object and the values part is a text object.
  5. KeyValueTextInputFormat → is an InputFormat for plain text files where each line contains both a key and a value, separated by a specific character. By default, the separator is a tab (\t) → keyvalue The file is split into lines, using linefeed or carriage-return as the end-of-line marker. Each line is then split into key and value parts using the separator. Mapper input→ One pair (key, value) is emitted for each line of the file: Key = the text before the separator Value = the text after the separator The two parts are text objects. This InputFormat is useful when your text file already has a structured key-value format, allowing the Mapper to directly process meaningful (key, value) pairs instead of generating them from offsets and line content like TextInputFormat.
  6. SequenceFileInputFormat → Designed for binary or sequence files, allowing more efficient storage and processing of structured data.

OutputFormat

In Hadoop, the OutputFormat class is used to write the results of a MapReduce job back to HDFS. Any class that extends the abstract class org.apache.hadoop.mapreduce.OutputFormat can be used to define how the output is stored. Hadoop provides several predefined OutputFormat classes for standard file formats.

Common OutputFormat Classes:

  1. TextOutputFormat → Designed for plain text files. Each output (key, value) pair is written as a single line in the output file. → Line format: key\tvalue\n → The input of the second job must be a KeyValueTextInputFormat \t = tab character separating key and value \n = newline character, ending the line
  2. SequenceFileOutputFormat → Designed for binary or sequential files, which are more efficient for storing structured data. Hash function to divide pairs to the servers (mapper)

Driver Program

The Driver is responsible for configuring the job. It sets up the Mapper and the Reducer, specifies the input and output formats, and defines the number of Reducers to use. public class DriverBigData extends Configured implements Tool { @Override public int run(String[] args) throws Exception { Path inputPath; Path outputDir; int numberOfReducers; int exitCode; // Parse the parameters // Number of instances of the reducer class numberOfReducers = Integer.parseInt(args[ 0 ]); // Folder containing the input data inputPath = new Path(args[ 1 ]); // Output folder outputDir = new Path(args[ 2 ]); Configuration conf = this.getConf(); // Define a new job Job job = Job.getInstance(conf); // Assign a name to the job job.setJobName("Basic MapReduce Project - WordCount example"); // DA MODIFICARE // Set path of the input file/folder (if it is a folder, the job reads all the files in the specified folder) for this job FileInputFormat.addInputPath(job, inputPath); // Set path of the output folder for this job FileOutputFormat.setOutputPath(job, outputDir); //The output is ALWAYS a folder, it cannot be a file because it’s generated one file for each reducer. // Specify the class of the Driver for this job job.setJarByClass(DriverBigData.class); // Set job input format job.setInputFormatClass(TextInputFormat.class);

IntWritable> {// Output value type protected void map( LongWritable key, // Input key type Text value, // Input value type Context context) throws IOException, InterruptedException { // Split each sentence in words. Use whitespace(s) as delimiter // (=a space, a tab, a line break, or a form feed) // The split method returns an array of strings String[] words = value.toString().split("\s+"); // Iterate over the set of words for(String word : words) { String cleanedWord = word.toLowerCase(); // Transform word case context.write(new Text(cleanedWord),new IntWritable( 1 ));//emit the pair (word, 1) } } } In Hadoop, the Context parameter in the map method of a Mapper is an object that provides a connection between the Hadoop framework and the Mapper code. It is a fundamental part of the map and reduce mechanism and has several important functions:

- Communication with the framework: The Context allows the Mapper to communicate with the Hadoop framework — for example, to write key-value pairs to the output using the method context.write(outputKey, outputValue); - Configuration and counters: The Context provides access to the job configuration and to counters that can be used to track statistics or debugging information; - Status monitoring: The Mapper’s status can be updated via context.setStatus(), which enables the framework to monitor the progress and activity of the job; - Data access: The Context provides access to the input data and allows the Mapper to read and manage the (key, value) pairs coming from the input. Here’s a typical usage example: protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { String line = value.toString(); String[] words = line.split(" "); for (String word : words) { context.write(new Text(word), new IntWritable(1)); } } In this example, each word is emitted as a key, and the associated value is 1 (the output value). The Context object is used to emit these results.

Reducer Program

The Reducer takes as input a key (the word) and a list of values (the number of occurrences). It sums the values for each key and produces the total count for each word. class ReducerBigData extends Reducer < Text, // Input key type IntWritable, // Input value type Text, // Output key type IntWritable> { // Output value type

@Override protected void reduce( Text key, // Input key type Iterable values, // Input value type Context context) throws IOException, InterruptedException { int occurrences = 0 ; // Iterate over the set of values and sum them for (IntWritable value : values) { occurrences = occurrences + value.get(); } context.write(key, new IntWritable(occurrences)); } } The number of invocations with the reduce method is associated with the number for each distinct key. So, for the first file is invoked 7 time.

Combiner

In the “Standard” MapReduce applications the (key, value) pairs emitted by the Mappers are sent to the Reducers through the network. Some “ pre-aggregations ” could be performed to limit the amount of network data by using Combiners (also called “mini reducers”). Consider the standard word count problem and suppose the input file is split in two input splits. Hence, two Mappers are instantiated (one for each split). With Combiners the (key, value) pairs emitted by the Mappers are analysed in main-memory (or on the local disk) and aggregated by the Combiners. Each Combiner pre-aggregates the values associated with the pairs emitted by the Mappers of a cluster node. Combiners perform “pre-aggregations” to limit the amount of network data generated by each cluster node.