All About Hadoop
Apache Hadoop:
s Apache HDFS:
HADOOP DISTRIBUTED FILE SYSTEM
Assuming that:
Apache Yarn:
Hadoop HDFS is the data storage layer for Hadoop and MapReduce was the data-processing layer in Hadoop 1x. However, the MapReduce algorithm, by itself, isn’t sufficient for the very wide variety of use-cases we see Hadoop being employed to solve. Hadoop 2.0 presents YARN, as a generic resource-management and distributed application framework, whereby, one can implement multiple data processing applications customized for the task at hand. The fundamental idea of YARN is to split up the two major responsibilities of the JobTracker i.e. resource management and job scheduling/monitoring, into separate daemons: a global ResourceManager and per-application ApplicationMaster (AM).
Apache Hive:
Apache Hadoop:
Apache Hadoop is an open source framework for distributed storage and processing of large sets of data on commodity hardware. Hadoop enables businesses to quickly gain insight from massive amounts of structured and unstructured data. .
The base Apache Hadoop framework is composed of the following modules:
· Hadoop Common – contains libraries and utilities needed by other Hadoop modules.
· Hadoop Distributed File System (HDFS) – a distributed file-system that stores data on commodity machines, providing very high aggregate bandwidth across the cluster.
· Hadoop YARN – a resource-management platform responsible for managing computing resources in clusters and using them for scheduling of users’ applications.
· Hadoop MapReduce – a programming model for large scale data processing.
Why Hadoop?
Let us now understand why Hadoop is very popular, why Hadoop has captured more than 90% of big data market.
Hadoop is not only a storage system but is a platform for data storage as well as processing. It is scalable (more nodes can be added on the fly), Fault tolerant (Even if nodes go down, data can be processed by another node) and Open source (can modify the source code if required).
Following characteristics of Hadoop make is a unique platform:
- Flexibility to store and mine any type of data whether it is structured, semi-structured or unstructured. It is not bounded by a single schema.
- Excels at processing data of complex nature, its scale-out architecture divides workloads across multiple nodes. Another added advantage is that its flexible file-system eliminates ETL bottlenecks.
- Scales economically, as discussed it can be deployed on commodity hardware. Apart from this its open-source nature guards against vendor lock.
Hadoop Architecture
After understanding what Hadoop is, let us now see Hadoop architecture.
Hadoop works in master – slave fashion. There is a master node and there are n numbers of slave nodes where n can be 1000s. Master manages, maintains and monitors the slaves while slaves are the actual worker nodes. Master should be deployed on good configuration hardware and not just any commodity hardware as it is the centerpiece of Hadoop cluster.
Master just stores the meta-data (data about data) while slaves are the nodes which store the data. Data is stored distributedly in the cluster. The client connects with master node to perform any task.
Hadoop Daemons
There are mainly 4 daemons which run for Hadoop. Daemons are the processes that run in the background.
- Namenode – It runs on master node for HDFS.
- Datanode – It runs on slave nodes for HDFS.
- ResourceManager – It runs on master node for Yarn.
- NodeManager – It runs on slave node for Yarn.
These 4 daemons run for Hadoop to be functional. Apart from this, there can be secondary NameNode, standby NameNode, Job HistoryServer, etc
How Hadoop works?
Till now we have studied Hadoop Introduction and Hadoop architecture in detail. Now Let us summarize how Hadoop works step by step:
- Step1: Input data is broken into blocks of size 128 Mb (by default) and then blocks are moved to different nodes.
- Step 2: Once all the blocks of the file are stored on datanodes, a user can process the data.
- Step 3: master, then schedules the program (submitted by the user) on individual nodes.
- Step 4: Once all the nodes process the data, output is written back to HDFS
Hadoop Flavors
Below are the various flavors of Hadoop.
- Apache – Vanilla flavor, the actual code is residing in apache repositories.
- Hortonworks – Popular distribution in the industry.
- Cloudera – It is the most popular in the industry.
- MapR – It has rewritten HDFS and its HDFS is faster as compared to others.
- IBM – Proprietary distribution is known as Big Insights.
All the databases have provided native connectivity with Hadoop for fast data transfer. For example, to transfer data from Oracle to Hadoop, you need a connector.
All flavors are almost same and if you know one, you can easily work on other flavors as well.
Hadoop Ecosystem
In this section of Hadoop introduction tutorial, we will cover Hadoop ecosystem. Let us see what all components form the Hadoop Eco-System:
- Hadoop HDFS: Distributed storage layer for Hadoop.
- Yarn: Resource management layer introduced in Hadoop 2.x.
- Hadoop Map-Reduce: Parallel processing layer for Hadoop.
- HBase: HBase is a column-oriented database that runs on top of HDFS. It is a NoSQL database which does not understand structured query. It is well suited for sparse data set.
- Hive: Hive is a data warehousing infrastructure based on Hadoop which enables easy data summarization, using SQL queries.
- Sqoop: Sqoop is a tool designed to transport huge volumes of data between Hadoop and RDBMS.
- Flume: Apache Flume is a reliable system for efficiently collecting large amounts of log data from many different sources in real-time.
- Oozie: Oozie is a Java Web application used to schedule Apache Hadoop jobs. It combines multiple jobs sequentially into one logical unit of work.
- Pig: Pig is a top-level scripting language that is used with Hadoop. Pigenables writing complex data processing without Java programming.
Each project has been developed to deliver an explicit function and each has its own community of developers and individual release cycles. There are five pillars to Hadoop that make it enterprise ready:
Data Management– Store and process vast quantities of data in a storage layer that scales linearly. Hadoop Distributed File System (HDFS) is the core technology for the efficient scale out storage layer, and is designed to run across low-cost commodity hardware. Apache Hadoop YARN is the pre-requisite for Enterprise Hadoop as it provides the resource management and pluggable architecture for enabling a wide variety of data access methods to operate on data stored in Hadoop with predictable performance and service levels.
· Apache Hadoop YARN– Part of the core Hadoop project, YARN is a next-generation framework for Hadoop data processing extending MapReduce capabilities by supporting non-MapReduce workloads associated with other programming models.
· HDFS– Hadoop Distributed File System (HDFS) is a Java-based file system that provides scalable and reliable data storage that is designed to span large clusters of commodity servers.
Data Access– Interact with your data in a wide variety of ways – from batch to real-time. Apache Hive is the most widely adopted data access technology, though there are many specialized engines. For instance, Apache Pig provides scripting capabilities, Apache Storm offers real-time processing, Apache HBase offers columnar NoSQL storage and Apache Accumulo offers cell-level access control.
· Apache Hive– Built on the MapReduce framework, Hive is a data warehouse that enables easy data summarization and ad-hoc queries via an SQL-like interface for large datasets stored in HDFS.
· Apache Pig– A platform for processing and analyzing large data sets. Pig consists of a high-level language (Pig Latin) for expressing data analysis programs paired with the MapReduce framework for processing these programs.
· MapReduce– MapReduce is a framework for writing applications that process large amounts of structured and unstructured data in parallel across a cluster of thousands of machines, in a reliable and fault-tolerant manner.
· Apache Spark– Spark is ideal for in-memory data processing. It allows data scientists to implement fast, iterative algorithms for advanced analytics such as clustering and classification of datasets.
· Apache Storm– Storm is a distributed real-time computation system for processing fast, large streams of data adding reliable real-time data processing capabilities to Apache Hadoop® 2.x
· Apache HBase– A column-oriented NoSQL data storage system that provides random real-time read/write access to big data for user applications.
· Apache Tez– Tez generalizes the MapReduce paradigm to a more powerful framework for executing a complex DAG (directed acyclic graph) of tasks for near real-time big data processing.
· Apache Kafka– Kafka is a fast and scalable publish-subscribe messaging system that is often used in place of traditional message brokers because of its higher throughput, replication, and fault tolerance.
· Apache HCatalog– A table and metadata management service that provides a centralized way for data processing systems to understand the structure and location of the data stored within Apache Hadoop.
· Apache Slider– A framework for deployment of long-running data access applications in Hadoop. Slider leverages YARN’s resource management capabilities to deploy those applications, to manage their lifecycles and scale them up or down.
· Apache Solr– Solr is the open source platform for searches of data stored in Hadoop. Solr enables powerful full-text search and near real-time indexing on many of the world’s largest Internet sites.
· Apache Mahout– Mahout provides scalable machine learning algorithms for Hadoop which aids with data science for clustering, classification and batch based collaborative filtering.
· Apache Accumulo– Accumulo is a high performance data storage and retrieval system with cell-level access control. It is a scalable implementation of Google’s Big Table design that works on top of Apache Hadoop and Apache ZooKeeper.
Data Governance and Integration– Quickly and easily load data, and manage according to policy. Workflow Manager provides workflows for data governance, while Apache Flume and Sqoop enable easy data ingestion, as do the NFS and WebHDFS interfaces to HDFS.
· Workflow Management– Workflow Manager allows you to easily create and schedule workflows and monitor workflow jobs. It is based on the Apache Oozie workflow engine that allows users to connect and automate the execution of big data processing tasks into a defined workflow.
· Apache Flume– Flume allows you to efficiently aggregate and move large amounts of log data from many different sources to Hadoop.
· Apache Sqoop– Sqoop is a tool that speeds and eases movement of data in and out of Hadoop. It provides a reliable parallel load for various, popular enterprise data sources.
Security– Address requirements of Authentication, Authorization, Accounting and Data Protection. Security is provided at every layer of the Hadoop stack from HDFS and YARN to Hive and the other Data Access components on up through the entire perimeter of the cluster via Apache Knox.
· Apache Knox– The Knox Gateway (“Knox”) provides a single point of authentication and access for Apache Hadoop services in a cluster. The goal of the project is to simplify Hadoop security for users who access the cluster data and execute jobs, and for operators who control access to the cluster.
· Apache Ranger– Apache Ranger delivers a comprehensive approach to security for a Hadoop cluster. It provides central security policy administration across the core enterprise security requirements of authorization, accounting and data protection.
Operations– Provision, manage, monitor and operate Hadoop clusters at scale.
· Apache Ambari– An open source installation lifecycle management, administration and monitoring system for Apache Hadoop clusters.
· Apache Oozie– Oozie Java Web application used to schedule Apache Hadoop jobs. Oozie combines multiple jobs sequentially into one logical unit of work.
· Apache ZooKeeper– A highly available system for coordinating distributed processes. Distributed applications use ZooKeeper to store and mediate updates to important configuration information.
HADOOP DISTRIBUTED FILE SYSTEM
HDFS is a distributed file system that is designed for storing large data files. HDFS is a Java-based file system that provides scalable and reliable data storage, and it was designed to span large clusters of commodity servers. HDFS has demonstrated production scalability of up to 200 PB of storage and a single cluster of 4500 servers, supporting close to a billion files and blocks. HDFS is a scalable, fault-tolerant, distributed storage system that works closely with a wide variety of concurrent data access applications, coordinated by YARN. HDFS will “just work” under a variety of physical and systemic circumstances. By distributing storage and computation across many servers, the combined storage resource can grow linearly with demand while remaining economical at every amount of storage.
An HDFS cluster is comprised of a NameNode, which manages the cluster metadata, and DataNodes that store the data. Files and directories are represented on the NameNode by inodes. Inodes record attributes like permissions, modification and access times, or namespace and disk space quotas.
The file content is split into large blocks (typically 128 megabytes), and each block of the file is independently replicated at multiple DataNodes. The blocks are stored on the local file system on the DataNodes.
The Namenode actively monitors the number of replicas of a block. When a replica of a block is lost due to a DataNode failure or disk failure, the NameNode creates another replica of the block. The NameNode maintains the namespace tree and the mapping of blocks to DataNodes, holding the entire namespace image in RAM.
The NameNode does not directly send requests to DataNodes. It sends instructions to the DataNodes by replying to heartbeats sent by those DataNodes. The instructions include commands to:
· replicate blocks to other nodes,
· remove local block replicas,
· re-register and send an immediate block report, or
· shut down the node.
Apache MapReduce:
MapReduce is the key algorithm that the Hadoop data processing engine uses to distribute work around a cluster. A MapReduce job splits a large data set into independent chunks and organizes them into key, value pairs for parallel processing. This parallel processing improves the speed and reliability of the cluster, returning solutions more quickly and with greater reliability.
The Map function divides the input into ranges by the InputFormat and creates a map task for each range in the input. The JobTracker distributes those tasks to the worker nodes. The output of each map task is partitioned into a group of key-value pairs for each reduce.
· map(key1,value) -> list<key2,value2>
The Reduce function then collects the various results and combines them to answer the larger problem that the master node needs to solve. Each reduce pulls the relevant partition from the machines where the maps executed, then writes its output back into HDFS. Thus, the reduce is able to collect the data from all of the maps for the keys and combine them to solve the problem.
· reduce(key2, list<value2>) -> list<value3>
The current Apache Hadoop MapReduce System is composed of the JobTracker, which is the master, and the per-node slaves called TaskTrackers. The JobTracker is responsible for resource management (managing the worker nodes i.e. TaskTrackers), tracking resource consumption/availability and also job life-cycle management (scheduling individual tasks of the job, tracking progress, providing fault-tolerance for tasks etc).
The TaskTracker has simple responsibilities – launch/teardown tasks on orders from the JobTracker and provide task-status information to the JobTracker periodically.
The Apache Hadoop projects provide a series of tools designed to solve big data problems. The Hadoop cluster implements a parallel computing cluster using inexpensive commodity hardware. The cluster is partitioned across many servers to provide a near linear scalability. The philosophy of the cluster design is to bring the computing to the data. So each datanode will hold part of the overall data and be able to process the data that it holds. The overall framework for the processing software is called MapReduce.
Mapreduce
Overview Hadoop MapReduce is a software framework for easily writing applications which process vast amounts of data (multi-terabyte data-sets) in-parallel on large clusters (thousands of nodes) of commodity hardware in a reliable, fault-tolerant manner.
A MapReduce job usually splits the input data-set into independent chunks which are processed by the map tasks in a completely parallel manner. The framework sorts the outputs of the maps, which are then input to the reduce tasks. Typically both the input and the output of the job are stored in a file-system. The framework takes care of scheduling tasks, monitoring them and re-executes the failed tasks. Typically the compute nodes and the storage nodes are the same, that is, the MapReduce framework and the Hadoop Distributed File System (see HDFS Architecture Guide) are running on the same set of nodes.a reliable, fault-tolerant manner.
The MapReduce framework consists of a single master JobTracker and one slave TaskTracker per cluster-node. The master is responsible for scheduling the jobs' component tasks on the slaves, monitoring them and re-executing the failed tasks. The slaves execute the tasks as directed by the master.
I Inputs and Outputs:
The MapReduce framework operates exclusively on pairs, that is, the framework views the input to the job as a set of pairs and produces a set of pairs as the output of the job, conceivably of different types. The key and value classes have to be serializable by the framework and hence need to implement the Writable interface. Additionally, the key c`lasses have to implement the WritableComparable interface to facilitate sorting by the framework. Input and Output types of a MapReduce job: (input) -> map -> -> combine -> -> reduce -> (output)
Example: Before we jump into the details, lets walk through an example MapReduce application to get a flavour for how they work. WordCount is a simple application that counts the number of occurences of each word in a given input set.
Source Code
WordCount.java
1. package org.myorg;
2.3. import java.io.IOException;
4 4.5. import java.util.*;
5. 6. import org.apache.hadoop.fs.Path;
7. import org.apache.hadoop.conf.*;
8. import org.apache.hadoop.io.*;
9. import org.apache.hadoop.mapred.*;
10. import org.apache.hadoop.util.*;
11.12. public class WordCount {
13.14. public static class Map extends MapReduceBase implements Mapper {
15. private final static IntWritable one = new IntWritable(1);
16. private Text word = new Text();
17. 18. public void map(LongWritable key, Text value, OutputCollector output, Reporter reporter) throws IOException {
19. String line = value.toString();
20. StringTokenizer tokenizer = new StringTokenizer(line);
21. while (tokenizer.hasMoreTokens()) {
22. word.set(tokenizer.nextToken());
23. output.collect(word, one);
24. }
25. }
26. }
27. 28. public static class Reduce extends MapReduceBase implements Reducer {
29. public void reduce(Text key, Iterator values, OutputCollector output, Reporter reporter) throws IOException {
30. int sum = 0;
31. while (values.hasNext()) {
32. sum += values.next().get();
33. }
34. output.collect(key, new IntWritable(sum));
35. }
36. }
37. 38. public static void main(String[] args) throws Exception {
39. JobConf conf = new JobConf(WordCount.class); 40. conf.setJobName("wordcount");
41. 42. conf.setOutputKeyClass(Text.class);
43. conf.setOutputValueClass(IntWritable.class);
44.45. conf.setMapperClass(Map.class);
46. conf.setCombinerClass(Reduce.class);
47. conf.setReducerClass(Reduce.class);
48. 49. conf.setInputFormat(TextInputFormat.class);
50. conf.setOutputFormat(TextOutputFormat.class);
51. 52. FileInputFormat.setInputPaths(conf, new Path(args[0]));
53. FileOutputFormat.setOutputPath(conf, new Path(args[1]));
54. 55. JobClient.runJob(conf);
57. }
58. }
Usage
Assuming HADOOP_HOME is the root of the installation and HADOOP_VERSION is the Hadoop version installed, compile WordCount.java and create a jar:
$ mkdir wordcount_classes
$ javac -classpath ${HADOOP_HOME}/hadoop-${HADOOP_VERSION}- core.jar -d wordcount_classes WordCount.java
$ jar -cvf /usr/joe/wordcount.jar -C wordcount_classes/ .
Assuming that:
• /usr/joe/wordcount/input - input directory in HDFS
• /usr/joe/wordcount/output - output directory in HDFS
Sample text-files as input:
$ bin/hadoop dfs -ls /usr/joe/wordcount/input/
/usr/joe/wordcount/input/file01
/ /usr/joe/wordcount/input/file02
$ bin/hadoop dfs -cat /usr/joe/wordcount/input/file01 Hello World Bye World
$ bin/hadoop dfs -cat /usr/joe/wordcount/input/file02 Hello Hadoop Goodbye Hadoop
Run the application:
$ bin/hadoop jar /usr/joe/wordcount.jar org.myorg.WordCount / usr/joe/wordcount/input /usr/joe/wordcount/output
Output:
$ bin/hadoop dfs -cat /usr/joe/wordcount/output/part-00000
Bye 1
Goodbye 1
Hadoop 2
Hello 2
World 2
Walk-through:
The WordCount application is quite straight-forward.
The Mapper implementation (lines 14-26), via the map method (lines 18-25), processes one line at a time, as provided by the specified TextInputFormat (line 49). It then splits the line into tokens separated by whitespaces, via the StringTokenizer, and emits a keyvalue pair of < , 1>.
For the given sample input the first map emits:
< Hello, 1>
< World, 1>
< Bye, 1>
< World, 1>
The second map emits:
< Hello, 1>
< Hadoop, 1>
< Goodbye, 1>
< Hadoop, 1>
WordCount also specifies a combiner (line 46). Hence, the output of each map is passed through the local combiner (which is same as the Reducer as per the job configuration) for local aggregation, after being sorted on the keys.
The output of the first map:
< Bye, 1>
< Hello, 1>
< World, 2>
The output of the second map:
< Goodbye, 1>
< Hadoop, 2>
< Hello, 1>
The Reducer implementation (lines 28-36), via the reduce method (lines 29-35) just sums up the values, which are the occurence counts for each key (i.e. words in this example).
Thus the output of the job is:
< Bye, 1>
< Goodbye, 1>
< Hadoop, 2>
< Hello, 2>
< World, 2>
The run method specifies various facets of the job, such as the input/output paths (passed via the command line), key/value types, input/output formats etc., in the JobConf. It then calls the JobClient.runJob (line 55) to submit the and monitor its progress.
MapReduce - User Interfaces
Applications typically implement the Mapper and Reducer interfaces to provide the map and reduce methods. These form the core of the job.
Mapper:
Mapper maps input key/value pairs to a set of intermediate key/value pairs. Maps are the individual tasks that transform input records into intermediate records. The transformed intermediate records do not need to be of the same type as the input records. A given input pair may map to zero or many output pairs. Overall, Mapper implementations are passed the JobConf for the job via the JobConfigurable.configure(JobConf) method and override it to initialize themselves. The framework then calls map(WritableComparable, Writable, OutputCollector, Reporter) for each key/value pair in the InputSplit for that task. Applications can then override the Closeable.close() method to perform any required cleanup.Output pairs do not need to be of the same types as input pairs. A given input pair may map to zero or many output pairs. Output pairs are collected with calls to OutputCollector.collect(WritableComparable,Writable). Applications can use the Reporter to report progress, set application-level status messages and update Counters, or just indicate that they are alive. All intermediate values associated with a given output key are subsequently grouped by the framework, and passed to the Reducer(s) to determine the final output. Users can control the grouping by specifying a Comparator via JobConf.setOutputKeyComparatorClass(Class). The Mapper outputs are sorted and then partitioned per Reducer. The total number of partitions is the same as the number of reduce tasks for the job. Users can control which keys (and hence records) go to which Reducer by implementing a custom Partitioner. Users can optionally specify a combiner, via JobConf.setCombinerClass(Class), to perform local aggregation of the intermediate outputs, which helps to cut down the amount of data transferred from the Mapper to the Reducer. The intermediate, sorted outputs are always stored in a simple (key-len, key, value-len, value) format. Applications can control if, and how, the intermediate outputs are to be compressed and the CompressionCode to be used via the JobConf.
How Many Maps?
The number of maps is usually driven by the total size of the inputs, that is, the total number of blocks of the input files. The right level of parallelism for maps seems to be around 10-100 maps per-node, although it has been set up to 300 maps for very cpu-light map tasks. Task setup takes awhile, so it is best if the maps take at least a minute to execute. Thus, if you expect 10TB of input data and have a blocksize of 128MB, you'll end up with 82,000 maps, unless setNumMapTasks(int) (which only provides a hint to the framework) is used to set it even higher.
Reducer:
Reducer reduces a set of intermediate values which share a key to a smaller set of values. The number of reduces for the job is set by the user via JobConf.setNumReduceTasks(int). Overall, Reducer implementations are passed the JobConf for the job via the JobConfigurable.configure(JobConf) method and can override it to initialize themselves. The framework then calls reduce(WritableComparable, Iterator, OutputCollector, Reporter) method for each pair in the grouped inputs. Applications can then override the Closeable.close() method to perform any required cleanup. Reducer has 3 primary phases: shuffle, sort and reduce.
Shuffle:
I Input to the Reducer is the sorted output of the mappers. In this phase the framework fetches the relevant partition of the output of all the mappers, via HTTP.
Sort:
The framework groups Reducer inputs by keys (since different mappers may have output the same key) in this stage. The shuffle and sort phases occur simultaneously; while map-outputs are being fetched they are merged.
Secondary Sort:
If equivalence rules for grouping the intermediate keys are required to be different from those for grouping keys before reduction, then one may specify a Comparator via JobConf.setOutputValueGroupingComparator(Class). Since JobConf.setOutputKeyComparatorClass(Class) can be used to control how intermediate keys are grouped, these can be used in conjunction to simulate secondary sort on values.
Reduce:
I In this phase the reduce(WritableComparable, Iterator, OutputCollector, Reporter) method is called for each pair in the grouped inputs. The output of the reduce task is typically written to the FileSystem via OutputCollector.collect(WritableComparable, Writable). Applications can use the Reporter to report progress, set application-level status messages and update Counters, or just indicate that they are alive. The output of the Reducer is not sorted.
How Many Reduces?
The right number of reduces seems to be 0.95 or 1.75 multiplied by ( * mapred.tasktracker.reduce.tasks.maximum). With 0.95 all of the reduces can launch immediately and start transfering map outputs as the maps finish. With 1.75 the faster nodes will finish their first round of reduces and launch a second wave of reduces doing a much better job of load balancing. Increasing the number of reduces increases the framework overhead, but increases load balancing and lowers the cost of failures. The scaling factors above are slightly less than whole numbers to reserve a few reduce slots in the framework for speculative-tasks and failed tasks.
Reducer NONE:
It is legal to set the number of reduce-tasks to zero if no reduction is desired. In this case the outputs of the map-tasks go directly to the FileSystem, into the output path set by setOutputPath(Path). The framework does not sort the map-outputs before writing them out to the FileSystem.
Partitioner :
Partitioner partitions the key space. Partitioner controls the partitioning of the keys of the intermediate map-outputs. The key (or a subset of the key) is used to derive the partition, typically by a hash function. The total number of partitions is the same as the number of reduce tasks for the job. Hence this controls which of the m reduce tasks the intermediate key (and hence the record) is sent to for reduction. HashPartitioner is the default Partitioner.
Reporter :
Reporter is a facility for MapReduce applications to report progress, set application-level status messages and update Counters. Mapper and Reducer implementations can use the Reporter to report progress or just indicate that they are alive. In scenarios where the application takes a significant amount of time to process individual key/value pairs, this is crucial since the framework might assume that the task has timed-out and kill that task. Another way to avoid this is to set the configuration parameter mapred.task.timeout to a high-enough value (or even set it to zero for no time-outs). Applications can also update Counters using the Reporter.
OutputCollector:
OutputCollector is a generalization of the facility provided by the MapReduce framework to collect data output by the Mapper or the Reducer (either the intermediate outputs or the output of the job). Hadoop MapReduce comes bundled with a library of generally useful mappers, reducers, and partitioners.
Hadoop HDFS is the data storage layer for Hadoop and MapReduce was the data-processing layer in Hadoop 1x. However, the MapReduce algorithm, by itself, isn’t sufficient for the very wide variety of use-cases we see Hadoop being employed to solve. Hadoop 2.0 presents YARN, as a generic resource-management and distributed application framework, whereby, one can implement multiple data processing applications customized for the task at hand. The fundamental idea of YARN is to split up the two major responsibilities of the JobTracker i.e. resource management and job scheduling/monitoring, into separate daemons: a global ResourceManager and per-application ApplicationMaster (AM).
The ResourceManager and per-node slave, the NodeManager (NM), form the new, and generic, system for managing applications in a distributed manner.
The ResourceManager is the ultimate authority that arbitrates resources among all the applications in the system. The per-application ApplicationMaster is, in effect, a framework specific entity and is tasked with negotiating resources from the ResourceManager and working with the NodeManager(s) to execute and monitor the component tasks.
ResourceManager has a pluggable Scheduler, which is responsible for allocating resources to the various running applications subject to familiar constraints of capacities, queues etc. The Scheduler is a pure scheduler in the sense that it performs no monitoring or tracking of status for the application, offering no guarantees on restarting failed tasks either due to application failure or hardware failures. The Scheduler performs its scheduling function based on the resource requirements of the applications; it does so based on the abstract notion of a **Resource Container **which incorporates resource elements such as memory, CPU, disk, network etc.
NodeManager is the per-machine slave, which is responsible for launching the applications’ containers, monitoring their resource usage (CPU, memory, disk, network) and reporting the same to the ResourceManager.
The per-application ApplicationMaster has the responsibility of negotiating appropriate resource containers from the Scheduler, tracking their status and monitoring for progress. From the system perspective, the ApplicationMaster itself runs as a normal container.
Here is an architectural view of YARN:
One of the crucial implementation details for MapReduce within the new YARN system that I’d like to point out is that we have reused the existing MapReduce framework without any major surgery. This was very important to ensure compatibility for existing MapReduce applications and users.
Hadoop 1 v/s 2:
Sl No
|
Hadoop1
|
Hadoop2
|
1
|
Supports MapReduce (MR) processing model only.
Does not support Non MR tools.
|
Allows to work in MR as well as other distributed computing
models like Spark, Hama, Giraph, Message Passing Interface)
MPI & HBase coprocessors.
|
2
|
MR does both processing and cluster-resource management.
|
YARN (Yet Another Resource Negotiator) does cluster resource
management and processing is done using different processing
models.
|
3
|
Has limited scaling of nodes. Limited to 4000 nodes per cluster
|
Has better scalability. Scalable up to 10000 nodes per cluster
|
4
|
Works on concepts of slots – slots can run either a Map task or a Reduce task only.
|
Works on concepts of containers. Using containers can run
generic tasks.
|
5
|
A single Namenode to manage the entire namespace.
|
Multiple Namenode servers manage multiple namespaces.
|
6
|
Has Single-Point-of-Failure (SPOF) – because of single Namenode- and in the case of Namenode failure, needs manual intervention to overcome.
|
Has to feature to overcome SPOF with a standby Namenode
and in the case of Namenode failure, it is configured for automatic
recovery.
|
7
|
MR API is compatible with Hadoop1x. A program written in Hadoop1 executes in Hadoop1x without any additional files.
|
MR API requires additional files for a program written in
Hadoop1x to execute in Hadoop2x.
|
8
|
Has a limitation to serve as a platform for event processing, streaming and real-time operations.
|
Can serve as a platform for a wide variety of data analytics-
possible to run event processing, streaming and real-time
operations.
|
9
|
A Namenode failure affects the stack.
|
The Hadoop stack – Hive, Pig, HBase etc. are all
equipped to handle Namenode failure.
|
10
|
Does not support Microsoft Windows
|
Added support for Microsoft windows
|
Apache Hive:
What Is Hive
Hive is a data warehousing infrastructure based on Apache Hadoop. Hadoop provides massive scale out and fault tolerance capabilities for data storage and processing on commodity hardware.
Hive is designed to enable easy data summarization, ad-hoc querying and analysis of large volumes of data.
What Hive Is NOT
Hive is not designed for online transaction processing. It is best used for traditional data warehousing tasks.
Data Units
In the order of granularity - Hive data is organized into:
- Databases: Namespaces function to avoid naming conflicts for tables, views, partitions, columns, and so on. Databases can also be used to enforce security for a user or group of users.
- Tables: Homogeneous units of data which have the same schema.
- Partitions: Each Table can have one or more partition Keys which determines how the data is stored. Partitions—apart from being storage units—also allow the user to efficiently identify the rows that satisfy a specified criteria; for example, a date_partition of type STRING and country_partition of type STRING. Each unique value of the partition keys defines a partition of the Table. For example, all "US" data from "2009-12-23" is a partition of the page_views table. Therefore, if you run analysis on only the "US" data for 2009-12-23, you can run that query only on the relevant partition of the table, thereby speeding up the analysis significantly.
- Buckets (or Clusters): Data in each partition may in turn be divided into Buckets based on the value of a hash function of some column of the Table. For example the page_views table may be bucketed by userid, which is one of the columns, other than the partitions columns, of the page_view table.
Primitive Types
- Types are associated with the columns in the tables. The following Primitive types are supported:
- Integers
- TINYINT—1 byte integer
- SMALLINT—2 byte integer
- INT—4 byte integer
- BIGINT—8 byte integer
- Boolean type
- BOOLEAN—TRUE/FALSE
- Floating point numbers
- FLOAT—single precision
- DOUBLE—Double precision
- Fixed point numbers
- DECIMAL—a fixed point value of user defined scale and precision
- String types
- STRING—sequence of characters in a specified character set
- VARCHAR—sequence of characters in a specified character set with a maximum length
- CHAR—sequence of characters in a specified character set with a defined length
- Date and time types
- TIMESTAMP— a specific point in time, up to nanosecond precision
- DATE—a date
- Binary types
- BINARY—a sequence of bytes
Hive DDL Commands:
Create Database Statement:
A database in Hive is a namespace or a collection of tables.
Drop database
Creating Hive Tables:
Create a table called Sonoo with two columns, the first being an integer and the other a string.
Create a table called HIVE_TABLE with two columns and a partition column called ds. The partition column is a virtual column. It is not part of the data itself but is derived from the partition that a particular dataset is loaded into.By default, tables are assumed to be of text input format and the delimiters are assumed to be ^A(ctrl-a).
Browse the table
Altering and Dropping Tables
Hive: Internal Tables
There are 2 types of tables in Hive, Internal and External. This case study describes creation of internal table, loading data in it, creating views, indexes and dropping table on weather data.
Creating Internal Table
Internal table are like normal database table where data can be stored and queried on. On dropping these tables the data stored in them also gets deleted and data is lost forever. So one should be careful while using internal tables as one drop command can destroy the whole data. Open new terminal and fire up hive by just typing hive. Create table on weather data.
CREATE TABLE weather (wban INT, date STRING, precip INT)
ROW FORMAT DELIMITED
FIELDS TERMINATED BY ‘,’
LOCATION ‘ /hive/data/weather’;
ROW FORMAT should have delimiters used to terminate the fields and lines like in the above example the fields are terminated with comma (“,”). The default location of Hive table is overwritten by using LOCATION. So the data now is stored in data/weather folder inside hive.
Load the Data in Table
Data can be loaded in 2 ways in Hive either from local file or from HDFS to Hive. To load the data from local to Hive use the following command in NEW terminal:
hadoop fs –copyFromLocal /home/user/data/weather/2012.txt hdfs://hname:10001/hive/data/weather
Here the hdfs path was initially made in the create statement using LOCATION ‘ /hive/data/weather’.
Another way to load data is to load it from HDFS to hive using the following command:
LOAD DATA INPATH ‘hdfs:/data/2012.txt’ INTO TABLE weather;
Views
Views are used for creating virtual tables. They are faster than creating actual tables and they can work as table while using them in any other query. For example precipitation view can be made as follows and can be used in other query just like a table is used.
CREATE VIEW AS precipitation_data SELECT * FROM weatherext WHERE precip IS NOT NULL AND precip>0;
Following query can be used to retrieve data from precipitation_data
SELECT * FROM precipitation_data;
Indexing
Indexes are made on top of tables so that they speed up queries. Most popular column that are used very often in WHERE clause should be indexed to make the query run faster. Partition can be built on weather table’s date column in following way:
CREATE INDEX date_index ON TABLE weather (date) AS ‘COMPACT’ WITH REBUILD;
After making this index any query that uses date column of weather table will be faster than running it before creating index.
Learn Hadoop by working on interesting Big Data and Hadoop Projects for just $9
Drop table
On dropping the table loaded by second method that is from HDFS to Hive, the data gets deleted and there is no copy of data on HDFS. This means that on creating internal table the data gets moved from HDFS to Hive. Table can be dropped using:
DROP TABLE weather;
Hive: External Tables
Creating external table
Open new terminal and fire up hive by just typing hive. Create table on weather data.
CREATE EXTERNAL TABLE weatherext ( wban INT, date STRING)
ROW FORMAT DELIMITED
FIELDS TERMINATED BY ‘,’
LOCATION ‘ /hive/data/weatherext’;
ROW FORMAT should have delimiters used to terminate the fields and lines like in the above example the fields are terminated with comma (“,”). The default location of Hive table is overwritten by using LOCATION. So the data now is stored in data/weatherext folder inside hive.
Load the data in table
Load the data from HDFS to Hive using the following command:
LOAD DATA INPATH ‘hdfs:/data/2012.txt’ INTO TABLE weatherext;
Partitioning of table
Hive stores tables in partitions. Partitions are used to divide the table into related parts. Partitions make data querying more efficient. For example in the above weather table the data can be partitioned on the basis of year and month and when query is fired on weather table this partition can be used as one of the column.
CREATE EXTERNAL TABLE IF NOT EXSISTS weatherext ( wban INT, date STRING)
PARTITIONED BY (year INT, month STRING)
ROW FORMAT DELIMITED
FIELDS TERMINATED BY ‘,’
LOCATION ‘ /hive/data/weatherext’;
Loading data in partitioned tables is different than non-partitioned one. There is little manual work of mentioning the partition data. Data can be loaded in partition, year 2012 and month 01 and 02 as follows:
LOAD DATA INPATH ‘hdfs:/data/2012.txt’ INTO TABLE weatherext PARTITION (year=2012, month=’01’);
LOAD DATA INPATH ‘hdfs:/data/2012.txt’ INTO TABLE weatherext PARTITION (year=2012, month=’02’);
This creates the partitioned table and makes different folder for each partition which helps in querying data.
Querying of partitioned table
Partitioned tables can use partition parameters as one of the column for querying. To retrieve all the data for month of ‘02’ following query can be used on weather table.
SELECT * FROM weatherext WHERE month = ‘02’;
Drop table
On dropping the external table, the data does not get deleted from HDFS. Thus it is evident that the external table are just pointers on HDFS data. Table can be dropped using:
DROP TABLE weather;
Hive Partitioning:
In Hive’s partitioning method, all the data present in a table is divided into
multiple partitions. Each partition corresponds to a specific value(s) of partition column(s) and is kept as a sub-record inside the table’s record present in the HDFS. So on querying a particular table, appropriate partition of the table is queried which contains the query value. Hence it decreases the I/O time required by the query which increases the performance speed.
In Hive’s partitioning method, all the data present in a table is divided into
multiple partitions. Each partition corresponds to a specific value(s) of partition column(s) and is kept as a sub-record inside the table’s record present in the HDFS. So on querying a particular table, appropriate partition of the table is queried which contains the query value. Hence it decreases the I/O time required by the query which increases the performance speed.
Partitioning Example
Let’s understand this with an example; consider a table named record which contains student’s data such as rollno, name, class, and batch. Suppose you need to retrieve the details of the entire students who left the school in the year 2011. The whole table is queried if a query has been raised to retrieve any information. However, if you partition the student’s table with the year, a lot of query processing time will be reduced on retrieving any information. The example below will help you to learn how to partition a file and its data:
The file named file1 contains student data table.
1
2
3
4
5
6
| record/studentdata/file1rollno, name, class, batch1, monika, 12, 20102, yash, 12, 20103, shilpa,11, 20114, parv, 11, 2011 |
Now we will partition the above data into two files using year.
1
2
3
4
5
6
| record/studentdata/2010/file21, monika, 12, 20102, yash, 12, 2010record/studentdata/2011/file33, shilpa,11, 20114, parv,11, 2011 |
While retrieving the data from the table, only the data of specified partition will be queried. Create a partitioned table:
1
2
3
| CREATE TABLE studentTab (rollno INT, name STRING, class INT, batch INT) PARTITIONED BY (year STRING);LOAD DATA LOCAL INPATH 'record/studentdata/2011/file2' OVERWRITE INTO TABLE studentTab PARTITION (year='2010');LOAD DATA LOCAL INPATH 'record/studentdata/2011/file3' OVERWRITE INTO TABLE studentTab PARTITION (year='2011'); |
There are 2 types of partition:
Hive Bucketing:
* we organize tables into buckets, reason is to enable more efficient queries and bucketing imposes extra structure on the table.
* Makes sampling more efficient.
Partitioning v/s Bucketing:
Both partitioning and bucketing slice the data for executing the query much more efficiently than non-sliced data.
In partitioning, number of slices will keep on changing as data is modified.
In bucketing, number of slices are fixed which are specified while creating the table.
Enable bucketing in hive:
To enable bucketing, need to set below:
set hive.enforce.bucketing=true;
syntax:
create table bucketed_users(id int, name string) clustered by (id) into 4 buckets;
CLUSTERED BY clause is to specify the columns to bucket on and the number of buckets.
HIVE BUCKETING EXAMPLE:
1. create external table cc_bucket(cdate string, issue string, product string, state string, zipcode string, cid string) partitioned by (product string, submitted_via string) clustered by (zipcode) into 3 buckets row format delimited fields terminated by ',' lines terminated by '\n' stored as textfile;
2. set hive.enforce.bucketing=true;
set hive.exec.dynamic.partition=true;
set hive.exec.dynamic.partition.mode=nonstrict;
3. insert overwrite table cc_bucket partition(product,submitted_via) select cdate,issue,state,zipcode,cid,product,submitted_via from consumercomp;
You can also crosscheck by visiting localhost:50070 i.e, hdfs browse directory.
1.static
2.Dynamic
Static: In DML/DDL involving multiple partitioning columns,the columns whose values are known at compile time.
Dynamic:Here the values are known at execution time, not at the compile time.
Static partition Example:
steps:
1. create table clientdetails(client_id int,client_name string)partitioned by(country string)row format delimited fields terminated by ',';
2. describe clientdetails;
3. create 2 input files to give the path while loading data.
4. load data inpath '/client_us' into table clientdetails partition(country="us");
5. load data inpath '/client_us' into table clientdetails partition(country="india");
6. select * from cientdetails;
Dynamic Partition Example:
Here insert,select queries dynamic partition columns must be specified LAST among columns.
Only allowes non-strict mode.
steps:
1. create external table consumercomp(cdate string, product string, issue string, state string, zipcode string, submitted_via string, cid string) row format delimited fields terminated by ',' lines terminated by '\n' stored as textfile;
2. load data local inpath '/path' into table consumercomp;
(there must be file to give a path while loading)
3.To view the data
select * from consumercomp;
create partition table:
4. create external table cc_partition(cdate string, product string, issue string, state string, zipcode string, cid string) partitioned by (submmitted_via) row format delimited fields terminated by ',' lines terminated by '\n' stored as textfile;
Two modes are available:
Strict mode: here at least one partition column has to be static.
Non strict mode
so, changing it to non strict mode.
i.e,
5. set hive.exec.dynamic.partition=true;
set hive.exec.dynamic.partition.mode=nonstrict;
6.Load data to partitioned table(cc_partition)
insert overwrite table cc_partition partition(submitted_via) select cdate, product, issue, state, zipcode, cid, submiited_via from cc_partition;
7. select * from cc_partition;
Hive Bucketing:
* we organize tables into buckets, reason is to enable more efficient queries and bucketing imposes extra structure on the table.
* Makes sampling more efficient.
Partitioning v/s Bucketing:
Both partitioning and bucketing slice the data for executing the query much more efficiently than non-sliced data.
In partitioning, number of slices will keep on changing as data is modified.
In bucketing, number of slices are fixed which are specified while creating the table.
Enable bucketing in hive:
To enable bucketing, need to set below:
set hive.enforce.bucketing=true;
syntax:
create table bucketed_users(id int, name string) clustered by (id) into 4 buckets;
CLUSTERED BY clause is to specify the columns to bucket on and the number of buckets.
HIVE BUCKETING EXAMPLE:
1. create external table cc_bucket(cdate string, issue string, product string, state string, zipcode string, cid string) partitioned by (product string, submitted_via string) clustered by (zipcode) into 3 buckets row format delimited fields terminated by ',' lines terminated by '\n' stored as textfile;
2. set hive.enforce.bucketing=true;
set hive.exec.dynamic.partition=true;
set hive.exec.dynamic.partition.mode=nonstrict;
3. insert overwrite table cc_bucket partition(product,submitted_via) select cdate,issue,state,zipcode,cid,product,submitted_via from consumercomp;
You can also crosscheck by visiting localhost:50070 i.e, hdfs browse directory.







Comments