Introduction to
Big Data Analytics
Comprehensive coverage of Big Data fundamentals, Hadoop ecosystem, NoSQL databases, Cassandra, MongoDB, Hive, Pig, Spark, and stream processing.
Data = raw facts & figures collected from various sources to be analyzed for insights. Computer data may be text, images, audio, software programs.
Structured
Highly organized, stored in rows/columns (tables). Fixed schema. Queried with SQL. Stored in RDBMS (MySQL, Oracle).
Semi-Structured
No rigid schema but uses tags/markers (JSON, XML). Self-describing with metadata. Stored in NoSQL or formats like JSON/XML.
Unstructured
No predefined format. Text docs, images, videos, social media posts. Requires NLP/ML to analyze. Stored in data lakes.
Structured: Employee tables, spreadsheets, GPS data | Semi-structured: Email, JSON API responses, XML config, website logs | Unstructured: Social media posts, PDFs, voice recordings, photos/videos
Big Data is a massive, continuously growing collection of data so huge and complex that no typical data management technology can effectively store or process it. Data in Petabytes (10¹⁵ bytes) qualifies. ~90% of today's data was generated in the last 3 years.
Sources: Social media posts/photos/videos, GPS signals, emails/blogs, software logs, weather stations, digital pictures/videos.
Volume
Amount of data (Terabytes → Petabytes). IoT causing exponential growth.
Variety
Different formats: structured, semi-structured, unstructured. Text, audio, video.
Velocity
Speed of data generation & processing. Social media major contributor. Real-time streaming.
Veracity
Uncertainty / trustworthiness of data. Incompleteness, inconsistency from high volume.
Value
Turning big data into revenue. The end goal after addressing all other V's.
Visualization
Displaying in charts, graphs, maps for easy understanding of trends and patterns.
Virality
How quickly information spreads P2P. Rate of spread across networks.
Storage
Vast daily data in different formats. Legacy systems can't store unstructured data.
Processing
Reading, transforming, extracting useful info from raw data in unified formats.
Security
Non-encrypted data at risk. Must balance access vs. strict security protocols.
Data Quality
Poor quality issues: correct original source, use highly accurate identity methods.
Visualization
Elements too close together, data reduction causes loss, rapidly shifting visuals.
Cloud Governance
Managing regulations, performance, governance/control, and expenses in cloud.
Real-Time Insights
Performing analyses as system collects data. Requires logic & math for speed.
Healthcare
EHRs, genomic data, wearables. Barriers: cost, compilation, security, communication gaps.
Effective scaling methods: Database sharding, memory caching, moving to cloud, and separating read-only and write-active databases. Combine all for next-level scaling.
Trending Technologies: Hadoop Ecosystem, Apache Spark, NoSQL Databases, R Software, Predictive Analytics, Prescriptive Analytics.
Collection of technologies, frameworks, and tools used to handle, process, analyze, and derive insights from large datasets.
| Layer | Purpose | Key Tools |
|---|---|---|
| Data Storage | Store massive volumes of data | HDFS, MongoDB, Cassandra, Amazon Redshift, Google BigQuery |
| Data Processing | Process large datasets | Apache Hadoop, Apache Spark, Apache Flink, Kafka, NiFi, AWS Kinesis |
| ETL (Integration) | Extract, Transform, Load from sources | Apache NiFi, Talend, Informatica, AWS Kinesis |
| Data Querying | Query & analyze large datasets | Apache Hive, Presto, Impala, Tableau, Power BI |
| ML & AI | Learn from data & predict | TensorFlow, PyTorch, scikit-learn, Keras, DataRobot |
| Governance & Security | Secure, govern, and comply | Apache Ranger, Apache Sentry, AWS IAM, Apache Atlas |
Big Data 1.0
Focus: Batch processing, scalable storage.
Tech: Hadoop, HDFS, MapReduce.
Key: Offline analysis of large volumes.
Big Data 2.0
Focus: Real-time processing, advanced analytics.
Tech: Apache Spark, Storm, HBase.
Key: Dynamic, diverse data sources.
Big Data 3.0
Focus: AI/ML, actionable insights.
Tech: TensorFlow, PyTorch, data lakes.
Key: Predictive & real-time analytics.
Business Intelligence
- Answers known business questions
- Central server / Data Warehouse
- Structured data in RDBMS
- Carries data to processing functions
- Processes historical data sets only
Big Data
- Finds unknown questions AND answers
- Distributed file system (HDFS)
- Both structured & unstructured
- Takes processing to data (MapReduce)
- Processes historical + real-time sources
NoSQL = "Not Only SQL". High-performance agile processing of large-scale information. Inherently unstructured, distributed architecture, horizontal scaling.
Key-Value Stores
Simplest form. Data in key/value pairs. Unique key for each element. Values can be strings, JSON, XML, Blob.
Examples: DynamoDB, Riak, Redis
Document Oriented
Documents as key-value pairs. Stored as XML/JSON/BSON. Each document has unique object ID. Flexible schema.
Examples: MongoDB, CouchDB, OrientDB
Column-Oriented
Based on Google BigTable. Each column treated separately. High performance on SUM, COUNT, AVG, MIN queries.
Examples: HBase, Cassandra, Hypertable
Graph Oriented
Stores relationship between data. Nodes linked with edges. Facebook-like relationship tracking.
Examples: Neo4J, FlockDB, OrientDB
Schema Agnostic – no upfront schema design. Horizontal Scaling – add cheap commodity servers. High Availability – masterless architecture. Performance – distributed processing at scale.
| Feature | RDBMS | NoSQL | NewSQL |
|---|---|---|---|
| Schema | Fixed schema | Schema-free | Both fixed & free |
| Consistency | ACID properties | Eventual consistency | ACID properties |
| Scalability | Vertical (scale-up) | Horizontal | Horizontal |
| Transactions | Complex + joins | Simple only | Fully supported OLTP |
| Data velocity | Low velocity | High velocity | High velocity |
| Structure | Centralized | Decentralized | Distributed |
| Examples | MySQL, PostgreSQL | DynamoDB, MongoDB | VoltDB, CockroachDB |
Advantages
- Combines SQL + NoSQL benefits
- ACID transaction consistency
- Easy migration
- Familiar to developers
Disadvantages
- Fewer features than traditional SQL
- In-memory issues with huge volumes
- Fewer skilled professionals
- Lack of admin tools
In-Memory Analytics
All relevant data stored in RAM, eliminating hard disk access. Faster access, rapid deployment, better insights.
In-Database Processing
Fuses data warehouses with analytical systems. DB itself runs computations, eliminating export need.
SMP (Symmetric Multi-Processing)
Single common main memory shared by 2+ identical processors. Tightly coupled. Each has cache memory on system bus.
MPP (Massively Parallel Processing)
Processors each have own OS + dedicated memory. Work on different parts of same program. Communicate via messaging interface.
Shared Nothing Architecture
Neither memory nor disk shared among processors. vs Shared Memory (common memory) vs Shared Disk (common disks, private memory).
Open-source framework for storing and processing large datasets (GBs to PBs) on clusters of commodity hardware. Developed at Apache Software Foundation. In 2008, defeated supercomputers for sorting terabytes.
Data Locality Concept: Computational logic is sent to cluster nodes containing data, not the other way around.
- Default block size: 128 MB (from Hadoop 2+)
- Fault-tolerant via data replication (default 3 replicas)
- Master-slave architecture
- Files stored across multiple machines redundantly
- Enables parallel processing
NameNode (Master)
Manages filesystem namespace. Stores metadata. Tracks which files → which blocks → which DataNodes.
DataNode (Slave)
Stores actual data blocks. Manages state of HDFS node. Interacts with blocks. Reports to NameNode.
Secondary NameNode
Periodically reads file system metadata from NameNode RAM → writes to disk. Combines EditLogs + FsImage. Also called CheckpointNode.
Core processing component providing the logic of processing. Uses divide-and-conquer on cluster nodes.
Map Phase
- Filtering, grouping, sorting
- Converts data into key-value pairs (intermediate keys)
- Each mapper processes its data slice independently
Reduce Phase
- Aggregates and summarizes Map output
- Shuffle & Sort → groups equivalent keys
- Combiner (optional): local reducer to pre-aggregate
JobTracker (on NameNode) = master, coordinates full execution | TaskTrackers (on DataNodes) = slaves, execute individual tasks | TaskTracker sends heartbeat + progress to JobTracker.
-- Word Count Example --
Input:
"Welcome to Hadoop Class"
"Hadoop is good"
"Hadoop is bad"
Map Output (key-value pairs):
(Welcome,1), (to,1), (Hadoop,1), (Class,1)
(Hadoop,1), (is,1), (good,1)
(Hadoop,1), (is,1), (bad,1)
Shuffle & Sort → Group by key
Reduce Output:
bad → 1 | Class → 1 | good → 1
Hadoop → 3 | is → 2 | to → 1 | Welcome → 1
Introduced in Hadoop 2.x. Separates resource management from processing layer. Allows multiple data processing engines (Spark, Flink, etc.) to run on same cluster.
ResourceManager
Global resource allocator. Contains: Applications Manager (accepts job submissions) + Scheduler (allocates CPU, disk, network).
NodeManager
Runs on each node. Manages resources (CPU, memory, bandwidth) on single node. Reports to ResourceManager.
ApplicationMaster
Framework-specific library. Negotiates resources from RM. Works with NM to execute & monitor containers. One per job.
Client submits application
RM allocates container to start ApplicationMaster
AM registers with ResourceManager
AM negotiates containers from RM
AM notifies NodeManager to launch containers
Application code executes in container
AM un-registers with RM when complete
| Feature | Hadoop 1.x | Hadoop 2.x | Hadoop 3.0 |
|---|---|---|---|
| Resource Mgmt | Single JobTracker | YARN (RM + AppMaster) | YARN + optimizations |
| Scalability | Single JobTracker bottleneck | Flexible with YARN | Ongoing improvements |
| Processing | MapReduce only | MapReduce + others (Spark, Tez) | All engines + optimizations |
| High Availability | Single point of failure | HA for NameNode | Enhanced HA |
| Fault Tolerance | HDFS replication only | HA configs for RM + NN | Further improvements |
| Storage | Basic replication | HDFS Federation | Erasure Coding (storage efficient) |
| Java Support | Java 6 & 7 | Java 7 | Full Java 8 support |
| Containers | Limited | Docker containers with YARN | Docker + Kubernetes |
Erasure Coding – storage efficient alternative to replication | GPU Support – offload computations | Native Azure + Aliyun Storage | Improved Shell Scripting – no Java wrappers needed
| Component | Type | Purpose |
|---|---|---|
| HDFS | Storage | Distributed file system, backbone of Hadoop |
| YARN | Resource Mgmt | Resource allocation and job scheduling |
| MapReduce | Processing | Distributed batch data processing |
| Apache Spark | Processing | In-memory real-time processing (100x faster than MR) |
| Apache Pig | Scripting | High-level Pig Latin scripting for MapReduce |
| Apache Hive | Querying | SQL-like HQL queries on HDFS data (data warehousing) |
| HBase | NoSQL DB | Distributed NoSQL DB built on HDFS (real-time R/W) |
| ZooKeeper | Coordination | Distributed cluster coordination and synchronization |
| Oozie | Scheduling | Workflow/job scheduler |
| Kafka | Streaming | Distributed event streaming platform |
| Mahout | ML | Scalable machine learning algorithms on Hadoop |
| Sqoop | ETL | Bulk data transfer between Hadoop and RDBMS |
| Flume | Ingestion | Collect/aggregate/move large amounts of log data |
Platform built on Hadoop for analyzing large datasets. Developed by Yahoo (2006). Uses Pig Latin (SQL-like procedural language). Pig Engine converts scripts into MapReduce jobs.
200 lines of Java = 10 lines of Pig Latin (16x less code). SQL-like learning curve. Built-in operators: JOIN, FILTER, SORT, GROUP. Nested data types (tuples, bags, maps).
Pig Data Model: Atom (single value/field) → Tuple (ordered fields, like a row) → Bag (unordered set of tuples, like a table) → Map (key-value pairs) → Relation (bag of tuples)
Data warehouse tool on top of Hadoop. Developed at Facebook → Apache. Uses HiveQL (HQL) which converts to MapReduce jobs internally. Stores schema in MetaStore, data in HDFS.
Open-source distributed NoSQL database built on HDFS. Modeled after Google's BigTable. Provides real-time random read/write to large datasets. Column-oriented storage. Written in Java.
HMaster
Coordinates cluster. Handles region assignment, load balancing, failover, schema changes.
RegionServers
Host regions (data partitions). Handle read/write requests from clients.
ZooKeeper
Cluster coordination, leader election, synchronization for HBase.
Distributed coordination service for managing large sets of hosts. Services: Naming Service, Configuration Management, Cluster Management, Leader Election, Locking & Synchronization, Highly Reliable Data Registry.
Architecture: Client → Server → Ensemble (min 3 nodes) → Leader (auto-elected) → Follower. ZooKeeper Data Model: znode tree structure with path separators (/).
Lightning-fast cluster computing. Built on top of Hadoop MapReduce. 100x faster than Hadoop for in-memory computations. Written in Scala. Supports Python, Java, Scala, R, SQL APIs.
Spark Core
Base execution engine. Task scheduling, memory management, fault recovery.
Spark SQL
SQL queries on structured data. SchemaRDD abstraction.
Spark Streaming
Live data stream processing using mini-batches + RDD transformations.
MLlib
Distributed ML library. 9x faster than Hadoop-based Mahout.
GraphX
Distributed graph processing. Pregel abstraction API.
RDD (Resilient Distributed Dataset): Fault tolerant, Distributed, Dataset (partitioned collection). Immutable. Lazy evaluation. Two operations: Transformations (create new RDD) and Actions (pass results to driver).
Free, open-source, distributed wide-column store NoSQL database. Designed for large data across commodity servers with high availability and no single point of failure. Written in Java. Developed by Apache (originally at Facebook for Inbox Search, 2008).
Origin: Blend of Google BigTable (data model + storage) + Amazon Dynamo (distribution features). Facebook open-sourced in 2008 → Apache Incubator 2009 → Top-level Apache project 2010.
Easy Data Distribution
Peer-to-peer architecture. No master-slave issues. Flexible data distribution.
Elastic Scalability
Horizontal scaling. Zero downtime. Read/write throughput increases during scaling.
High Availability
Auto-replication to multiple nodes. Failed nodes replaced with no downtime.
Tunable Consistency
Configure required consistency level. Client approved as soon as cluster accepts write.
Efficient Writes
Blazing fast writes on cheap commodity hardware. Hundreds of terabytes without sacrificing read efficiency.
Flexible Data Storage
All formats: structured, semi-structured, unstructured. Dynamic accommodation of structure changes.
Eric Brewer (2000): A distributed system can only guarantee 2 of 3 properties simultaneously:
Consistency (C)
All nodes return same data. Read returns most recent write. Every node has same copy of replicated data.
Availability (A)
Every request gets a response. System remains 100% operational. Every node responds in reasonable time.
Partition Tolerance (P)
System continues despite partial network failure. Sustains any amount of network failure without total failure.
| Trade-off | Description | Examples |
|---|---|---|
| CA | Always responds with consistent data; no partition tolerance | MySQL, PostgreSQL |
| AP | Distributed, processes requests even in network partition | Amazon DynamoDB, Google Cloud Spanner |
| CP | Distributed, drops requests instead of returning inconsistent data | Apache HBase, MongoDB, Redis |
Cassandra follows AP (Availability + Partition Tolerance) with BASE consistency (Basically Available Soft State Eventual Consistency).
Cluster
Outermost container. Nodes arranged in ring format. Every node contains a replica for failure handling.
Gossip Protocol
Peer-to-peer intra-ring communication. Nodes share status info with neighbors (3-way handshake). Enables failure detection.
Partitioner
Hash function. Distributes data across nodes. Computes token for partition key. Identifies rows uniquely.
Replication Strategies
SimpleStrategy: single datacenter only. NetworkTopologyStrategy: multiple datacenters (recommended).
Commit Log
Crash-recovery mechanism. Every write is first written here. Write = successful only if in commit log.
Mem-table
Memory-resident data structure. Data written after commit log. Multiple mem-tables per column family.
SSTable
Stored String Table. Disk file. Data flushed from Mem-table when threshold reached. Immutable once written.
Bloom Filter
Probabilistic structure. Tests if partition key is in SSTable (avoids expensive IO). Per-SSTable in memory.
Client initiates write request
Written to Commit Log (write considered successful here)
Pushed to Mem-table (memory)
When Mem-table threshold reached → flushed to SSTable on disk (non-blocking)
| Level | Write Requirement | Read Requirement |
|---|---|---|
| ONE | At least 1 replica commit log + Memtable | Response from closest replica |
| QUORUM | Quorum of replicas | Result from quorum with latest timestamp |
| LOCAL_QUORUM | Quorum in same datacenter as coordinator | Quorum in same datacenter (reduces latency) |
| EACH_QUORUM | Quorum in all datacenters | Quorum in all datacenters |
| ALL | All replica nodes (highest consistency) | All replicas must respond (lowest availability) |
-- Create Keyspace (namespace for tables) -- CREATE KEYSPACE Employees WITH REPLICATION = { 'class': 'SimpleStrategy', 'replication_factor': 3 }; -- Use Keyspace -- USE Employees; -- Create Table -- CREATE TABLE example_table ( id UUID PRIMARY KEY, name TEXT, age INT, tags LIST<TEXT>, categories SET<TEXT>, attributes MAP<TEXT, TEXT> ); -- Insert (BATCH for multiple) -- BEGIN BATCH INSERT INTO example_table (id, name, age) VALUES (uuid(), 'Alice', 30); INSERT INTO example_table (id, name, age) VALUES (uuid(), 'Bob', 25); APPLY BATCH; -- Read / Update / Delete -- SELECT * FROM example_table WHERE id = some_uuid; UPDATE example_table SET age = 31 WHERE id = some_uuid; DELETE FROM example_table WHERE id = some_uuid; TRUNCATE example_table; -- delete all rows
LIST
Ordered elements. Stored multiple times. Index-based retrieval. For emails, phone numbers.
SET
Unordered group of unique elements. Returns in sorted order when queried.
MAP
Key-value pairs. For attributes, todo items, address maps.
COUNTER
Distributed, atomic, increment-only. For page views, likes, sales tracking.
TTL (Time-To-Live)
Optional expiration in seconds. Auto-deleted after period. For sessions, temporary data.
TRACING
Detailed execution info. Identifies bottlenecks, latency, performance insights.
-- Counter Example -- CREATE TABLE page_views (article_id UUID PRIMARY KEY, views counter); UPDATE page_views SET views = views + 1 WHERE article_id = ?; -- TTL: auto-expire in 30 seconds -- INSERT INTO userlogin (userid, password) VALUES (1, 'pass') USING TTL 30; -- Export / Import CSV -- COPY mykeyspace.mytable TO '/path/output.csv' WITH HEADER = true; COPY mykeyspace.mytable FROM '/path/input.csv' WITH HEADER = true;
Partition Key = responsible for data distribution across nodes (hashed to find node). Clustering Key = responsible for data sorting within a partition. Composite Partition Key = multiple columns as partition key using double brackets.
PRIMARY KEY (a) → partition: a | PRIMARY KEY (a, b) → partition: a, clustering: b | PRIMARY KEY ((a,b), c) → composite partition: (a,b), clustering: c
Open-source document-oriented database. Categorized under NoSQL. Developed by MongoDB.Inc under SSPL license (Feb 2009). Data stored in BSON (Binary JSON) format. Max document size: 16MB. Max nesting depth: 100 levels.
Database (= MySQL database) → Collection (= MySQL table, schema-less) → Document (= row, BSON key-value pairs) → Field (= column)
| MongoDB | RDBMS |
|---|---|
| Non-relational, document-oriented | Relational database |
| Dynamic/flexible schema | Predefined schema |
| Suitable for hierarchical storage | Not suitable for hierarchical |
| CAP theorem (C, A, P) | ACID properties |
| Much faster performance | Slower than MongoDB |
| Schema-less collections | Fixed table structure |
// Database Operations use mydb // create/switch db show dbs // list databases db.dropDatabase() // drop current db db.createCollection("students") // create collection show collections // list collections // CREATE db.records.insertOne({ name: "Alice", age: 25 }); db.records.insertMany([{ name: "Bob" }, { name: "Carol" }]); // READ db.records.find() // all docs db.records.find({ name: "Alice" }) // filter db.records.findOne({ age: 25 }) // first match // UPDATE db.records.updateOne({ name: "Alice" }, { $set: { age: 26 } }); db.records.updateMany({ age: 25 }, { $set: { status: "active" } }); db.records.replaceOne({ name: "Alice" }, { name: "Alice", age: 30 }); // DELETE db.records.deleteOne({ name: "Alice" }); db.records.deleteMany({ age: { $lt: 18 } });
Indexing
Every field indexed with primary/secondary indices. Without index → full collection scan (slow).
Sharding
Horizontal scalability. Large data partitioned into chunks by shard key, distributed across shards.
Replication
Replica sets. Multiple copies on different servers. If primary fails → secondary takes over.
Aggregation
3 methods: Aggregation Pipeline, Map-Reduce Function, Single-Purpose Aggregation. Like SQL GROUP BY.
Data warehousing tool. Processes structured data in Hadoop. Uses HDFS for storage, MapReduce for execution, RDBMS for metadata. Developed at Facebook → Apache Hive.
Hive CLI / Web UI
Interface to execute queries. CLI = command line. Web UI = graphical browser interface.
Driver
Receives queries, transfers to compiler. Controls lifecycle: compilation → optimization → execution.
Compiler
Parses HQL, performs semantic analysis. Converts HiveQL to MapReduce DAG of tasks.
MetaStore
Central repo for table definitions, schemas, partition info, HDFS mappings.
Execution Engine
Executes DAG of MapReduce + HDFS tasks in dependency order.
JDBC/ODBC
Java/app connectivity drivers. Thrift server for cross-language requests.
Embedded: Unit tests only. Single connection. Apache Derby DB. Both DB + metastore in main Hive Server process.
Local: MySQL-based. Multiple connections. Metastore in main Hive process, DB in separate process/host.
Remote: Hive driver + metastore on different JVMs. DB completely isolated from Hive users.
Tables
Managed/Internal: Hive controls data. DROP → data deleted from HDFS.
External: Data stays in HDFS. DROP → only metadata removed, data intact.
Partitions
Subdivisions based on column values (e.g., year, month). Each partition = HDFS subdirectory. Improves query performance.
Buckets (Clusters)
Hash-based data segregation. Provides better sampling + efficient joins. CLUSTERED BY (col) INTO N BUCKETS.
| Format | Type | Best For |
|---|---|---|
| TextFile | Row-based (default) | Simple, human-readable. CSV/TXT. Each row = one line of text. |
| SequenceFile | Binary key-value pairs | Compressed binary. Supports: Uncompressed, Record compressed, Block compressed. |
| RCFile | Column-oriented (row groups) | Read specific columns fast. Columns compressed separately. Saves space. |
-- DDL: Create -- CREATE DATABASE IF NOT EXISTS employee_db; CREATE TABLE IF NOT EXISTS employee ( emp_id INT, emp_name STRING, salary FLOAT ) ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' STORED AS TEXTFILE; -- DDL: Show, Describe, Alter, Drop -- SHOW DATABASES; SHOW TABLES; DESCRIBE employee; ALTER TABLE employee ADD COLUMNS (age INT); ALTER TABLE employee RENAME TO staff; DROP TABLE IF EXISTS employee; TRUNCATE TABLE employee; -- removes rows, keeps structure -- DML: Load, Insert, Select -- LOAD DATA LOCAL INPATH '/home/user/emp.csv' INTO TABLE employee; INSERT INTO TABLE employee VALUES (1, 'John', 50000); SELECT emp_name, salary FROM employee WHERE salary > 40000; -- Export / Import -- EXPORT TABLE employee TO '/user/hive/export/employee'; IMPORT TABLE employee_copy FROM '/user/hive/export/employee';
Static Partitioning
- Partition values specified manually
- Faster execution (Hive knows exact partition)
- Good when loading specific date files
Dynamic Partitioning
- Hive auto-determines partition values from data
- Need to enable: SET hive.exec.dynamic.partition = true
- Good for large diverse datasets
-- Create partitioned table -- CREATE TABLE sales (id INT, amount FLOAT) PARTITIONED BY (year INT, month INT) STORED AS TEXTFILE; -- Static partition load -- LOAD DATA INPATH '/data/sales_2025.txt' INTO TABLE sales PARTITION (year=2025, month=10); -- Dynamic partition insert -- SET hive.exec.dynamic.partition = true; SET hive.exec.dynamic.partition.mode = nonstrict; INSERT INTO TABLE sales PARTITION (year, month) SELECT id, amount, year, month FROM temp_sales;
High-level abstraction from MapReduce. Developed by Yahoo (2006). Pig Engine converts Pig Latin scripts into MapReduce jobs. Two execution environments: local JVM (small data) and Hadoop cluster (distributed).
Parser
Syntax check, type checking. Output: DAG (Direct Acyclic Graph) of logical operators.
Optimizer
Logical optimizations (projection, pushdown) on the DAG.
Compiler
Compiles optimized plan into series of MapReduce jobs.
Execution Engine
Submits MapReduce jobs to Hadoop in sorted dependency order.
| Type | Description | Example |
|---|---|---|
| Atom (Field) | Single value, stored as string, used as string or number | 'Rahul' or 50 |
| Tuple | Ordered set of fields (like a row in RDBMS) | (Rahul, 50) |
| Bag | Unordered set of tuples. Represented by {} | {(Raja, 30), (Ali, 45)} |
| Map | Key-value pairs. Key = chararray (unique). Represented by [] | [name#Raja, age#30] |
| Relation | A bag of tuples. Unordered. | Complete dataset |
Local Mode
- Single JVM, localhost
- Local file system I/O
- For development & prototyping
pig -x local
MapReduce Mode (Default)
- Hadoop cluster
- HDFS I/O
- Semi/fully distributed Hadoop
pigorpig -x mapreduce
-- Load data -- A = LOAD '/pigdemo/student.tsv' AS (rollno:int, name:chararray, gpa:float); -- FILTER: select rows where GPA > 4 -- B = FILTER A BY gpa > 4.0; -- FOREACH: transform each row -- C = FOREACH A GENERATE UPPER(name); -- LIMIT: first 3 rows -- D = LIMIT A 3; -- GROUP: group by field -- G = GROUP A BY rollno; -- DISTINCT: unique values -- U = DISTINCT A; -- ORDERBY: sort -- O = ORDER A BY gpa DESC; -- JOIN: join two relations -- J = JOIN A BY rollno, B BY id; -- DUMP or STORE output -- DUMP B; STORE B INTO '/output/result';
| Feature | Pig | Hive | MapReduce |
|---|---|---|---|
| Language type | Procedural data flow | Declarative (SQL-like) | Low-level Java |
| Used by | Programmers/Researchers | Analysts | Java developers |
| Data | Structured + semi + unstructured | Mostly structured | Any |
| Schema | Optional | Mandatory | N/A |
| Code lines | ~10 for 200 Java lines | SQL queries | 200+ lines |
| Compilation | Not needed | Not needed | Long compile process |
In-memory cluster computing. Built on Hadoop MapReduce. 100x faster for large-scale in-memory processing. 10x faster for disk-based processing. Written in Scala (U.C. Berkeley). Supports Python, Java, Scala, R, SQL.
Resilient = fault tolerant, can rebuild on failure | Distributed = data partitioned across cluster nodes | Dataset = partitioned collection of values. RDDs are immutable and follow lazy evaluation (transformations not executed until action called).
Transformations
- Create a new RDD from existing
- Lazy (not executed immediately)
- map(), filter(), flatMap(), union()
Actions
- Trigger computation, return result
- Eager execution
- count(), collect(), reduce(), save()
Master Node / Driver
Contains driver program + Spark Context (gateway to all Spark functionality). Splits job into tasks. Distributes to worker nodes.
Worker Nodes
Execute tasks on partitioned RDDs. Return results to Spark Context. Add more workers → more parallelism + more memory for caching.
Cluster Managers
Apache Mesos, Hadoop YARN, Standalone Scheduler. Allocate resources for Spark jobs.
Stream Data = continuous, unbounded flow of data generated over time. Unlike static databases, stream data is dynamic, constantly evolving, potentially infinite. Examples: IoT sensors, financial transactions, social media, GPS.
Continuous Flow
No fixed endpoint. Generated constantly over time.
High Velocity
High rate of generation. Real-time processing essential.
Unbounded Length
No predetermined end. Cannot be fully stored.
Temporal Dependency
Order of arrival matters. Recent data more relevant.
Dynamic Nature
Characteristics change over time. Adaptability required.
Input Streams: Multiple streams at different rates/types/schedules. | Working Store: In memory/disk for query processing (limited capacity, holds summaries). | Archival Store: Long-term storage (not efficient for direct querying). | Stream Processor: Cannot control rate of data arrival (unlike DBMS).
- High Velocity: Elements arrive rapidly. Missing real-time window = data loss. Archival access less desirable.
- Main Memory Execution: Algorithms must run in RAM. Secondary storage access must be infrequent.
- Multiplicity of Streams: Many simultaneous streams overwhelm available memory.
- Memory Constraints: Limited memory makes problems challenging → need approximate algorithms.
Approximate Answers – preferred over exact for efficiency. Hashing Techniques – introduce randomness for approximate but close results. Acceptable to trade accuracy for real-time performance.
-- Continuous monitoring query on sensor stream -- SELECT * FROM SensorDataStream WHERE Temperature > 28 AND Humidity > 70; -- Sample stream data -- Timestamp SensorID Temperature Humidity 2024-03-11 12:00:01 Sensor1 25.5°C 60% 2024-03-11 12:00:03 Sensor2 22.0°C 55% 2024-03-11 12:00:05 Sensor3 28.3°C 70% ← triggers alert!
Data Science is a multidisciplinary field to address challenges in Big Data. Involves gathering, analyzing, and decision-making from vast amounts of data. Finds patterns and makes future predictions. Applies to ALL data — big and small.
Better Decisions
Should we choose A or B? Data-driven choices over intuition.
Predictive Analysis
What will happen next? Forecast revenue, elections, delays.
Pattern Discovery
Find hidden information and correlations in the data.
- Mathematics & Applied Mathematics
- Applied Statistics / Data Analysis
- Solid Programming (R, Python, Julia, SQL)
- Data Mining & Machine Learning
- Database Storage and Management
Route planning, flight delay prediction, promotional offers, revenue forecasting, election prediction, health benefit analysis, consumer behavior analysis, cybersecurity, fraud detection, e-commerce personalization.
📚 End of BDA Module 1 Notes — Covers: Data Types → Big Data 5V's → Challenges → Hadoop (HDFS, MapReduce, YARN) → Ecosystem (Pig, Hive, HBase, ZooKeeper, Spark) → Databases (Cassandra, MongoDB) → Stream Data → Data Science. Good luck!