7AID4-01 · RTU · 4th Year
Big Data Analytics
Big Data features and the 3 V's, GFS and HDFS, Hadoop building blocks and cluster modes, MapReduce programming in Java (Driver, Mapper, Reducer, Combiner, Partitioner), Hadoop I/O and Writables, Pig Latin and Hive – with exam-ready diagrams and code.
Last time you stopped at card —. ·
- 62cards
- 5units
- 0nailed
- 62diagrams
62/62
-
Big Data refers to data sets whose size, speed and complexity are beyond the ability of traditional tools (RDBMS, single server) to capture, store, manage and analyse within an acceptable time.
Example: Facebook generates 4+ petabytes per day, a Boeing jet engine produces about 10 TB of sensor data in 30 minutes of flight, NSE records crores of trades daily.
Features / characteristics of Big Data:
- Volume – huge size (terabytes → petabytes → zettabytes)
- Velocity – data arrives very fast and must be processed quickly (streams, real time)
- Variety – many formats: tables, text, images, video, logs, JSON
- Veracity – data may be uncertain, noisy or incomplete
- Value – useful insight must be extracted, otherwise data is just cost
- Variability – meaning and flow rate of data keep changing
Other features of a Big Data system:
- Distributed – stored across many machines
- Scalable – add more nodes to handle more data (horizontal scaling)
- Fault tolerant – node failure does not lose data (replication)
- Schema-on-read – structure is applied while reading, not while storing
Units to remember: 1 KB → MB → GB → TB → PB → EB → ZB → YB (each ×1024).
Exam tip: Definition + the V's with one example each is a complete 5-mark answer.
-
Challenges of Big Data:
1. Storage – Data grows faster than disk capacity of one machine. Need distributed storage (HDFS).
2. Processing speed – Reading 1 TB from a single disk at 100 MB/s takes about 2.5 hours. With 100 disks in parallel it takes under 2 minutes. Need parallel processing (MapReduce).
3. Heterogeneity (variety) – 80% of data is unstructured (text, images, video) and does not fit in rows and columns.
4. Hardware failure – With thousands of commodity machines, failure is normal, not an exception. System must recover automatically.
5. Data quality (veracity) – Missing, duplicate and inconsistent data gives wrong results.
6. Security and privacy – Personal data (Aadhaar, health, banking) must be protected.
7. Scalability – System must grow from 10 to 10,000 nodes without redesign.
8. Combining data – Data read from many disks must be correctly merged (sort, join).
9. Skilled manpower and cost – Shortage of data engineers and analysts.
Challenge Hadoop's answer Storage HDFS (blocks on many nodes) Processing MapReduce (parallel) Failure Replication (default 3 copies) Variety Schema-on-read, any file format Cost Commodity hardware, open source Exam tip: Always pair every challenge with how Hadoop solves it.
-
Apache Hadoop is an open-source framework written in Java for the distributed storage and parallel processing of very large data sets on clusters of commodity hardware. It was created by Doug Cutting and Mike Cafarella (2005–06), inspired by Google's GFS and MapReduce papers, and is named after a toy elephant.
Core components:
- 1. HDFS – storage layer
- 2. MapReduce – processing layer
- 3. YARN – resource management (Hadoop 2)
- 4. Hadoop Common – shared libraries and utilities
Why Hadoop is used for Big Data analytics:
- Scalable – grows from one server to thousands of machines (scale-out)
- Cost effective – uses cheap commodity hardware and is open source
- Fault tolerant – data is replicated 3 times; failed tasks are re-run automatically
- Flexible – stores structured, semi-structured and unstructured data (schema-on-read)
- Fast – data locality: the code moves to the data, and processing is parallel
- Simple – programmer writes only map and reduce logic
- High throughput – designed for batch processing of huge files
Hadoop ecosystem:
Tool Purpose HDFS Distributed storage MapReduce Batch processing YARN Cluster resource management Pig Data-flow scripting (Pig Latin) Hive Data warehouse, SQL-like queries HBase NoSQL column-oriented database Sqoop Import/export between RDBMS and Hadoop Flume Collecting log and streaming data Oozie Workflow scheduling ZooKeeper Coordination service Mahout Machine-learning library Spark Fast in-memory processing Hadoop 1 vs Hadoop 2:
Point Hadoop 1 Hadoop 2 Processing MapReduce only YARN + MapReduce and others Daemons JobTracker, TaskTracker ResourceManager, NodeManager NameNode Single point of failure High availability (standby) Block size 64 MB 128 MB Scalability About 4,000 nodes About 10,000 nodes Exam tip: For a 2-mark answer: "Hadoop stores big data reliably on cheap machines (HDFS) and processes it in parallel (MapReduce)".
-
A data stream is a continuous, unbounded, fast sequence of data items arriving in real time – e.g. sensor readings, stock ticks, network packets, click-streams. It relates to the Velocity feature of Big Data. Queries on streams are continuous queries: they run all the time and give new answers as new data arrives.
Issues and challenges:
1. Unbounded memory requirement
The stream never ends, so it cannot be stored completely. Queries must work with limited memory.
2. Single-pass processing
Each item can be seen only once; there is no chance to go back and re-read old data.
3. Approximate query answering
Exact answers may need unlimited memory, so we accept approximate answers using sampling, sketches, histograms and synopses.
4. Sliding windows
Only the most recent data (last N items or last T seconds) is considered. Choosing the window type and size is a design issue.
5. Blocking operators
Operators such as sort, join, sum, count, max need the whole input before giving output – impossible on an endless stream. They have to be redefined over windows.
6. High and variable arrival rate
Data may come in bursts. When the system is overloaded it must drop some tuples – called load shedding.
7. Real-time response
Results are needed with very low latency, before the data loses its value.
8. Timestamps and out-of-order data
Items may arrive late or in the wrong order; deciding the time of each item (event time vs arrival time) is difficult.
9. Queries referring to past data
An ad-hoc query asked now may need old data that was already thrown away.
10. Fault tolerance and scalability
The system must keep running without losing state when a node fails.
Point Traditional DBMS query Stream query Data Stored, finite Continuous, unbounded Query One-time Continuous Access Random, many passes Sequential, single pass Answer Exact Often approximate Storage Unlimited disk Limited memory Tools: Apache Storm, Spark Streaming, Flink, Kafka. (Hadoop MapReduce is batch-oriented and not suited for streams.)
-
Traditional large-scale systems = RDBMS on a powerful server, data warehouses, and compute-intensive systems like Grid computing / HPC with MPI, where data is kept on a central storage (SAN) and copied to compute nodes.
Problems:
- 1. Vertical scaling (scale-up) limit – To handle more data we buy a bigger server (more CPU, RAM). It is very costly and has a physical limit.
- 2. Data is moved to the code – Data is copied over the network from storage to the processing node. For huge data, network bandwidth becomes the bottleneck.
- 3. Slow disk seek – RDBMS uses B-Tree and many seeks. Seek time improves much slower than transfer rate, so updating a large part of the database is slow.
- 4. Only structured data – Fixed schema (schema-on-write). Cannot handle text, images, logs.
- 5. Poor fault tolerance – Single point of failure. In MPI the programmer has to handle failures and checkpoints manually.
- 6. Complex programming – Programmer must manage threads, sockets, synchronisation and data flow.
- 7. High cost – Proprietary hardware and licences.
Hadoop's approach:
- Scale-out: add cheap commodity machines
- Move code to data (data locality): program runs on the node where the data block lives
- Sequential streaming reads of large blocks instead of seeks
- Automatic fault tolerance: replication and task re-execution
- Simple model: programmer writes only
map()andreduce()
Point RDBMS Hadoop MapReduce Data size Gigabytes Petabytes Access Interactive and batch Batch Updates Read and write many times Write once, read many times Structure Static schema Dynamic schema Integrity High (ACID) Low Scaling Non-linear (scale-up) Linear (scale-out)
-
Sources of Big Data are grouped into three broad classes:
1. Human / Social generated
- Social media: Facebook posts, tweets, Instagram photos, YouTube videos
- E-mails, blogs, reviews, WhatsApp messages
- Search queries and click-streams
2. Machine generated
- Sensors and IoT devices (smart meters, wearables)
- Web server logs and application logs
- GPS and satellite data, CCTV
- Scientific instruments (weather stations, Large Hadron Collider)
3. Transactional / Business generated
- Banking and stock-market transactions (NSE, BSE)
- E-commerce orders (Amazon, Flipkart), billing records
- Telecom call detail records (CDR)
- Government records: Aadhaar, GST, railways
Source Example Data type Social media Tweets, likes Unstructured Sensors Temperature readings Semi-structured Web logs Apache access log Semi-structured Transactions Bank ledger Structured Media Images, audio, video Unstructured Exam tip: Draw the three-class diagram (Human, Machine, Business) with two examples each.
-
The 3 V's were given by Doug Laney (2001). They define Big Data.
1. Volume (size of data)
- Amount of data generated and stored
- Measured in TB, PB, EB, ZB
- Example: Facebook stores 300+ PB; YouTube gets 500+ hours of video uploaded every minute
2. Velocity (speed of data)
- Speed at which data is generated, collected and must be processed
- Batch → near real time → real time → streaming
- Example: stock-market ticks, 6,000+ tweets per second, sensor streams
3. Variety (forms of data)
- Different formats and sources
- Structured (tables), semi-structured (XML, JSON, logs), unstructured (text, image, audio, video)
- About 80% of the world's data is unstructured
Additional V's (5 V's / 6 V's):
- Veracity – trustworthiness and quality of data (noise, bias, missing values)
- Value – business benefit obtained from the data
- Variability – inconsistency in data flow and meaning
V Question it answers Keyword Volume How much? Scale Velocity How fast? Speed Variety How many kinds? Formats Veracity How correct? Quality Value How useful? Insight Mnemonic: Very Vast Variety → Volume, Velocity, Variety.
-
1. Structured data
- Organised in a fixed schema of rows and columns
- Stored in RDBMS, queried using SQL
- Easy to search and analyse
- Examples: employee table, bank transactions, Excel sheet
- About 10–20% of total data
2. Semi-structured data
- No rigid table, but has tags or markers that describe the data (self-describing)
- Schema is flexible
- Examples: XML, JSON, CSV, e-mail (header + body), web logs, NoSQL documents
3. Unstructured data
- No predefined format or schema
- Difficult to store in tables and to analyse
- Examples: text documents, PDFs, images, audio, video, social-media posts
- About 80% of total data
Example of the same information:
Structured : | 101 | Ravi | 21 | Semi-structured : {"id":101, "name":"Ravi", "age":21} Unstructured : "Ravi, whose roll number is 101, turned 21 this year."Point Structured Semi-structured Unstructured Schema Fixed Flexible None Storage RDBMS XML / JSON / NoSQL HDFS, data lake Query SQL XPath, NoSQL queries Text mining, ML Analysis Easy Moderate Hard Exam tip: Hadoop is popular because it stores all three types – it applies schema while reading (schema-on-read).
-
Google File System (GFS) is a scalable distributed file system developed by Google (paper published in 2003 by Ghemawat, Gobioff and Leung) for large data-intensive applications. It runs on cheap commodity hardware and gives fault tolerance. HDFS is the open-source implementation of GFS.
Design assumptions:
- Component failures are normal
- Files are huge (multi-GB)
- Most writes are appends, random writes are rare
- Workload is large streaming reads
- High sustained throughput is more important than low latency
Architecture – three components:
1. GFS Master (single)
- Stores all metadata in memory: namespace, file-to-chunk mapping, chunk locations
- Keeps an operation log and checkpoints for recovery
- Does chunk lease management, garbage collection, re-replication and rebalancing
- Talks to chunkservers using HeartBeat messages
2. Chunkservers (many)
- Store the actual data as chunks of fixed size 64 MB on local Linux disks
- Each chunk has a unique 64-bit chunk handle
- Each chunk is replicated 3 times by default
3. GFS Client
- Library linked into the application
- Asks the master only for metadata, then reads/writes data directly with chunkservers
Read operation:
- 1. Client converts (file name, byte offset) into a chunk index
- 2. Client sends (file name, chunk index) to the master
- 3. Master replies with chunk handle and replica locations
- 4. Client reads the data directly from the nearest chunkserver
Key point: File data never flows through the master – this avoids a bottleneck.
-
HDFS was designed by Doug Cutting by following the GFS paper. Both use a master–slave architecture, large blocks and replication.
Point GFS HDFS Developed by Google (proprietary) Apache (open source) Language C++ Java Master node Master NameNode Slave node Chunkserver DataNode Unit of storage Chunk Block Default size 64 MB 64 MB (Hadoop 1), 128 MB (Hadoop 2) Default replicas 3 3 Metadata log Operation log EditLog + FsImage Write model Random writes and record append Write once, append only Multiple writers Supported Single writer per file Processing layer Google MapReduce Hadoop MapReduce Health check HeartBeat Heartbeat + Block report Common terms mapping:
GFS Master <-> NameNode Chunkserver <-> DataNode Chunk (64 MB) <-> Block (128 MB) Operation log <-> EditLog Bigtable <-> HBaseExam tip: "HDFS is the open-source clone of GFS" – write this line and then the comparison table.
-
HDFS (Hadoop Distributed File System) is the storage layer of Hadoop. It stores very large files as blocks across a cluster of commodity machines with streaming data access.
Components of HDFS (list all, explain any four):
- 1. NameNode – master, stores metadata
- 2. DataNode – slave, stores the actual blocks
- 3. Secondary NameNode – checkpointing (merges EditLog into FsImage)
- 4. Blocks – fixed-size pieces of a file (128 MB)
- 5. Replication – copies of each block (default 3) with rack awareness
- 6. FsImage and EditLog – metadata files of the NameNode
- 7. HDFS Client – library that talks to NameNode and DataNodes
- 8. Heartbeat and Block report – health messages from DataNodes
Architecture: Master–Slave
1. NameNode (master)
- Manages the file system namespace (directory tree) and metadata
- Knows which blocks make a file and on which DataNodes they are stored
- Metadata is kept in RAM and persisted in FsImage and EditLog
2. DataNodes (slaves)
- Store and retrieve actual data blocks
- Send heartbeat every 3 seconds and a block report to the NameNode
- Perform block creation, deletion and replication on NameNode's instruction
3. Blocks
- A file is split into fixed-size blocks: 128 MB (Hadoop 2) / 64 MB (Hadoop 1)
- A 500 MB file → 4 blocks (128 + 128 + 128 + 116 MB)
- A file smaller than a block does not occupy the full block
4. Replication
- Each block is copied to 3 DataNodes (default replication factor = 3)
- Rack awareness: 1st replica on the writer's node, 2nd on a node in a different rack, 3rd on a different node of that same second rack
Features of HDFS:
- Fault tolerant and highly available
- Scalable to thousands of nodes
- High throughput (batch processing)
- Write Once, Read Many (WORM) model
- Data locality – computation moves to the data
HDFS is not suitable for: low-latency access, lots of small files (metadata fills NameNode RAM), multiple writers or random modifications.
Why large blocks? To reduce seek cost and reduce the amount of metadata at the NameNode.
-
Anatomy of a File READ:
- 1. Client calls
open()onDistributedFileSystem. - 2. It asks the NameNode for the block locations (sorted by nearness to the client).
- 3. Client gets an
FSDataInputStreamand callsread(). - 4. Data is streamed from the nearest DataNode holding block 1.
- 5. When the block ends, the stream connects to the best DataNode for the next block.
- 6. Client calls
close().
Anatomy of a File WRITE:
- 1. Client calls
create()onDistributedFileSystem. - 2. NameNode checks permissions and that the file does not exist, then makes an entry.
- 3. Client writes to
FSDataOutputStream; data is split into packets put in the data queue. - 4. NameNode gives a list of 3 DataNodes – they form a pipeline.
- 5. Packet flows DN1 → DN2 → DN3. Acknowledgements return DN3 → DN2 → DN1 → client (ack queue).
- 6. Client calls
close()and informs the NameNode that the file is complete.
Java example – reading a file from HDFS:
import java.io.InputStream; import java.net.URI; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IOUtils; public class FileSystemCat { public static void main(String[] args) throws Exception { String uri = args[0]; // hdfs://localhost:9000/user/a.txt Configuration conf = new Configuration(); FileSystem fs = FileSystem.get(URI.create(uri), conf); InputStream in = null; try { in = fs.open(new Path(uri)); // returns FSDataInputStream IOUtils.copyBytes(in, System.out, 4096, false); } finally { IOUtils.closeStream(in); } } }Common shell commands:
hadoop fs -mkdir /user/data hadoop fs -put local.txt /user/data hadoop fs -ls /user/data hadoop fs -cat /user/data/local.txt hadoop fs -get /user/data/local.txt .Exam tip: Client gets only metadata from the NameNode. Data never passes through the NameNode.
- 1. Client calls
-
A daemon is a background process. Hadoop 1.x runs five daemons, each in its own JVM. They follow a master–slave design.
Daemon Layer Role Runs on NameNode Storage (HDFS) Master – keeps metadata Master node DataNode Storage (HDFS) Slave – stores blocks Every slave node Secondary NameNode Storage (HDFS) Checkpointing helper Separate machine JobTracker Processing (MapReduce) Master – schedules jobs Master node TaskTracker Processing (MapReduce) Slave – runs tasks Every slave node Typical cluster layout:
Master node : NameNode + JobTracker Helper node : Secondary NameNode Slave node 1..n: DataNode + TaskTrackerKey points:
- Each slave node runs both a DataNode and a TaskTracker so that tasks can run where the data is (data locality).
- NameNode and JobTracker are single points of failure in Hadoop 1.x.
- Check running daemons with the
jpscommand. - Start with
start-dfs.sh(HDFS daemons) andstart-mapred.sh(MapReduce daemons), orstart-all.sh.
Hadoop 2 note: JobTracker and TaskTracker are replaced by YARN's ResourceManager, NodeManager and ApplicationMaster.
Mnemonic: N-D-S-J-T → "No Data Should Just Travel".
-
NameNode (master of HDFS) – "the bookkeeper"
- Stores metadata: file names, directories, permissions, list of blocks of each file, replication factor
- Stores block locations in memory (rebuilt from block reports, not saved on disk)
- Maintains two persistent files:
- FsImage – complete snapshot of the namespace
- EditLog – every change made after the last snapshot
- Decides block placement and triggers re-replication when a DataNode dies
- Does not store actual data and data never flows through it
- Needs a lot of RAM: about 150 bytes per file/block object
- Single Point of Failure (SPOF) in Hadoop 1.x – if it fails, the whole file system is unavailable
DataNode (slave of HDFS) – "the workhorse"
- Stores actual data blocks as files on the local disk
- Serves read and write requests from clients
- Sends a heartbeat every 3 seconds; if no heartbeat for about 10 minutes, NameNode marks it dead and re-replicates its blocks
- Sends a block report (list of all blocks) periodically
- Verifies data using checksums
- Forwards data to the next DataNode in the write pipeline
Point NameNode DataNode Type Master Slave Stores Metadata Actual data blocks Count One (active) Many Hardware High RAM, reliable Commodity, large disks Failure effect Cluster down (Hadoop 1) Handled by replication Safe mode: At start-up the NameNode stays read-only until enough DataNodes report their blocks.
-
Secondary NameNode (SNN) is a helper daemon of the NameNode. Its only job is checkpointing – merging the EditLog into the FsImage periodically.
Important: It is NOT a backup or standby NameNode. It cannot take over automatically if the NameNode fails.
Why is it needed?
The NameNode writes every change to the EditLog and merges it with FsImage only at restart. On a busy cluster the EditLog becomes huge, so a restart would take hours. SNN keeps the EditLog small.
Checkpoint process:
- 1. SNN asks the NameNode to roll its edits – new changes now go to a fresh file
edits.new. - 2. SNN copies
fsimageandeditsfrom the NameNode (HTTP GET). - 3. SNN loads fsimage into memory and applies every operation from edits.
- 4. It creates a new merged file
fsimage.ckpt. - 5. SNN sends the new image back to the NameNode (HTTP POST).
- 6. NameNode replaces the old fsimage with the new one and renames
edits.newtoedits.
When does a checkpoint happen?
- Every 1 hour (
fs.checkpoint.period= 3600 s), or - When the edit log reaches 64 MB (
fs.checkpoint.size)
Points to remember:
- Needs as much memory as the NameNode, so it runs on a separate machine
- Its copy of the image is slightly old, so on NameNode failure some data loss is certain – but it can be used for manual recovery
- Hadoop 2 adds a real Standby NameNode for High Availability
Exam tip: Write "Secondary NameNode = checkpoint node, not hot standby" – examiners look for this line.
- 1. SNN asks the NameNode to roll its edits – new changes now go to a fresh file
-
JobTracker (master of MapReduce)
- Only one per cluster, usually on the master node
- Accepts jobs from clients
- Asks the NameNode where the data blocks are
- Creates an execution plan: splits the job into map and reduce tasks
- Assigns tasks to TaskTrackers that are near the data (data locality)
- Monitors tasks; if a task fails, it re-schedules it on another node
- Single point of failure for MapReduce in Hadoop 1
TaskTracker (slave of MapReduce)
- One on every slave node
- Executes the map and reduce tasks given by the JobTracker, each in a separate child JVM
- Has a fixed number of slots for map and reduce tasks
- Sends a heartbeat to the JobTracker every few seconds with its status and free slots
- If the heartbeat stops, the JobTracker assumes the node is dead and re-runs its tasks elsewhere
Job execution flow:
- 1. Client submits the job (jar + configuration) to the JobTracker.
- 2. Job resources are copied to HDFS; input splits are computed.
- 3. JobTracker creates one map task per input split.
- 4. TaskTrackers with free slots ask for work through heartbeats.
- 5. JobTracker assigns tasks (prefers node-local, then rack-local).
- 6. TaskTracker launches a child JVM and runs the task.
- 7. Progress and completion are reported back; the client is informed.
Point JobTracker TaskTracker Role Master Slave Number One One per slave node Work Scheduling and monitoring Executing tasks Pairs with NameNode DataNode Speculative execution: If a task is slow, the JobTracker starts a duplicate on another node and uses whichever finishes first.
-
Hadoop can be installed and run in three modes.
1. Local (Standalone) mode
- Default mode of Hadoop
- No daemons run; everything runs in a single JVM
- Uses the local file system, not HDFS
- The three XML files are left empty
- Use: learning, developing and debugging MapReduce programs
2. Pseudo-distributed mode
- A single-node cluster: all five daemons run on one machine, each in a separate JVM
- Uses HDFS; replication factor is set to 1
- Daemons communicate through
localhostusing SSH - Use: testing code, memory use and HDFS interaction before moving to a real cluster
3. Fully distributed mode
- The real production cluster with many machines
- Master nodes run NameNode and JobTracker; slave nodes run DataNode and TaskTracker
- Secondary NameNode runs on a separate machine
- Replication factor 3;
mastersandslavesfiles list the hosts - Gives full scalability and fault tolerance
Point Local Pseudo-distributed Fully distributed Machines 1 1 Many Daemons None All, on one node Spread across nodes JVMs Single One per daemon One per daemon File system Local FS HDFS HDFS Replication Not applicable 1 3 fs.default.namefile:///hdfs://localhost/hdfs://namenode/mapred.job.trackerlocallocalhost:8021jobtracker:8021Use Debugging Testing Production Exam tip: This table is asked very frequently – learn the property values row.
-
Hadoop is configured through files in the
conf/(oretc/hadoop/) directory. Each XML file holdspropertyelements with a name and a value.File Purpose Key properties core-site.xmlCommon settings for HDFS and MapReduce fs.default.name(NameNode URI),hadoop.tmp.dirhdfs-site.xmlHDFS daemon settings dfs.replication,dfs.name.dir,dfs.data.dir,dfs.block.sizemapred-site.xmlMapReduce daemon settings mapred.job.tracker,mapred.local.dirhadoop-env.shEnvironment variables JAVA_HOME,HADOOP_HEAPSIZEmastersHost of the Secondary NameNode one host per line slavesHosts running DataNode + TaskTracker one host per line Pseudo-distributed configuration:
core-site.xml<configuration> <property> <name>fs.default.name</name> <value>hdfs://localhost:9000</value> </property> </configuration>hdfs-site.xml<configuration> <property> <name>dfs.replication</name> <value>1</value> </property> </configuration>mapred-site.xml<configuration> <property> <name>mapred.job.tracker</name> <value>localhost:9001</value> </property> </configuration>Steps to start a pseudo-distributed cluster:
- 1. Install Java and set
JAVA_HOMEinhadoop-env.sh - 2. Set up password-less SSH to localhost (
ssh-keygen) - 3. Edit the three XML files as above
- 4. Format the NameNode:
hadoop namenode -format - 5. Start daemons:
start-dfs.shandstart-mapred.sh - 6. Verify with
jpsand the web UIs (NameNode 50070, JobTracker 50030)
Hadoop 2 names:
fs.defaultFS,dfs.namenode.name.dir,dfs.datanode.data.dir, plusyarn-site.xmlandmapreduce.framework.name = yarn.Reading configuration in Java:
Configuration conf = new Configuration(); conf.addResource("core-site.xml"); System.out.println(conf.get("fs.default.name")); - 1. Install Java and set
-
MapReduce is a programming model and processing framework of Hadoop for processing huge data sets in parallel on a cluster. It was introduced by Google (2004). The programmer writes only two functions – map and reduce – and the framework handles parallelism, data distribution and failures.
Everything is a key–value pair:
map : (K1, V1) -> list(K2, V2) reduce : (K2, list(V2)) -> list(K3, V3)Phases:
- 1. Input split – input file is divided into splits (usually one per HDFS block); one map task per split
- 2. Map – processes each record and emits intermediate (key, value) pairs
- 3. Shuffle and Sort – framework groups all values of the same key and sorts by key
- 4. Reduce – processes each key with its list of values and emits the final output
- 5. Output – written to HDFS as
part-r-00000files
WordCount example:
Input : "Deer Bear River" / "Car Car River" / "Deer Car Bear" Map output : (Deer,1) (Bear,1) (River,1) (Car,1) (Car,1) (River,1) (Deer,1) (Car,1) (Bear,1) Shuffle+Sort : (Bear,[1,1]) (Car,[1,1,1]) (Deer,[1,1]) (River,[1,1]) Reduce output: (Bear,2) (Car,3) (Deer,2) (River,2)Features:
- Scalable – add nodes to process more data
- Fault tolerant – failed tasks are re-executed
- Data locality – map runs on the node holding the block
- Simple – no thread or socket programming
Limitation: Meant for batch processing; not for real-time or iterative jobs.
Exam tip: Draw the Input → Split → Map → Shuffle/Sort → Reduce → Output diagram with the word-count values.
-
The dataset: The National Climatic Data Center (NCDC) collects readings from weather sensors across the world every hour. Data is stored as line-oriented ASCII – each line is one record with fixed-width fields (station id, date, time, temperature, quality code…). There is one file per station per year, so there are thousands of small files, which are merged year-wise.
Problem: Find the highest recorded temperature for each year.
Important fields in a record line:
Characters Field 15–19 Year 87 Sign of temperature (+ or −) 88–92 Air temperature in tenths of °C 92–93 Quality code - Missing temperature is written as 9999
- Reading is valid if the quality code is one of 0, 1, 4, 5, 9
Without Hadoop: A Unix
awkscript processes years one by one – slow (about 42 minutes for a century), and running it in parallel by hand is messy (unequal file sizes, combining results, single-machine limit).With MapReduce:
Input to map (K1,V1): (0, 0067011990999991950051507004...+0000...) (106, 0043011990999991950051512004...+0022...) (212, 0043011990999991950051518004...-0011...) (318, 0043012650999991949032412004...+0111...) (424, 0043012650999991949032418004...+0078...) Map output (K2,V2): (1950, 0) (1950, 22) (1950, -11) (1949, 111) (1949, 78) After shuffle : (1949, [111, 78]) (1950, [0, 22, -11]) Reduce output (K3,V3): (1949, 111) (1950, 22)- Key to map = byte offset of the line (ignored), value = the line
- Map extracts (year, temperature) and filters bad records
- Reduce finds the maximum of the list
Temperatures are in tenths of a degree, so 111 means 11.1 °C.
Exam tip: State input and output key–value types: map
(LongWritable, Text) → (Text, IntWritable), reduce(Text, IntWritable) → (Text, IntWritable).
-
Hadoop API is the set of Java packages, classes and interfaces that Hadoop gives to programmers to write MapReduce applications –
Mapper,Reducer,Job,Configuration,InputFormat,Writabletypes and so on. A program uses this API to tell the framework what to do in the map and reduce steps.Hadoop provides two Java APIs for MapReduce. The new API (introduced in release 0.20, often called "Context Objects") is cleaner and easier to evolve. The two are not compatible with each other.
Point Old API New API Package org.apache.hadoop.mapredorg.apache.hadoop.mapreduceMapper / Reducer Interfaces (extend MapReduceBase)Abstract classes Output collection OutputCollectorandReporterSingle ContextobjectJob configuration JobConfConfigurationJob control JobClient.runJob(conf)Jobclass,job.waitForCompletion(true)Reduce values java.util.Iteratorjava.lang.Iterable(for-each loop)Control of flow Only push style Push and pull – can override run()Output file names part-nnnnnpart-m-nnnnn(map),part-r-nnnnn(reduce)Exceptions IOExceptionIOException, InterruptedExceptionCleanup method close()cleanup(Context)Old API mapper:
public class MaxTempMapper extends MapReduceBase implements Mapper<LongWritable, Text, Text, IntWritable> { public void map(LongWritable key, Text value, OutputCollector<Text, IntWritable> output, Reporter reporter) throws IOException { // ... output.collect(new Text(year), new IntWritable(temp)); } }New API mapper:
public class MaxTempMapper extends Mapper<LongWritable, Text, Text, IntWritable> { @Override public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { // ... context.write(new Text(year), new IntWritable(temp)); } }Why abstract classes in the new API? A method with a default implementation can be added to an abstract class without breaking old code. Adding a method to an interface breaks every class that implements it.
Exam tip: Remember the pairs:
mapredvsmapreduce,JobConfvsJob,OutputCollectorvsContext,IteratorvsIterable.
-
The Mapper processes one input record at a time and emits intermediate key–value pairs. We extend the generic class
Mapper<KEYIN, VALUEIN, KEYOUT, VALUEOUT>and overridemap().import java.io.IOException; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; public class MaxTemperatureMapper extends Mapper<LongWritable, Text, Text, IntWritable> { private static final int MISSING = 9999; @Override public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { String line = value.toString(); String year = line.substring(15, 19); int airTemperature; if (line.charAt(87) == '+') { // parseInt does not like a leading plus airTemperature = Integer.parseInt(line.substring(88, 92)); } else { airTemperature = Integer.parseInt(line.substring(87, 92)); } String quality = line.substring(92, 93); if (airTemperature != MISSING && quality.matches("[01459]")) { context.write(new Text(year), new IntWritable(airTemperature)); } } }Explanation:
Type parameter Type Meaning KEYIN LongWritableByte offset of the line in the file VALUEIN TextOne line of the weather file KEYOUT TextYear VALUEOUT IntWritableAir temperature - Hadoop uses its own types (
LongWritable,Text,IntWritable) instead ofLong,String,Integerbecause they are optimised for network serialization. map()is called once for every record.context.write()emits the output pair.- Records with missing value 9999 or a bad quality code are filtered out.
Other methods of Mapper:
setup()runs once before the first record,cleanup()once after the last,run()controls the loop. - Hadoop uses its own types (
-
The Reducer receives each key with all its values grouped together (after shuffle and sort) and produces the final result. We extend
Reducer<KEYIN, VALUEIN, KEYOUT, VALUEOUT>and overridereduce().import java.io.IOException; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Reducer; public class MaxTemperatureReducer extends Reducer<Text, IntWritable, Text, IntWritable> { @Override public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException { int maxValue = Integer.MIN_VALUE; for (IntWritable value : values) { maxValue = Math.max(maxValue, value.get()); } context.write(key, new IntWritable(maxValue)); } }Explanation:
- Input types of the reducer must match the output types of the mapper → here
TextandIntWritable. reduce()is called once for every unique key – e.g.(1950, [0, 22, -11]).- The loop walks through the
Iterableand keeps the largest value. value.get()convertsIntWritableto a Javaint.context.write()writes(1950, 22)to the output filepart-r-00000.
Three phases inside a reduce task:
- 1. Shuffle – copy the sorted map outputs from all mappers
- 2. Sort / merge – merge them so that equal keys are together
- 3. Reduce – call
reduce()for each key group
Points to remember:
- Number of reducers is set by
job.setNumReduceTasks(n); default is 1 - With
n = 0the job is map-only and map output goes directly to HDFS - Each reducer writes its own output file, so n reducers give n part files
- Keys reach a reducer in sorted order; values are not sorted
- Input types of the reducer must match the output types of the mapper → here
-
The Driver is the class with the
main()method. It configures the job and submits it to the cluster. It tells Hadoop which Mapper, Reducer, input/output paths and data types to use.import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; public class MaxTemperature { public static void main(String[] args) throws Exception { if (args.length != 2) { System.err.println("Usage: MaxTemperature <input path> <output path>"); System.exit(-1); } Job job = new Job(); job.setJarByClass(MaxTemperature.class); job.setJobName("Max temperature"); FileInputFormat.addInputPath(job, new Path(args[0])); FileOutputFormat.setOutputPath(job, new Path(args[1])); job.setMapperClass(MaxTemperatureMapper.class); job.setReducerClass(MaxTemperatureReducer.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); System.exit(job.waitForCompletion(true) ? 0 : 1); } }Line-by-line meaning:
Statement Purpose new Job()Creates the job specification object setJarByClass()Hadoop finds the JAR containing this class and ships it to the cluster addInputPath()Input file or directory (can be called many times) setOutputPath()Output directory – must not already exist setMapperClass()/setReducerClass()Classes to run setOutputKeyClass()/setOutputValueClass()Types of the reducer output waitForCompletion(true)Submits the job and waits; trueprints progressIf map output types differ from reduce output types, also call
setMapOutputKeyClass()andsetMapOutputValueClass().Optional settings:
setCombinerClass(),setPartitionerClass(),setNumReduceTasks(),setInputFormatClass().Running the job:
javac -classpath `hadoop classpath` -d classes *.java jar -cvf maxtemp.jar -C classes . hadoop jar maxtemp.jar MaxTemperature input/ncdc/sample.txt output hadoop fs -cat output/part-r-00000Why must the output directory not exist? To prevent accidental overwriting of the result of a long previous job.
-
WordCount counts how many times each word appears in the input. It is the "Hello World" of Hadoop.
import java.io.IOException; import java.util.StringTokenizer; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; public class WordCount { // ---------- MAPPER ---------- public static class TokenizerMapper extends Mapper<Object, Text, Text, IntWritable> { private final static IntWritable one = new IntWritable(1); private Text word = new Text(); public void map(Object key, Text value, Context context) throws IOException, InterruptedException { StringTokenizer itr = new StringTokenizer(value.toString()); while (itr.hasMoreTokens()) { word.set(itr.nextToken()); context.write(word, one); // (word, 1) } } } // ---------- REDUCER ---------- public static class IntSumReducer extends Reducer<Text, IntWritable, Text, IntWritable> { private IntWritable result = new IntWritable(); public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException { int sum = 0; for (IntWritable val : values) { sum += val.get(); } result.set(sum); context.write(key, result); // (word, total) } } // ---------- DRIVER ---------- public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); Job job = Job.getInstance(conf, "word count"); job.setJarByClass(WordCount.class); job.setMapperClass(TokenizerMapper.class); job.setCombinerClass(IntSumReducer.class); job.setReducerClass(IntSumReducer.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); FileInputFormat.addInputPath(job, new Path(args[0])); FileOutputFormat.setOutputPath(job, new Path(args[1])); System.exit(job.waitForCompletion(true) ? 0 : 1); } }Steps to compile and run:
# 1. Compile the program against the Hadoop libraries mkdir classes javac -classpath `hadoop classpath` -d classes WordCount.java # 2. Package the classes into a JAR file jar -cvf wordcount.jar -C classes . # 3. Put the input file into HDFS hadoop fs -mkdir /input hadoop fs -put sample.txt /input # 4. Run the job (the output directory must not exist) hadoop jar wordcount.jar WordCount /input /output # 5. See the result hadoop fs -ls /output hadoop fs -cat /output/part-r-00000 # 6. Remove the output directory before running again hadoop fs -rm -r /outputWorking:
- 1. Mapper splits each line into words and emits
(word, 1). - 2. Combiner adds the counts locally on each mapper node.
- 3. Shuffle and sort groups the pairs:
(Car, [1,1,1]). - 4. Reducer adds the list and emits
(Car, 3).
Good practice shown: The
TextandIntWritableobjects are created once and reused withset()– this avoids creating millions of objects.Exam tip: In a 10-mark question write all three parts (Mapper, Reducer, Driver) and a small sample input/output.
- 1. Mapper splits each line into words and emits
-
A mapper works on key–value pairs, but a file in HDFS is just a stream of bytes. Three components convert the file into records.
1. InputFormat
- Decides how the input is split and how it is read
- Two jobs:
getSplits()creates the InputSplits,createRecordReader()returns a RecordReader - Default is
TextInputFormat
2. InputSplit
- A logical chunk of the input processed by one map task
- It does not contain data – only a reference (file, start offset, length, host locations)
- Usually split size = HDFS block size (128 MB), so number of splits = number of map tasks
3. RecordReader
- Converts the byte-oriented split into record-oriented (key, value) pairs for the mapper
- Called again and again until the split is finished
- For
TextInputFormatthe reader isLineRecordReader: key = byte offset of the line (LongWritable), value = line content (Text) - Handles records that cross block boundaries: it reads past the end of the split to finish the last line and skips the first partial line of the next split
How the Mapper uses it (the
run()method):public void run(Context context) throws IOException, InterruptedException { setup(context); while (context.nextKeyValue()) { // RecordReader.nextKeyValue() map(context.getCurrentKey(), context.getCurrentValue(), context); } cleanup(context); }Why is the RecordReader important?
- The Mapper cannot read raw bytes – without a RecordReader it would get no (key, value) input at all
- It defines what one record means (a line, a key-value line, N lines, a binary record)
- It handles records split across block boundaries, so no line is lost or read twice
- It gives the byte-offset key, which lets each record be identified uniquely
- A custom RecordReader lets Hadoop process any format – XML, JSON, logs, multi-line records
- It streams records one by one, so a huge split never has to fit in memory
Common InputFormats:
InputFormat Key Value TextInputFormat(default)Byte offset Line KeyValueTextInputFormatText before the tab Text after the tab NLineInputFormatByte offset Line (N lines per split) SequenceFileInputFormatUser defined User defined Block vs split: A block is a physical division of data in HDFS. A split is a logical division used by MapReduce.
RecordWriter is the opposite – it writes the output (key, value) pairs to the output file (
TextOutputFormatwrites key TAB value).
-
A Combiner is an optional function that runs on the map output, on the mapper's node, before the data is sent to the reducer. It is called a "mini reducer" or local reducer.
Why? Bandwidth in a cluster is limited. The combiner reduces the amount of data transferred between mappers and reducers during the shuffle.
Example – maximum temperature for 1950 with two mappers:
Mapper 1 output : (1950, 0) (1950, 20) (1950, 10) Mapper 2 output : (1950, 25) (1950, 15) WITHOUT combiner -> reducer gets (1950, [0, 20, 10, 25, 15]) -> 5 values travel WITH combiner -> Mapper 1 sends (1950, 20), Mapper 2 sends (1950, 25) reducer gets (1950, [20, 25]) -> 2 values travel Result in both cases: (1950, 25)This works because
max(0, 20, 10, 25, 15) = max( max(0, 20, 10), max(25, 15) ).Setting the combiner in the driver:
job.setMapperClass(MaxTemperatureMapper.class); job.setCombinerClass(MaxTemperatureReducer.class); // reducer reused as combiner job.setReducerClass(MaxTemperatureReducer.class);Rules:
- The combiner is a class that extends
Reducer - Its input and output types must be the same as the map output types
- Hadoop gives no guarantee of how many times it is called (zero, one or many) – so the job must give the same result with or without it
- The operation must be commutative and associative
Operation Combiner usable? Max, Min Yes Sum, Count Yes Mean (average) No Median No Why not for mean?
mean(0, 20, 10, 25, 15) = 14butmean( mean(0, 20, 10), mean(25, 15) ) = mean(10, 20) = 15– wrong answer.(Fix: let the combiner emit sum and count, and compute the mean in the reducer.)
Exam tip: "A combiner does not replace the reducer; it only reduces shuffle data."
- The combiner is a class that extends
-
A Partitioner decides which reducer each intermediate (key, value) pair from the mapper goes to. It runs after the map (and before the combiner/shuffle) and guarantees that all records with the same key reach the same reducer.
Number of partitions = number of reduce tasks.
Default: HashPartitioner
public class HashPartitioner<K, V> extends Partitioner<K, V> { public int getPartition(K key, V value, int numReduceTasks) { return (key.hashCode() & Integer.MAX_VALUE) % numReduceTasks; } }key.hashCode()gives an integer for the key& Integer.MAX_VALUEmakes it non-negative% numReduceTasksgives a partition number from 0 to n−1
Why a custom partitioner?
- The hash may distribute data unevenly (data skew) – one reducer overloaded
- We may want a meaningful grouping, e.g. one output file per age group, per country or per year
Custom Partitioner example – partition employees by age group (3 reducers):
import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Partitioner; public class AgePartitioner extends Partitioner<Text, Text> { @Override public int getPartition(Text key, Text value, int numReduceTasks) { String[] fields = value.toString().split("\t"); int age = Integer.parseInt(fields[2]); if (numReduceTasks == 0) return 0; if (age <= 20) { return 0; // part-r-00000 } else if (age <= 30) { return 1 % numReduceTasks; // part-r-00001 } else { return 2 % numReduceTasks; // part-r-00002 } } }In the driver:
job.setPartitionerClass(AgePartitioner.class); job.setNumReduceTasks(3);Point Combiner Partitioner Purpose Reduce data sent to reducers Decide the reducer for each key Extends ReducerPartitionerMethod reduce()getPartition()Optional? Yes Default HashPartitioner is always used Exam tip: With only one reducer the partitioner has no effect – every key goes to partition 0.
-
Shuffle is the process by which the framework sorts the map outputs and transfers them to the reducers. MapReduce guarantees that the input to every reducer is sorted by key. Shuffle is called the "heart of MapReduce".
Map side:
- 1. Map output is written to a circular memory buffer (default 100 MB,
io.sort.mb). - 2. When the buffer is 80% full, a background thread spills the content to disk.
- 3. Before spilling, data is divided into partitions (one per reducer), and inside each partition it is sorted by key in memory.
- 4. If a combiner is set, it runs on the sorted data.
- 5. Many spill files are merged into one partitioned and sorted output file.
Reduce side:
- 1. Copy phase – the reducer fetches its partition from every mapper over HTTP (5 parallel copier threads by default).
- 2. Merge (sort) phase – the fetched map outputs are merged, keeping the sort order (merge factor 10).
- 3. Reduce phase –
reduce()is called once for each key with its values; output is written to HDFS.
Complete order of steps:
map() -> buffer -> partition -> sort -> combine -> spill -> merge -> copy (fetch) -> merge -> reduce() -> output to HDFSPoints to remember:
- Sorting is done on keys, not on values
- Map output can be compressed to make the shuffle faster (
mapred.compress.map.output) - If there are zero reducers, no shuffle and sort happens
- Tuning the shuffle (bigger buffer, fewer spills) gives a large performance gain
Exam tip: Mention the numbers – 100 MB buffer, 80% threshold – and draw the map-side and reduce-side boxes.
- 1. Map output is written to a circular memory buffer (default 100 MB,
-
Define Big Data.
Data sets so large, fast and varied that traditional tools cannot store or process them; described by Volume, Velocity and Variety.
What are the three V's?
Volume (size), Velocity (speed of generation), Variety (different formats).
Types of data / What is semi-structured data?
Structured, semi-structured, unstructured. Semi-structured data has no fixed table schema but carries tags or markers, e.g. XML, JSON.
Why is Hadoop used in Big Data analytics?
It stores huge data on cheap commodity machines (HDFS) and processes it in parallel (MapReduce) with scalability and fault tolerance.
What is Google File System?
Google's scalable distributed file system with one master and many chunkservers storing 64 MB chunks with 3 replicas; HDFS is based on it.
What is HDFS?
The Hadoop Distributed File System – stores very large files as replicated blocks across a cluster in a master–slave (NameNode–DataNode) design.
Define DataNode.
Slave daemon of HDFS that stores the actual data blocks and sends heartbeats and block reports to the NameNode.
What is JobTracker?
Master daemon of MapReduce that accepts jobs, schedules tasks on TaskTrackers and monitors them.
Pseudo-distributed vs fully distributed mode?
Pseudo: all daemons on one machine, replication 1, for testing. Fully: daemons spread over many machines, replication 3, for production.
Two important XML configuration files?
core-site.xml(NameNode address) andhdfs-site.xml(replication factor); alsomapred-site.xml.What is MapReduce?
A programming model that processes large data in parallel using a map function (filter and transform) and a reduce function (aggregate).
What is Hadoop API?
The set of Java packages, classes and interfaces (
org.apache.hadoop.mapred– old,org.apache.hadoop.mapreduce– new) used to write MapReduce programs.What is Mapper code?
The class extending
Mapperwhosemap()method reads one record and emits intermediate key–value pairs.What is Driver code?
The class with
main()that configures the job (mapper, reducer, paths, types) and submits it.Function of a Partitioner?
Decides which reducer gets each map output key:
hash(key) mod numReducers.Combiner vs Partitioner?
Combiner locally aggregates map output to reduce data transfer; Partitioner decides the reducer for each key.
-
Serialization is the process of converting a structured object into a byte stream so that it can be sent over a network or written to disk. Deserialization converts the byte stream back into an object.
Where Hadoop uses it:
- Inter-process communication – RPC between nodes
- Persistent storage – writing data to HDFS files
A good serialization format must be:
- Compact – saves network bandwidth
- Fast – little overhead to read and write
- Extensible – protocol can change over time
- Interoperable – works across languages
Hadoop does not use Java Serialization (
java.io.Serializable) because it is bulky (writes class names and metadata) and slow, and creates a new object for every record. Hadoop uses its own compact format – Writable.The Writable interface:
package org.apache.hadoop.io; import java.io.DataOutput; import java.io.DataInput; import java.io.IOException; public interface Writable { void write(DataOutput out) throws IOException; // serialize void readFields(DataInput in) throws IOException; // deserialize }Example with IntWritable:
IntWritable writable = new IntWritable(); writable.set(163); // or new IntWritable(163) // Serialize ByteArrayOutputStream out = new ByteArrayOutputStream(); DataOutputStream dataOut = new DataOutputStream(out); writable.write(dataOut); dataOut.close(); byte[] bytes = out.toByteArray(); // 4 bytes: 00 00 00 a3 // Deserialize IntWritable newWritable = new IntWritable(); ByteArrayInputStream in = new ByteArrayInputStream(bytes); DataInputStream dataIn = new DataInputStream(in); newWritable.readFields(dataIn); System.out.println(newWritable.get()); // 163An integer is written as 4 bytes in big-endian order: 163 →
000000a3.Points to remember:
- Every key and value type in MapReduce must implement
Writable - Writable objects are mutable and are reused, which reduces garbage collection
- Every Writable must have a default (no-argument) constructor
-
MapReduce sorts keys during the shuffle phase, so keys must be comparable as well as writable.
1. WritableComparable
public interface WritableComparable<T> extends Writable, Comparable<T> { }- Combines
Writable(write, readFields) andjava.lang.Comparable(compareTo) - All keys must implement WritableComparable; values need only Writable
- Example:
IntWritable implements WritableComparable<IntWritable>
2. RawComparator
public interface RawComparator<T> extends Comparator<T> { public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2); }- Compares two records directly from their serialized bytes, without deserializing them into objects
b1= byte array,s1= start position,l1= length (same for the second record)- Much faster – no object creation
- Example: IntWritable's comparator reads the integers straight from the byte arrays and compares them
3. WritableComparator
- A general-purpose implementation of RawComparator for WritableComparable classes
- Gives a default raw
compare()that deserializes the objects and calls theircompareTo() - Acts as a factory for comparators
RawComparator<IntWritable> comparator = WritableComparator.get(IntWritable.class); IntWritable w1 = new IntWritable(163); IntWritable w2 = new IntWritable(67); // compare objects int r1 = comparator.compare(w1, w2); // > 0 (163 > 67) // compare serialized bytes byte[] b1 = serialize(w1); byte[] b2 = serialize(w2); int r2 = comparator.compare(b1, 0, b1.length, b2, 0, b2.length); // > 0Interface / class Purpose WritableSerialize and deserialize ComparableCompare two objects WritableComparableBoth – required for keys RawComparatorCompare serialized bytes directly WritableComparatorReady-made RawComparator implementation Exam tip: Reason for RawComparator = speed in the sort phase, since millions of keys are compared.
- Combines
-
Hadoop provides a Writable wrapper class for every Java primitive type (except
char, which can be stored in anIntWritable). All are in the packageorg.apache.hadoop.io. Each hasget()andset()methods.Java primitive Writable class Serialized size (bytes) boolean BooleanWritable1 byte ByteWritable1 short ShortWritable2 int IntWritable4 int VIntWritable1–5 float FloatWritable4 long LongWritable8 long VLongWritable1–9 double DoubleWritable8 Usage:
IntWritable i = new IntWritable(10); int x = i.get(); // unwrap i.set(25); // reuse the same object LongWritable l = new LongWritable(100L); DoubleWritable d = new DoubleWritable(3.14); BooleanWritable b = new BooleanWritable(true);Fixed-length vs variable-length encoding:
Fixed length (
IntWritable,LongWritable)- Always the same number of bytes
- Good when values are uniformly distributed over the whole range (e.g. hash values)
Variable length (
VIntWritable,VLongWritable)- Small numbers take fewer bytes: a value between −112 and 127 uses only 1 byte; otherwise the first byte tells the sign and how many bytes follow
- Good for non-uniform data where most values are small – saves space
- VInt and VLong use the same encoding, so you can switch from VInt to VLong later without changing the stored data
163 as IntWritable -> 00 00 00 a3 (4 bytes) 163 as VIntWritable -> 8f a3 (2 bytes) 1 as VIntWritable -> 01 (1 byte)Class hierarchy:
Writable └── WritableComparable ├── BooleanWritable, ByteWritable, ShortWritable ├── IntWritable, VIntWritable, LongWritable, VLongWritable ├── FloatWritable, DoubleWritable ├── Text, BytesWritable, NullWritable, MD5Hash ├── ArrayWritable, TwoDArrayWritable ├── MapWritable, SortedMapWritable └── ObjectWritable, GenericWritableExam tip: All the wrappers implement WritableComparable, so all can be used as keys.
-
Textis a Writable for UTF-8 character sequences. It is the Writable equivalent ofjava.lang.String.Features:
- Stores data in standard UTF-8 encoding
- Uses a variable-length int to store the number of bytes, so the maximum size is 2 GB
- Mutable – the same object can be reused with
set() - Implements
WritableComparable, so it can be a key
Indexing is by byte offset, not by character:
Text t = new Text("hadoop"); t.getLength(); // 6 -> number of BYTES t.getBytes().length; // 6 t.charAt(2); // (int) 'd' -> returns an int code point, not char t.charAt(100); // -1 if out of range t.find("do"); // 2 -> byte offset (like String.indexOf) t.find("pig"); // -1 t.toString(); // "hadoop" as a Java StringMutability:
Text t = new Text("hadoop"); t.set("pig"); t.getLength(); // 3 t.getBytes().length; // 3 or more -> buffer may be larger, so always trust getLength()Text vs String:
Point Java StringHadoop TextEncoding UTF-16 UTF-8 Indexing unit charcode unitByte offset charAt()returnscharint(Unicode code point)Mutable? No (immutable) Yes length()Number of char units getLength()= number of bytesSerialization Java Serializable Writable (compact) Rich API (substring, split) Yes No – convert with toString()Why the difference matters: For plain ASCII text, byte offset and character index are the same. For multi-byte characters (Hindi, emoji) one character takes 2–4 bytes, so
getLength()is greater than the number of characters.Iterating over characters: Convert the Text to a
java.nio.ByteBufferand callText.bytesToCodePoint()repeatedly.Exam tip: In most programs we simply write
String line = value.toString();and then use String methods. -
BytesWritable
- A wrapper for an array of binary data (
byte[]) - Serialized format: a 4-byte integer giving the number of bytes, followed by the bytes themselves
- Mutable – value can be changed with
set() - Used for images, audio or any raw binary data, and as key/value in SequenceFiles
BytesWritable b = new BytesWritable(new byte[] { 3, 5 }); byte[] bytes = serialize(b); // Hex output: 000000020305 // 00000002 -> length = 2 // 03 05 -> the data b.setCapacity(11); b.getLength(); // 2 -> actual data size b.getBytes().length; // 11 -> size of the backing buffer- Always use
getLength()for the real size;getBytes().lengthgives only the buffer capacity.
NullWritable
- A special Writable with a zero-length serialization – no bytes are written or read
- Used as a placeholder when a key or a value is not needed
- It is an immutable singleton – get the instance with
NullWritable.get()(the constructor is private)
// Emit only the key, no value context.write(new Text(word), NullWritable.get()); // Driver job.setOutputValueClass(NullWritable.class);Uses of NullWritable:
- Mapper or reducer that outputs only keys or only values (e.g. finding distinct words)
- Storing a list of values in a SequenceFile where no key is needed
- Saves disk space and network transfer compared to writing an empty
Text
Point BytesWritable NullWritable Holds Binary byte array Nothing Serialized size 4 + n bytes 0 bytes Mutable Yes No (singleton) Create with new BytesWritable(bytes)NullWritable.get()Use Images, binary records Placeholder key/value - A wrapper for an array of binary data (
-
ObjectWritable
- A general-purpose wrapper that can hold: Java primitives,
String,enum,Writable,null, or arrays of any of these - Used in Hadoop RPC to marshal and unmarshal method arguments and return values
- Useful when a field can be of more than one type – e.g. the values in a SequenceFile have different types
- Drawback: it writes the full class name of the wrapped type every time it is serialized, e.g.
org.apache.hadoop.io.Text– a big waste of space
ObjectWritable ow = new ObjectWritable(new Text("hadoop")); Object obj = ow.get(); // returns the wrapped Text Class c = ow.getDeclaredClass(); // Text.classGenericWritable
- A better choice when the number of possible types is small and known in advance
- It keeps a static array of types and stores only the index (one byte) of the type instead of the class name
- It is an abstract class – we must subclass it and say which types are allowed by overriding
getTypes()
import org.apache.hadoop.io.GenericWritable; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.Writable; public class MyGenericWritable extends GenericWritable { private static Class<? extends Writable>[] CLASSES = null; static { CLASSES = (Class<? extends Writable>[]) new Class[] { IntWritable.class, // index 0 Text.class // index 1 }; } public MyGenericWritable() { } public MyGenericWritable(Writable instance) { set(instance); } @Override protected Class<? extends Writable>[] getTypes() { return CLASSES; } }Usage in a reducer:
for (MyGenericWritable v : values) { Writable w = v.get(); if (w instanceof IntWritable) { /* number */ } else if (w instanceof Text) { /* string */ } }Point ObjectWritable GenericWritable Types supported Any (primitives, String, enum, Writable, arrays) Only those listed in getTypes()Type information stored Full class name 1-byte index Space Wasteful Compact Use directly? Yes No – must subclass Main use Hadoop RPC Different value types from mappers to one reducer Exam tip: Typical use of GenericWritable – a reduce-side join, where two mappers emit different value types for the same key.
- A general-purpose wrapper that can hold: Java primitives,
-
The package
org.apache.hadoop.iohas six Writable collection types.1. ArrayWritable – a one-dimensional array of Writable instances
2. TwoDArrayWritable – a two-dimensional array (matrix) of Writable instances
- All elements must be of the same class, given in the constructor
ArrayWritable aw = new ArrayWritable(Text.class); aw.set(new Text[] { new Text("pig"), new Text("hive") }); Writable[] arr = aw.get();- To use it as reducer input or in a SequenceFile, make a subclass that fixes the type:
public class TextArrayWritable extends ArrayWritable { public TextArrayWritable() { super(Text.class); } }3. ArrayPrimitiveWritable – a wrapper for arrays of Java primitives (
int[],double[]); the type is detected automatically, so no subclass is needed.4. MapWritable – implements
java.util.Map<Writable, Writable>5. SortedMapWritable – implements
java.util.SortedMap<WritableComparable, Writable>(keys kept sorted)- Keys and values can be of different types in the same map
- The type of each entry is stored as a single byte that indexes into an array of types (so only 127 non-standard types are possible)
MapWritable src = new MapWritable(); src.put(new IntWritable(1), new Text("cat")); src.put(new VIntWritable(2), new LongWritable(163)); MapWritable dest = new MapWritable(); WritableUtils.cloneInto(dest, src); Text t = (Text) dest.get(new IntWritable(1)); // cat LongWritable n = (LongWritable) dest.get(new VIntWritable(2)); // 1636. EnumSetWritable – a wrapper for a
java.util.EnumSet(a set of enum values).What about Set and List?
- Set – use a
MapWritablewithNullWritablevalues (orEnumSetWritablefor enums) - List of one type – use
ArrayWritable - List of mixed types – use
GenericWritableelements inside anArrayWritable
Class Java equivalent Elements ArrayWritableWritable[]Same type TwoDArrayWritableWritable[][]Same type ArrayPrimitiveWritableint[],double[]...Primitives MapWritableHashMapMixed types SortedMapWritableTreeMapMixed, sorted keys EnumSetWritableEnumSetEnum values Mnemonic: A-T-A-M-S-E → Array, TwoDArray, ArrayPrimitive, Map, SortedMap, EnumSet.
-
The built-in Writables cover simple cases. When a key or value has several fields (e.g. a pair of strings, or an employee record), we write our own class. A custom Writable gives full control over the binary format and the sort order.
Steps:
- 1. Implement
WritableComparable<T>(or onlyWritableif it is used just as a value) - 2. Provide a default constructor (Hadoop creates objects by reflection)
- 3. Write
write()– serialize every field in order - 4. Write
readFields()– read the fields back in the same order - 5. Override
hashCode()– used by HashPartitioner to choose the reducer - 6. Override
equals()andtoString()–toString()is used by TextOutputFormat - 7. Write
compareTo()– defines the sort order of keys
TextPair – a pair of strings:
import java.io.*; import org.apache.hadoop.io.*; public class TextPair implements WritableComparable<TextPair> { private Text first; private Text second; public TextPair() { set(new Text(), new Text()); } public TextPair(String first, String second) { set(new Text(first), new Text(second)); } public void set(Text first, Text second) { this.first = first; this.second = second; } public Text getFirst() { return first; } public Text getSecond() { return second; } @Override public void write(DataOutput out) throws IOException { first.write(out); second.write(out); } @Override public void readFields(DataInput in) throws IOException { first.readFields(in); second.readFields(in); } @Override public int hashCode() { return first.hashCode() * 163 + second.hashCode(); } @Override public boolean equals(Object o) { if (o instanceof TextPair) { TextPair tp = (TextPair) o; return first.equals(tp.first) && second.equals(tp.second); } return false; } @Override public String toString() { return first + "\t" + second; } @Override public int compareTo(TextPair tp) { int cmp = first.compareTo(tp.first); if (cmp != 0) { return cmp; } return second.compareTo(tp.second); } }Explanation:
write()andreadFields()simply delegate to the twoTextfieldscompareTo()sorts by the first string, and if equal, by the secondhashCode()must give the same value on every JVM, otherwise the same key may go to different reducers
Exam tip: The three method groups to mention – serialization (write, readFields), partitioning (hashCode), sorting (compareTo).
- 1. Implement
-
Problem: When
TextPairis used as a key, the default comparator deserializes both records into objects and then callscompareTo(). During sorting, millions of comparisons happen, so creating objects every time is slow.Solution: Write a RawComparator that compares the two keys directly in their serialized byte form.
How TextPair looks in bytes: It is two
Textobjects joined together. EachTextis stored as a variable-length integer (VInt) holding the number of bytes, followed by the UTF-8 bytes.[ VInt len1 ][ bytes of first ][ VInt len2 ][ bytes of second ]So the length of the first field = size of the VInt + value of the VInt.
public static class Comparator extends WritableComparator { private static final Text.Comparator TEXT_COMPARATOR = new Text.Comparator(); public Comparator() { super(TextPair.class); } @Override public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) { try { int firstL1 = WritableUtils.decodeVIntSize(b1[s1]) + readVInt(b1, s1); int firstL2 = WritableUtils.decodeVIntSize(b2[s2]) + readVInt(b2, s2); int cmp = TEXT_COMPARATOR.compare(b1, s1, firstL1, b2, s2, firstL2); if (cmp != 0) { return cmp; } return TEXT_COMPARATOR.compare(b1, s1 + firstL1, l1 - firstL1, b2, s2 + firstL2, l2 - firstL2); } catch (IOException e) { throw new IllegalArgumentException(e); } } } static { WritableComparator.define(TextPair.class, new Comparator()); // register }Explanation:
- 1.
decodeVIntSize(b1[s1])→ how many bytes the length-prefix itself occupies - 2.
readVInt(b1, s1)→ the value of the prefix = number of bytes of the first string - 3. Their sum
firstL1= total bytes taken by the firstTextfield - 4. Compare the first fields using Text's own raw comparator
- 5. If they are equal, compare the remaining bytes (the second fields)
- 6. The static block registers the comparator so that Hadoop uses it automatically for
TextPair
Advantages:
- No object creation and no deserialization
- Faster sort and merge in the shuffle phase
- Less garbage collection
Exam tip: We extend WritableComparator (not implement RawComparator directly) because it already gives helper methods like
readVInt()andreadInt(). - 1.
-
A custom comparator is a comparator written separately from the key class to sort or group keys in a different way from the default
compareTo()order.Example – FirstComparator: compares only the first field of a
TextPairand ignores the second.public static class FirstComparator extends WritableComparator { private static final Text.Comparator TEXT_COMPARATOR = new Text.Comparator(); public FirstComparator() { super(TextPair.class); } // Raw (byte-level) comparison @Override public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) { try { int firstL1 = WritableUtils.decodeVIntSize(b1[s1]) + readVInt(b1, s1); int firstL2 = WritableUtils.decodeVIntSize(b2[s2]) + readVInt(b2, s2); return TEXT_COMPARATOR.compare(b1, s1, firstL1, b2, s2, firstL2); } catch (IOException e) { throw new IllegalArgumentException(e); } } // Object-level comparison @Override public int compare(WritableComparable a, WritableComparable b) { if (a instanceof TextPair && b instanceof TextPair) { return ((TextPair) a).getFirst().compareTo(((TextPair) b).getFirst()); } return super.compare(a, b); } }Both
compare()methods are overridden so that the two give the same result.Where comparators are plugged in (driver):
job.setSortComparatorClass(KeyComparator.class); // order of keys given to reducer job.setGroupingComparatorClass(FirstComparator.class); // which keys go in one reduce() call job.setPartitionerClass(FirstPartitioner.class); // which reducerUse: Secondary sort
MapReduce sorts keys but not values. To get values in sorted order (e.g. maximum temperature of each year appearing first):
- 1. Make a composite key = (year, temperature)
- 2. Partition by year only → all records of a year go to the same reducer
- 3. Sort comparator → year ascending, temperature descending
- 4. Grouping comparator → group by year only, so one
reduce()call gets all temperatures of that year, already sorted
Comparator Set by Decides Sort comparator setSortComparatorClass()Order of keys Grouping comparator setGroupingComparatorClass()Keys treated as equal for one reduce call Partitioner setPartitionerClass()Reducer number Exam tip: Rules for a custom comparator – extend
WritableComparator, callsuper(KeyClass.class)in the constructor, overridecompare().
-
Apache Pig is a high-level platform for analysing large data sets on Hadoop. It was developed at Yahoo! (2006) and later given to Apache. Programs are written in a data-flow scripting language called Pig Latin, and Pig automatically converts them into MapReduce jobs.
Why the name? Like a pig, it "eats anything" – structured, semi-structured or unstructured data.
Why Pig is needed:
- Writing MapReduce in Java is long and difficult – a simple join needs about 200 lines
- Not every analyst knows Java
- Common operations (join, filter, group, sort) have to be coded again and again
- About 10 lines of Pig Latin = 200 lines of Java; development time is far less
Two parts of Pig:
- 1. Pig Latin – the language to express data flows
- 2. Pig Engine (runtime) – the execution environment that runs Pig Latin on Hadoop
Features:
- Rich set of operators: join, filter, group, sort, union
- Ease of programming – similar to SQL
- Automatic optimisation of the execution plan
- Extensible – user-defined functions (UDFs) in Java, Python
- Handles all kinds of data; schema is optional
- Nested data types: tuple, bag, map
WordCount in Pig Latin (compare with 60 lines of Java):
lines = LOAD 'input.txt' AS (line:chararray); words = FOREACH lines GENERATE FLATTEN(TOKENIZE(line)) AS word; grpd = GROUP words BY word; counts = FOREACH grpd GENERATE group, COUNT(words); STORE counts INTO 'output';Point Pig MapReduce Level High-level data-flow language Low-level framework Language Pig Latin Java Lines of code Few Many Join operation Built-in, one line Hard to write Compilation Not needed (converted internally) Long compile and package cycle Speed of execution Slightly slower Faster when hand-tuned Best for Quick analysis, ETL, prototyping Fine-grained control Exam tip: "Pig is to Hadoop what a scripting language is to an operating system" – an abstraction over MapReduce.
-
Pig sits on top of Hadoop. A Pig Latin script passes through several components that turn it into MapReduce jobs.
1. Pig Latin script / interfaces
The user submits statements through the Grunt shell, a script file, or an embedded Java program (Pig Server).
2. Parser
- Checks syntax and does type checking
- Output is a logical plan – a DAG (Directed Acyclic Graph) in which nodes are the operators and edges are the data flows
3. Optimizer
- Performs logical optimisations on the DAG
- Examples: projection push-down (drop unused columns early), filter push-down (filter rows as early as possible)
4. Compiler
- Converts the optimised logical plan into a physical plan and then into a series of MapReduce jobs
5. Execution Engine
- Submits the MapReduce jobs to Hadoop in sorted order
- Jobs run on the cluster and produce the result
6. Hadoop (HDFS + MapReduce)
- HDFS provides the input data and stores the output
Flow:
Pig Latin script | Parser -> logical plan (DAG) | Optimizer -> optimised logical plan | Compiler -> MapReduce jobs | Execution engine -> runs jobs on Hadoop | Result in HDFS / on screenLazy evaluation: Pig only builds the plan when statements are typed. Nothing runs until a
DUMPorSTOREstatement is reached. This lets the optimizer look at the whole program first.Plans in order: Logical plan → Physical plan → MapReduce plan. Use
EXPLAIN alias;to see them.Exam tip: Draw the block diagram with Parser → Optimizer → Compiler → Execution Engine inside a box named "Pig Latin Compiler / Pig Engine", with Hadoop below it.
-
A Pig Latin program is a series of statements. Each statement takes a relation as input and gives another relation as output. Every Pig program follows the same three-step flow, similar to ETL (Extract–Transform–Load).
Step 1 – LOAD
- Read the data from HDFS (or local file system) into a relation
- A schema may be given with
AS - Nothing is actually loaded yet – Pig only notes where the data is
Step 2 – TRANSFORM
- Apply operators:
FILTER,FOREACH ... GENERATE,GROUP,JOIN,ORDER BY,DISTINCT,UNION - This is where all the data manipulation happens
Step 3 – DUMP or STORE
DUMP– show the result on the screen (for debugging small data)STORE– write the result to a file in HDFS- Only now does Pig run the MapReduce jobs
Example – total flight miles of each airline carrier:
A = LOAD 'data/flights.csv' USING PigStorage(',') AS (year:int, carrier:chararray, distance:int); B = FILTER A BY distance > 0; C = GROUP B BY carrier; D = FOREACH C GENERATE group AS carrier, SUM(B.distance) AS total_miles; E = ORDER D BY total_miles DESC; DUMP E; STORE E INTO 'output/miles' USING PigStorage(',');Explanation:
Statement Step Work LOADLoad Reads the CSV and applies a schema FILTERTransform Removes rows with zero distance GROUPTransform Collects rows of each carrier into a bag FOREACH ... GENERATETransform Computes the sum for each group ORDERTransform Sorts in descending order DUMP/STOREOutput Triggers execution and gives the result Points to remember:
- Each statement ends with a semicolon
- Names like A, B, C are called aliases (relation names)
- Keywords are not case sensitive, but alias names and function names are case sensitive
- Pig Latin is a data-flow language (step by step), while SQL is a declarative language (says what, not how)
Debugging helpers:
DESCRIBE(schema),EXPLAIN(plans),ILLUSTRATE(sample run step by step).
-
The ABCs of Pig Latin are its basic building blocks: statements and operators, relations, and data types.
Structure of Pig Latin:
- A program is a sequence of statements; each ends with a semicolon
- A statement applies an operator to a relation and gives a new relation:
alias = OPERATOR input ...; - An expression (like
marks > 75) is used inside operators - Keywords are not case sensitive; aliases and function names are
- Comments:
--for one line,/ ... /for many lines
Pig has a fully nested data model. Data types are of two kinds: scalar (simple) and complex.
Scalar types:
Type Description Example int32-bit signed integer 10 long64-bit signed integer 10L float32-bit floating point 10.5F double64-bit floating point 10.5 chararrayString in UTF-8 'hadoop' bytearrayBlob of bytes (default type when no schema is given) – booleantrue / false true datetimeDate and time 2026-01-15T10:30:00 Complex types:
1. Atom – a single value (field), e.g.
'Ravi'or212. Tuple – an ordered set of fields, like a row. Written in round brackets.
(Ravi, 21, Jaipur)3. Bag – an unordered collection of tuples, like a table. Written in curly brackets. Tuples in a bag need not have the same number of fields, and duplicates are allowed.
{(Ravi, 21), (Sita, 20), (Aman, 22, Kota)}4. Map – a set of key–value pairs. Written in square brackets with
#. The key must be a chararray and unique.[name#Ravi, age#21]5. Relation – the outermost structure; it is a bag of tuples (an "outer bag"). A bag inside a tuple is called an inner bag.
Nested example:
(Ravi, {(DBMS, 85), (BDA, 90)}, [city#Jaipur, pin#302001])Here a tuple contains an atom, a bag and a map.
Comparison with RDBMS:
Pig RDBMS Relation (bag) Table Tuple Row Field (atom) Column value Nested bag, map Not allowed (1NF) Null: Any type can be
null– it means the value is unknown or missing.Mnemonic for brackets: Tuple
( ), Bag{ }, Map[ ]. -
Assume this relation:
students = LOAD 'student.txt' USING PigStorage(',') AS (id:int, name:chararray, branch:chararray, marks:int);Loading and storing:
Operator Use LOADRead data into a relation STORESave a relation to a file DUMPPrint a relation on the screen Filtering and projection:
toppers = FILTER students BY marks >= 75; names = FOREACH students GENERATE name, marks; uniq = DISTINCT names; top5 = LIMIT students 5;Grouping and aggregation:
grp = GROUP students BY branch; stats = FOREACH grp GENERATE group, COUNT(students), AVG(students.marks);Output of GROUP is
(group, {bag of matching tuples}).Sorting:
sorted = ORDER students BY marks DESC;Joining and combining:
j = JOIN students BY id, fees BY sid; -- inner join lj = JOIN students BY id LEFT OUTER, fees BY sid; cg = COGROUP students BY id, fees BY sid; -- group two relations together u = UNION students, old_students; SPLIT students INTO pass IF marks >= 40, fail IF marks < 40;Flattening nested data:
words = FOREACH lines GENERATE FLATTEN(TOKENIZE(line));FLATTENremoves one level of nesting – it turns a bag into separate rows.Diagnostic operators:
Operator Use DESCRIBEShow the schema of a relation EXPLAINShow logical, physical and MapReduce plans ILLUSTRATEShow step-by-step execution on sample data Built-in functions:
- Eval:
COUNT,SUM,AVG,MIN,MAX,CONCAT,SIZE,TOKENIZE - Load/Store:
PigStorage,TextLoader,JsonLoader,BinStorage - String:
UPPER,LOWER,SUBSTRING,TRIM - Math:
ABS,ROUND,SQRT
Exam tip: Group the operators as Load/Store, Relational (filter, group, join, sort) and Diagnostic – then give one line of code for each.
- Eval:
-
Pig has two execution modes. The mode decides where the data is and where the script runs.
1. Local mode
- Pig runs in a single JVM on one machine
- Uses the local file system – Hadoop and HDFS are not required
- Suitable for small data sets, learning, development and testing
- Command:
pig -x local pig -x local wordcount.pig2. Distributed mode (MapReduce mode)
- This is the default mode
- Pig translates the script into MapReduce jobs and runs them on a Hadoop cluster (pseudo or fully distributed)
- Data is read from and written to HDFS
- Suitable for large data sets and production
- Pig must know the cluster: it reads
core-site.xmlandmapred-site.xmlfromHADOOP_HOME - Command:
pig pig -x mapreduce pig -x mapreduce wordcount.pigPoint Local mode Distributed (MapReduce) mode Flag -x local-x mapreduce(default)File system Local HDFS Runs on Single JVM, one machine Hadoop cluster Needs Hadoop? No Yes Data size Small Large Parallelism No Yes Use Testing, debugging Production Good practice: First test the script in local mode on a small sample, and then run the same script without any change in MapReduce mode on the full data.
Newer engines: Later versions also support
-x tezand-x spark, which run the same script on faster engines.Exam tip: "Local mode → local file system; MapReduce mode → HDFS" is the key line.
-
Pig programs can be run through three interfaces, and each of them works in both local and MapReduce mode.
1. Grunt shell (interactive mode)
- A command-line shell started by typing
pig; the prompt isgrunt> - Statements are typed one by one and run when
DUMPorSTOREis given - Best for ad-hoc queries and prototyping
- Also runs HDFS commands (
fs -ls) and shell commands (sh ls)
$ pig -x local grunt> A = LOAD 'student.txt' USING PigStorage(',') AS (id:int, name:chararray); grunt> B = FILTER A BY id > 100; grunt> DUMP B; grunt> quit2. Script (batch mode)
- All statements are saved in a file with the extension
.pig - The whole file is run with a single command – suitable for production and scheduled jobs
$ pig wordcount.pig $ pig -x local -param input=data.txt wordcount.pig grunt> run wordcount.pig (or: exec wordcount.pig)3. Embedded mode (in Java)
- Pig Latin statements are run from inside a Java program using the
PigServerclass – similar to using JDBC for SQL - Useful to combine Pig with normal program logic (loops, conditions)
import org.apache.pig.PigServer; public class WordCountPig { public static void main(String[] args) throws Exception { PigServer pig = new PigServer("mapreduce"); // or "local" pig.registerQuery("A = LOAD 'input.txt' AS (line:chararray);"); pig.registerQuery("B = FOREACH A GENERATE FLATTEN(TOKENIZE(line)) AS word;"); pig.registerQuery("C = GROUP B BY word;"); pig.registerQuery("D = FOREACH C GENERATE group, COUNT(B);"); pig.store("D", "output"); // triggers execution } }Interface How Best for Grunt shell Type statements at grunt>Interactive, ad-hoc work Script file pig file.pigBatch, production Embedded PigServerin JavaIntegration with applications Useful Grunt commands:
help,quit,fs,sh,clear,history,set,kill jobid,exec,run.Difference between exec and run:
execruns the script in a separate context (its aliases are not visible in the shell afterwards);runruns it in the current shell, so the aliases remain available. - A command-line shell started by typing
-
Script 1 – Maximum temperature per year (the weather problem in 5 lines):
records = LOAD 'input/ncdc/sample.txt' AS (year:chararray, temperature:int, quality:int); filtered = FILTER records BY temperature != 9999 AND (quality == 0 OR quality == 1 OR quality == 4 OR quality == 5 OR quality == 9); grouped = GROUP filtered BY year; max_temp = FOREACH grouped GENERATE group, MAX(filtered.temperature); DUMP max_temp;Output:
(1949,111)and(1950,22).Script 2 – Using a User Defined Function (UDF)
When built-in functions are not enough, we write our own function in Java.
Step 1 – Java code (extend
EvalFunc):package myudfs; import java.io.IOException; import org.apache.pig.EvalFunc; import org.apache.pig.data.Tuple; public class UPPER extends EvalFunc<String> { @Override public String exec(Tuple input) throws IOException { if (input == null || input.size() == 0 || input.get(0) == null) { return null; } String str = (String) input.get(0); return str.toUpperCase(); } }Step 2 – Compile it into a JAR, then register and use it:
REGISTER myudfs.jar; A = LOAD 'student.txt' USING PigStorage(',') AS (id:int, name:chararray); B = FOREACH A GENERATE id, myudfs.UPPER(name); DUMP B;Types of UDF:
Type Base class Purpose Eval function EvalFuncCompute a value from fields Filter function FilterFuncReturns boolean, used in FILTER Load function LoadFuncCustom input format Store function StoreFuncCustom output format Parameter substitution in scripts:
A = LOAD '$input' AS (line:chararray);Run with
pig -param input=data.txt script.pig.Pig Latin vs SQL:
Point Pig Latin SQL Style Procedural data-flow (step by step) Declarative Schema Optional, can be given at run time Mandatory Data model Nested (tuple, bag, map) Flat tables Data Structured and unstructured Structured Execution Lazy; optimised pipeline Query optimiser decides the plan Intermediate results Can be stored at any step Not easily Exam tip: Steps for a UDF – write (extend EvalFunc, override exec) → compile to JAR → REGISTER → call with the package name.
-
Input file
marks.csv(roll number, name, branch, subject, marks):101,Ravi,AID,BDA,82 101,Ravi,AID,ML,74 102,Sita,AID,BDA,91 102,Sita,AID,ML,88 103,Aman,CSE,BDA,56 103,Aman,CSE,ML,38Pig Latin script
student_avg.pig:-- 1. LOAD the data with a schema marks = LOAD 'marks.csv' USING PigStorage(',') AS (roll:int, name:chararray, branch:chararray, subject:chararray, score:int); -- 2. Remove invalid records valid = FILTER marks BY score IS NOT NULL AND score >= 0 AND score <= 100; -- 3. Average, highest and lowest score of each student by_student = GROUP valid BY (roll, name); student_avg = FOREACH by_student GENERATE FLATTEN(group) AS (roll, name), COUNT(valid) AS subjects, AVG(valid.score) AS avg_score, MAX(valid.score) AS highest, MIN(valid.score) AS lowest; -- 4. Average score of each subject by_subject = GROUP valid BY subject; subject_avg = FOREACH by_subject GENERATE group AS subject, AVG(valid.score) AS avg_score; -- 5. Students with average above 75, ranked toppers = FILTER student_avg BY avg_score > 75.0; ranked = ORDER student_avg BY avg_score DESC; -- 6. Output DUMP ranked; STORE subject_avg INTO 'output/subject_avg' USING PigStorage(',');Output of
DUMP ranked:(102,Sita,2,89.5,91,88) (101,Ravi,2,78.0,82,74) (103,Aman,2,47.0,56,38)subject_avggives(BDA,76.33)and(ML,66.67).Explanation:
Step Statement Work 1 LOAD ... ASReads the comma-separated file and names the fields 2 FILTERKeeps only valid marks between 0 and 100 3 GROUP BY (roll, name)Makes one group per student: ((101,Ravi), {bag of rows})3 FOREACH ... GENERATE AVG()Computes the average on the bag of each group 4 GROUP BY subjectClass average of each subject 5 FILTER,ORDERFinds toppers and sorts by average 6 DUMP/STORETriggers the MapReduce jobs and gives the output Points to note:
- After
GROUP, the key is calledgroupand the bag has the name of the grouped relation (valid) valid.scoremeans "the score column of the bag"FLATTEN(group)turns the tuple key(101,Ravi)back into two separate fields- Run it with
pig -x local student_avg.pig(testing) orpig student_avg.pig(cluster)
Exam tip: Follow the flow LOAD → FILTER → GROUP → FOREACH (AVG) → ORDER → DUMP/STORE and show a small input and output.
- After
-
Good Pig scripts are correct, readable and efficient. Since every script becomes MapReduce jobs, the main aim is to move as little data as possible through the pipeline.
1. Filter early and often
Apply
FILTERas soon as possible afterLOAD, so that fewer rows go to later (costly) steps like join and group.2. Project early and often
Use
FOREACH ... GENERATEto keep only the columns that are needed. Unused columns should be dropped at the start.3. Declare the schema and types
Give field names and types with
AS (id:int, name:chararray). Without types every field is abytearrayand Pig has to guess, which is slower and error-prone (numbers default to double).4. Choose the right operator
Use
DISTINCT,LIMIT,JOINandCOGROUPcorrectly; do not useGROUPplus nested code when a built-in operator does the work.5. Set up joins properly
- Remove nulls from the join key before joining
- Keep the largest relation last in the JOIN
- Use special joins where suitable:
'replicated'(one small table, kept in memory),'skewed'(uneven keys),'merge'(already sorted inputs)
6. Use algebraic built-in functions
Functions like
COUNT,SUM,MIN,MAX,AVGcan use the combiner, which reduces shuffle data.7. Set parallelism
Use the
PARALLEL nclause (orSET default_parallel n) on reduce-side operators (GROUP, JOIN, ORDER) to control the number of reducers.8. Test on small data in local mode first
Use
pig -x localwith a sample, and check each step withDESCRIBE,ILLUSTRATEandEXPLAIN. UseDUMPonly for small data; useSTOREfor real runs.9. Remember lazy evaluation
Nothing runs until
DUMPorSTORE. Avoid many DUMPs – each one re-runs the pipeline. Store intermediate results if they are reused.10. Write readable, reusable scripts
- Meaningful alias names (
filtered_marks, notB) - Comments with
--or/ / - Parameters (
$input) instead of hard-coded paths - Reusable macros (
DEFINE) and UDFs for repeated logic
11. Combine and compress
Combine many small input files, and compress intermediate results (
pig.tmpfilecompression) to save disk and network.Example – bad vs good:
-- Bad: join everything first, filter later J = JOIN students BY id, marks BY sid; R = FILTER J BY marks::score > 75; -- Good: filter and project first, then join M = FILTER marks BY score > 75; M2 = FOREACH M GENERATE sid, score; S2 = FOREACH students GENERATE id, name; R = JOIN S2 BY id, M2 BY sid;Mnemonic: F-P-T-J-P → Filter early, Project early, Type your data, Join wisely, Parallelise.
-
Apache Hive is a data warehouse system built on top of Hadoop. It lets users query and analyse large data stored in HDFS using an SQL-like language called HiveQL (HQL). Hive converts the queries into MapReduce (or Tez / Spark) jobs.
It was developed at Facebook (2007) so that analysts who know SQL, but not Java, could use Hadoop.
Key idea: Hive applies structure (tables, rows, columns) on files that already exist in HDFS. The data stays as files in HDFS; the table definitions (schema) are kept separately in the metastore.
Features:
- SQL-like queries (HiveQL) – easy to learn
- Schema-on-read – schema is checked when data is read, so loading is very fast
- Stores schema in a metastore (RDBMS) and data in HDFS
- Handles very large data – scalable and fault tolerant
- Supports partitioning and bucketing for faster queries
- Supports many file formats: TextFile, SequenceFile, RCFile, ORC, Parquet
- Extensible with UDFs, UDAFs and UDTFs
- Provides JDBC / ODBC connectivity
Limitations:
- Not for OLTP – meant for batch analytics (OLAP)
- High latency – even a small query takes several seconds, since a job has to be started
- No real-time queries
- Row-level UPDATE and DELETE are limited (only in ACID / ORC tables)
- Sub-query support is limited
Hive vs RDBMS:
Point Hive RDBMS Schema Schema-on-read Schema-on-write Workload OLAP, batch analytics OLTP, real time Data size Petabytes Gigabytes to terabytes Model Write once, read many Read and write many times Latency High (seconds to minutes) Low (milliseconds) Transactions Limited Full ACID Scaling Horizontal, cheap Vertical, costly Storage HDFS Local disk / SAN Hello Hive:
hive> SHOW DATABASES; hive> CREATE TABLE hello (msg STRING); hive> SELECT COUNT(1) FROM hello;Exam tip: "Hive is not a database, it is a data warehouse infrastructure on Hadoop" – a common one-mark point.
-
HiveQL (Hive Query Language, HQL) is the SQL-like query language of Apache Hive. It is used to create databases and tables, load data and query data stored in HDFS. Hive translates each HiveQL statement into MapReduce (or Tez/Spark) jobs.
HiveQL has three parts: DDL (CREATE, ALTER, DROP), DML (LOAD, INSERT) and queries (SELECT with WHERE, GROUP BY, JOIN, ORDER BY).
HiveQL vs traditional SQL:
Point HiveQL Traditional SQL (RDBMS) Runs on Hadoop (HDFS + MapReduce) Database server Schema Schema-on-read Schema-on-write Purpose Analytics on huge data (OLAP) Transactions and queries (OLTP) Updates INSERT; UPDATE / DELETE only on ACID tables INSERT, UPDATE, DELETE freely Transactions Limited Full ACID Indexes Limited Fully supported Latency High – minutes (batch) Low – milliseconds Joins Equi-joins mainly All types of joins Data types Primitive + ARRAY, MAP, STRUCT Mostly primitive Sorting clauses ORDER BY, SORT BY, DISTRIBUTE BY, CLUSTER BY ORDER BY only Extra features Partitions, buckets, multi-table insert, TRANSFORMwith scriptsStored procedures, triggers, keys Data size Petabytes Gigabytes to terabytes Constraints (primary/foreign key) Not enforced Enforced Similarities: Both use databases, tables, rows and columns, and the same keywords – SELECT, FROM, WHERE, GROUP BY, HAVING, JOIN, ORDER BY, and aggregate functions.
How Hive simplifies querying on Hadoop data:
- 1. No Java programming – one line of HiveQL replaces a full MapReduce program
- 2. Familiar SQL syntax – analysts can work on Hadoop without learning a new model
- 3. Applies structure to raw files – tables are defined over files already in HDFS, without moving or converting them
- 4. Metastore – remembers the schema and location, so users need not know file paths and formats
- 5. Automatic optimisation – Hive plans joins, pushes filters down and chooses the number of reducers
- 6. Partitioning and bucketing – only the needed part of the data is scanned
- 7. Standard connectivity – JDBC/ODBC lets BI tools like Tableau and Excel query Hadoop
- 8. Extensible – UDFs for custom logic
Example – the same task both ways:
SELECT branch, AVG(marks) FROM student GROUP BY branch;In MapReduce this needs a Mapper class, a Reducer class and a Driver – about 60 lines of Java plus compiling and packaging a JAR.
Advantages of Hive (2-mark answer): easy SQL-like language, handles huge data, fast development, supports many file formats, and connects with BI tools.
-
Components of Hive:
1. Hive Clients / User Interface
- CLI / Beeline (command line), Web UI, and applications using JDBC, ODBC or Thrift
2. HiveServer (Thrift Server)
- Accepts requests from remote clients and passes them to the driver
3. Driver
- Receives the query, creates a session and controls the whole life cycle
- Contains:
- Parser – checks syntax, builds a parse tree
- Compiler (Planner) – does semantic checks using the metastore and builds the execution plan
- Optimizer – improves the plan (column pruning, predicate push-down, join re-ordering); plan is a DAG of stages
- Executor – runs the stages
4. Metastore
- Stores metadata: databases, tables, columns and types, partitions, and the HDFS location of data
- Kept in an RDBMS – embedded Derby by default, MySQL in production
5. Execution Engine
- Runs the plan as MapReduce jobs (or Tez / Spark) on the cluster
6. Hadoop – HDFS and MapReduce / YARN
- HDFS holds the actual data files
Steps in query execution:
- 1. User submits the query through a client (executeQuery)
- 2. Driver sends the query to the compiler (getPlan)
- 3. Compiler asks the metastore for metadata (getMetaData)
- 4. Metastore returns the metadata (sendMetaData)
- 5. Compiler creates the plan and returns it to the driver (sendPlan)
- 6. Driver sends the plan to the execution engine (executePlan)
- 7. Execution engine runs the jobs on Hadoop (executeJob) – it may also do DDL operations on the metastore
- 8. Results are fetched from HDFS and returned to the client (fetchResults / sendResults)
Flow in one line:
Client -> Driver -> Compiler <-> Metastore -> Optimizer -> Execution Engine -> MapReduce on HDFS -> Result back to clientExam tip: Draw three layers – Clients on top, Hive services (Driver, Compiler, Metastore) in the middle, Hadoop (MapReduce + HDFS) at the bottom.
-
Prerequisites: Java and a working Hadoop installation.
Installation steps:
- 1. Download and extract the Hive tarball
- 2. Set the environment variables:
export HIVE_HOME=/usr/local/hive export PATH=$PATH:$HIVE_HOME/bin- 3. Create the warehouse directories in HDFS:
hadoop fs -mkdir /tmp hadoop fs -mkdir -p /user/hive/warehouse hadoop fs -chmod g+w /tmp /user/hive/warehouse- 4. Configure
hive-site.xml(in$HIVE_HOME/conf) - 5. Initialise the metastore schema:
schematool -dbType derby -initSchema - 6. Start Hive: type
hive(orbeeline)
Configuration file –
hive-site.xml:<configuration> <property> <name>hive.metastore.warehouse.dir</name> <value>/user/hive/warehouse</value> </property> <property> <name>javax.jdo.option.ConnectionURL</name> <value>jdbc:mysql://localhost/metastore</value> </property> <property> <name>javax.jdo.option.ConnectionDriverName</name> <value>com.mysql.jdbc.Driver</value> </property> </configuration>Default values are in
hive-default.xml. A property can also be set for one session:hive> SET hive.exec.reducers.max=10;Order of priority of settings:
SETcommand in the session →-hiveconfoption on the command line →hive-site.xml→hive-default.xml.Metastore = metastore service + database that stores the metadata. It has three modes:
1. Embedded metastore (default)
- Metastore service runs in the same JVM as Hive, with an embedded Derby database on local disk
- Only one user/session at a time – good only for testing
2. Local metastore
- Service still runs in the Hive JVM, but connects to a separate database (MySQL, PostgreSQL)
- Many users can work at the same time
3. Remote metastore
- Metastore service runs in its own separate JVM / server; clients connect to it through Thrift (
hive.metastore.uris) - Better security and manageability – clients do not need database credentials; used in production
Mode Metastore service Database Users Embedded In Hive JVM Derby (embedded) One Local In Hive JVM MySQL (separate) Many Remote Separate JVM MySQL (separate) Many, secure
-
Hive can be accessed through several clients. Remote clients connect to HiveServer2, a service that lets many clients send queries using Thrift.
1. Hive CLI (
hive)- The original command-line shell; talks directly to the driver
- Modes: interactive (
hive>), single query (hive -e "query"), script file (hive -f script.hql)
2. Beeline
- The newer command-line client that connects to HiveServer2 through JDBC
beeline -u jdbc:hive2://localhost:10000 -n username3. Web interface (HWI / Hue)
- Browser-based interface to run queries and browse tables
4. Thrift client
- Hive server is exposed as a Thrift service, so programs in C++, Python, PHP, Ruby can talk to it
5. JDBC driver
- For Java applications; class
org.apache.hive.jdbc.HiveDriver, URL of the formjdbc:hive2://host:port/dbname
6. ODBC driver
- For tools that support ODBC, such as Excel, Tableau, Power BI
Java program using JDBC:
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class HiveJdbcClient { private static String driverName = "org.apache.hive.jdbc.HiveDriver"; public static void main(String[] args) throws Exception { Class.forName(driverName); // 1. load the driver Connection con = DriverManager.getConnection( // 2. connect to HiveServer2 "jdbc:hive2://localhost:10000/default", "hive", ""); Statement stmt = con.createStatement(); // 3. create a statement stmt.execute("CREATE TABLE IF NOT EXISTS student " + "(id INT, name STRING, marks INT) " + "ROW FORMAT DELIMITED FIELDS TERMINATED BY ','"); ResultSet rs = stmt.executeQuery( // 4. run a query "SELECT name, marks FROM student WHERE marks > 75"); while (rs.next()) { // 5. read the result System.out.println(rs.getString(1) + "\t" + rs.getInt(2)); } rs.close(); stmt.close(); con.close(); // 6. close } }Steps: Load driver → Get connection → Create statement → Execute query → Process ResultSet → Close.
Client Connects through Used by Hive CLI Direct to driver Developers Beeline JDBC to HiveServer2 Developers, admins JDBC HiveServer2 Java applications ODBC HiveServer2 BI tools Thrift Thrift server Python, C++, PHP programs Web UI HTTP Analysts Default ports: HiveServer2 = 10000, Metastore = 9083.
-
Hive data types are of two kinds: primitive and complex (collection).
Primitive types:
Category Type Description Integer TINYINT1 byte Integer SMALLINT2 bytes Integer INT4 bytes Integer BIGINT8 bytes Decimal FLOAT4-byte single precision Decimal DOUBLE8-byte double precision Decimal DECIMAL(p,s)Exact numbers (money) Boolean BOOLEANtrue / false String STRINGVariable length, no limit String VARCHAR(n)Variable length with a maximum String CHAR(n)Fixed length Date/Time TIMESTAMPDate and time with nanoseconds Date/Time DATEYear, month, day Binary BINARYArray of bytes Complex types:
1. ARRAY – an ordered list of elements of the same type; accessed by index starting at 0
ARRAY<STRING>→subjects[0]2. MAP – a set of key–value pairs; accessed by key
MAP<STRING, INT>→marks['BDA']3. STRUCT – a record with named fields that can be of different types; accessed by dot
STRUCT<city:STRING, pin:INT>→address.city4. UNIONTYPE – a value that can be any one of several types
Example table using all of them:
CREATE TABLE student ( id INT, name STRING, cgpa DOUBLE, subjects ARRAY<STRING>, marks MAP<STRING, INT>, address STRUCT<city:STRING, pin:INT> ) ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' COLLECTION ITEMS TERMINATED BY '|' MAP KEYS TERMINATED BY ':' STORED AS TEXTFILE;One line of the data file:
101,Ravi,8.6,BDA|ML|CC,BDA:90|ML:85,Jaipur|302001Query:
SELECT name, subjects[0], marks['BDA'], address.city FROM student; -- Ravi BDA 90 JaipurType conversion:
- Implicit: a smaller type is converted to a larger one automatically (TINYINT → INT → BIGINT → DOUBLE)
- Explicit: use
CAST('100' AS INT); if the cast fails, the result isNULL
Mnemonic for complex types: A-M-S-U → Array, Map, Struct, Union.
-
Database commands (DDL):
CREATE DATABASE IF NOT EXISTS college COMMENT 'College data' LOCATION '/user/hive/warehouse/college.db'; SHOW DATABASES; USE college; DESCRIBE DATABASE college; ALTER DATABASE college SET DBPROPERTIES ('owner' = 'ycotes'); DROP DATABASE IF EXISTS college CASCADE; -- CASCADE drops its tables tooA database is simply a directory in HDFS:
/user/hive/warehouse/college.db.Table commands:
CREATE TABLE IF NOT EXISTS student ( id INT, name STRING, branch STRING, marks INT ) COMMENT 'Student details' ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' STORED AS TEXTFILE; SHOW TABLES; DESCRIBE FORMATTED student; ALTER TABLE student RENAME TO students; ALTER TABLE students ADD COLUMNS (email STRING); ALTER TABLE students CHANGE marks total_marks INT; TRUNCATE TABLE students; DROP TABLE IF EXISTS students;Two types of tables:
1. Managed (internal) table – default
- Hive owns both the data and the metadata
- Data is moved into the warehouse directory
/user/hive/warehouse/student DROP TABLEdeletes the metadata and the data
2. External table
- Hive manages only the metadata; the data stays at the location you give
DROP TABLEdeletes only the metadata – the data files remain safe
CREATE EXTERNAL TABLE student_ext ( id INT, name STRING, marks INT ) ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' LOCATION '/data/college/students';Point Managed table External table Keyword CREATE TABLECREATE EXTERNAL TABLEData location Warehouse directory Any HDFS path ( LOCATION)Hive controls Data + metadata Metadata only On DROP Data deleted Data kept Use when Only Hive uses the data Data is shared with Pig, MapReduce, Spark Other ways to create a table:
CREATE TABLE s2 LIKE student; -- copy schema only CREATE TABLE toppers AS SELECT id, name FROM student WHERE marks > 75; -- CTASExam tip: "Drop of managed table = data lost; drop of external table = data safe" is the most asked difference.
-
Both techniques divide a table into smaller parts so that queries scan less data.
Partitioning
- Divides a table into parts based on the value of a partition column (date, country, branch)
- Each partition is a separate sub-directory in HDFS
- The partition column is not stored in the data file; it comes from the directory name
- A query with a filter on the partition column reads only that directory – called partition pruning
CREATE TABLE student_part (id INT, name STRING, marks INT) PARTITIONED BY (branch STRING) ROW FORMAT DELIMITED FIELDS TERMINATED BY ',';Directory structure:
/user/hive/warehouse/student_part/branch=CSE/000000_0 /user/hive/warehouse/student_part/branch=AID/000000_0 /user/hive/warehouse/student_part/branch=ECE/000000_0Static partitioning – we give the partition value ourselves:
LOAD DATA LOCAL INPATH 'cse.txt' INTO TABLE student_part PARTITION (branch = 'CSE');Dynamic partitioning – Hive creates partitions from the data:
SET hive.exec.dynamic.partition = true; SET hive.exec.dynamic.partition.mode = nonstrict; INSERT OVERWRITE TABLE student_part PARTITION (branch) SELECT id, name, marks, branch FROM student;Managing partitions:
SHOW PARTITIONS student_part;andALTER TABLE student_part ADD PARTITION (branch = 'ME');Bucketing
- Divides data into a fixed number of files (buckets) using a hash of a column
- Bucket number =
hash(column) mod number_of_buckets - Each bucket is a file inside the table or partition directory
- Useful for columns with many distinct values (id), where partitioning would create too many directories
CREATE TABLE student_bucket (id INT, name STRING, marks INT) CLUSTERED BY (id) SORTED BY (id ASC) INTO 4 BUCKETS; SET hive.enforce.bucketing = true; INSERT OVERWRITE TABLE student_bucket SELECT id, name, marks FROM student;Benefits of bucketing: efficient sampling (
TABLESAMPLE(BUCKET 1 OUT OF 4 ON id)) and faster map-side joins.Point Partitioning Bucketing Keyword PARTITIONED BYCLUSTERED BY ... INTO n BUCKETSCreated as Directory File Based on Column value Hash of column Number Depends on distinct values Fixed Column stored in file? No (it is a virtual column) Yes Good for Low-cardinality columns High-cardinality columns Benefit Partition pruning Sampling, joins Exam tip: Both can be used together – partition by branch, then bucket by id inside each partition.
-
Hive DML is used to load, insert and export data. Because Hive works on HDFS files (write once), DML is mostly bulk oriented.
1. LOAD DATA – put files into a table
LOAD DATA LOCAL INPATH '/home/user/student.txt' OVERWRITE INTO TABLE student; LOAD DATA INPATH '/data/student.txt' INTO TABLE student;LOCAL→ the file is on the local file system and is copied to the table directory- Without
LOCAL→ the file is already in HDFS and is moved (not copied) OVERWRITE→ existing data in the table is deleted first; without it the file is added- No transformation or checking is done – it is a pure file copy/move, so it is very fast (schema-on-read)
2. INSERT ... SELECT – load from a query
INSERT OVERWRITE TABLE toppers SELECT id, name, marks FROM student WHERE marks >= 75; INSERT INTO TABLE toppers SELECT id, name, marks FROM student WHERE marks BETWEEN 60 AND 74;INSERT OVERWRITEreplaces the data;INSERT INTOappends to it
3. Multi-table insert – scan the source only once
FROM student INSERT OVERWRITE TABLE pass SELECT id, name WHERE marks >= 40 INSERT OVERWRITE TABLE fail SELECT id, name WHERE marks < 40;4. INSERT ... VALUES – small inserts (Hive 0.14 onwards)
INSERT INTO TABLE student VALUES (101, 'Ravi', 'AID', 88), (102, 'Sita', 'CSE', 91);5. Export data to a directory
INSERT OVERWRITE LOCAL DIRECTORY '/tmp/result' ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' SELECT id, name FROM student;6. UPDATE and DELETE
UPDATE student SET marks = 95 WHERE id = 101; DELETE FROM student WHERE marks < 40;Allowed only on transactional (ACID) tables: stored as ORC, bucketed, with
TBLPROPERTIES ('transactional' = 'true').Statement Work LOAD DATACopy or move a file into a table INSERT OVERWRITEReplace table data with query result INSERT INTOAppend query result INSERT OVERWRITE DIRECTORYExport query result to files UPDATE/DELETERow-level change (ACID tables only) DDL vs DML: DDL (CREATE, ALTER, DROP) changes the metastore; DML changes the data files in HDFS.
Exam tip: Remember the pair – LOCAL = copy, no LOCAL = move; OVERWRITE = replace, INTO = append.
-
General form of a query:
SELECT [DISTINCT] columns FROM table [WHERE condition] [GROUP BY columns] [HAVING condition] [ORDER BY columns | SORT BY columns | DISTRIBUTE BY columns | CLUSTER BY columns] [LIMIT n];1. Selection and filtering
SELECT name, marks FROM student WHERE branch = 'AID' AND marks > 60 LIMIT 10;2. Aggregation with GROUP BY and HAVING
SELECT branch, COUNT(id) AS total, AVG(marks) AS avg_marks, MAX(marks) AS top FROM student GROUP BY branch HAVING AVG(marks) > 60;Aggregate functions:
COUNT,SUM,AVG,MIN,MAX.3. Joins (only equi-joins)
SELECT s.name, d.dept_name FROM student s JOIN department d ON (s.branch = d.dept_id); SELECT s.name, f.amount FROM student s LEFT OUTER JOIN fees f ON (s.id = f.sid);Types:
JOIN(inner),LEFT OUTER,RIGHT OUTER,FULL OUTER,LEFT SEMI JOIN. Keep the largest table last in the join for better performance. A small table can be joined in memory using a map-side join.4. Sorting – four clauses
Clause Meaning Reducers ORDER BYTotal ordering of the full result Only one (slow for big data) SORT BYSorts rows within each reducer (partial order) Many DISTRIBUTE BYSends rows with the same column value to the same reducer (no sorting) Many CLUSTER BYDISTRIBUTE BY+SORT BYon the same columnMany SELECT name, marks FROM student ORDER BY marks DESC; SELECT branch, name, marks FROM student DISTRIBUTE BY branch SORT BY marks DESC;5. Sub-queries and views
SELECT t.branch, t.avg_marks FROM (SELECT branch, AVG(marks) AS avg_marks FROM student GROUP BY branch) t WHERE t.avg_marks > 70; CREATE VIEW toppers_view AS SELECT id, name FROM student WHERE marks > 85;A view is a saved query (a virtual table) – it stores no data.
6. Built-in functions
- String:
UPPER,LOWER,CONCAT,SUBSTR,LENGTH,TRIM - Math:
ROUND,FLOOR,CEIL,SQRT - Date:
YEAR,MONTH,DATEDIFF,CURRENT_DATE - Conditional:
IF,CASE WHEN,COALESCE - Table-generating:
EXPLODE(turns an array into rows)
7. Seeing the plan:
EXPLAIN SELECT ...;shows the stages (map and reduce operators) of the query.How a query maps to MapReduce:
WHEREand column selection → done in the map phaseGROUP BYandJOINkeys → become the shuffle key- Aggregation → done in the reduce phase
- A simple
SELECTwithLIMITneeds no MapReduce job (fetch task)
Exam tip: ORDER BY vs SORT BY is a favourite short question – "ORDER BY = one reducer, global sort; SORT BY = per-reducer sort".
- String:
-
All three process data stored in HDFS. Pig and Hive are abstractions over MapReduce – their scripts and queries are converted into MapReduce jobs.
Point MapReduce Pig Hive Developed by Google / Apache Yahoo! Facebook Language Java Pig Latin HiveQL (SQL-like) Type of language Low-level programming Procedural data-flow Declarative Abstraction level Low High High Lines of code Many Few Fewest Schema None Optional Mandatory (in metastore) Data types supported Any Structured, semi and unstructured Mostly structured Metadata store No No Yes – Metastore Works on Client and cluster Client side Server side (HiveServer) Partitioning Custom partitioner Not built-in Built-in JDBC / ODBC No No Yes Main users Programmers Programmers, researchers Data analysts Best use Complex custom logic ETL, data pipelines Reports, ad-hoc analysis When to use what:
- MapReduce – when you need full control, custom data formats, or complex algorithms that are hard to express in scripts
- Pig – when you are building a data pipeline (ETL): cleaning, transforming and joining raw, messy data step by step
- Hive – when the data is structured and you want SQL-style reports and analysis, or want to connect BI tools
A typical real-world pipeline:
Raw logs in HDFS --(Pig: clean and transform)--> structured data --(Hive: tables and queries)--> reports and dashboardsSame problem in all three – count students per branch:
Pig:
A = LOAD 'student.txt' USING PigStorage(',') AS (id:int, name:chararray, branch:chararray); B = GROUP A BY branch; C = FOREACH B GENERATE group, COUNT(A); DUMP C;Hive:
SELECT branch, COUNT(id) FROM student GROUP BY branch;MapReduce: Mapper emits
(branch, 1), Reducer adds the values – about 60 lines of Java.Mnemonic: MapReduce = Manual, Pig = Pipeline, Hive = Hello SQL.
-
What is Writable?
Hadoop's serialization interface with two methods –
write(DataOutput)andreadFields(DataInput).What are wrapper classes?
Writable classes that wrap Java primitives, e.g.
IntWritablefor int,LongWritablefor long,BooleanWritablefor boolean.ObjectWritable vs GenericWritable?
ObjectWritable wraps any type but writes the full class name each time; GenericWritable stores only a one-byte index into a fixed list of types, so it is compact.
What is NullWritable?
A singleton Writable of zero length, used as a placeholder for an unwanted key or value.
What is a Raw Comparator?
A comparator that compares two keys directly from their serialized bytes without creating objects, making sorting faster.
Define Pig Latin.
The high-level data-flow scripting language of Apache Pig whose statements are converted into MapReduce jobs.
Write two simple Pig Latin commands.
A = LOAD 'student.txt' USING PigStorage(',') AS (id:int, name:chararray); DUMP A;What are the ABCs of Pig Latin?
Its basics: statements made of operators, relations (bags of tuples), data types (int, chararray, tuple, bag, map) and the syntax rules.
What are Pig script interfaces?
Ways to run Pig: Grunt shell (interactive), script file (batch) and embedded in Java (PigServer).
Local vs MapReduce mode of Pig?
Local: single JVM with the local file system. MapReduce: runs on the Hadoop cluster with HDFS.
Define HiveQL.
Hive Query Language – the SQL-like language of Hive used to define tables and query data stored in HDFS.
Two advantages of Hive?
SQL-like queries, so no Java needed; handles very large data with partitioning and bucketing.
Meaning of Hive clients?
Interfaces through which users reach Hive: CLI, Beeline, Web UI, JDBC, ODBC and Thrift clients.
What is Hive Data Manipulation Language?
Statements that load and modify data:
LOAD DATA,INSERT INTO / OVERWRITE,UPDATE,DELETE.What is the Metastore?
The central repository (an RDBMS such as Derby or MySQL) that stores Hive's table schemas, partitions and data locations.
Managed vs external table?
Dropping a managed table deletes data and metadata; dropping an external table deletes only metadata.
No card matches that search.
1/62
0
0:00
Question
Click the card or press Space to flip
Answer
Diagram for this card
Diagram
Handwritten diagram
Run complete
0 nailed · 0 in the pile · 0:00 · best combo 0
Scroll to zoom · drag to pan · Esc to close
Shortcuts
- S
- Start the run
- Space
- Show me the answer
- ← →
- Previous / next card
- 1 2
- Not yet / Nailed it
- D
- Open the diagram
- F
- Diagram full screen
- /
- Search the deck
- Esc
- Close whatever is open