Module 1 • Short Notes

Introduction to
Big Data Analytics

Comprehensive coverage of Big Data fundamentals, Hadoop ecosystem, NoSQL databases, Cassandra, MongoDB, Hive, Pig, Spark, and stream processing.

Topics
19 Units
Level
B.Tech CSE
1Introduction & Types of Digital Data

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).

Fixed SchemaSQLRDBMS

Semi-Structured

No rigid schema but uses tags/markers (JSON, XML). Self-describing with metadata. Stored in NoSQL or formats like JSON/XML.

JSONXMLFlexible

Unstructured

No predefined format. Text docs, images, videos, social media posts. Requires NLP/ML to analyze. Stored in data lakes.

ImagesVideoSocial Media
2Big Data & The V's

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.

The 7 V's of Big Data
V

Volume

Amount of data (Terabytes → Petabytes). IoT causing exponential growth.

V

Variety

Different formats: structured, semi-structured, unstructured. Text, audio, video.

V

Velocity

Speed of data generation & processing. Social media major contributor. Real-time streaming.

V

Veracity

Uncertainty / trustworthiness of data. Incompleteness, inconsistency from high volume.

V

Value

Turning big data into revenue. The end goal after addressing all other V's.

V

Visualization

Displaying in charts, graphs, maps for easy understanding of trends and patterns.

V

Virality

How quickly information spreads P2P. Rate of spread across networks.

3Challenges of Big Data

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.

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.

Scaling Solutions

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.

4Big Data Stack

Collection of technologies, frameworks, and tools used to handle, process, analyze, and derive insights from large datasets.

LayerPurposeKey Tools
Data StorageStore massive volumes of dataHDFS, MongoDB, Cassandra, Amazon Redshift, Google BigQuery
Data ProcessingProcess large datasetsApache Hadoop, Apache Spark, Apache Flink, Kafka, NiFi, AWS Kinesis
ETL (Integration)Extract, Transform, Load from sourcesApache NiFi, Talend, Informatica, AWS Kinesis
Data QueryingQuery & analyze large datasetsApache Hive, Presto, Impala, Tableau, Power BI
ML & AILearn from data & predictTensorFlow, PyTorch, scikit-learn, Keras, DataRobot
Governance & SecuritySecure, govern, and complyApache Ranger, Apache Sentry, AWS IAM, Apache Atlas
5Evolution of Analytics: 1.0 → 2.0 → 3.0

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.

6Business Intelligence vs Big Data

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
7NoSQL Databases

NoSQL = "Not Only SQL". High-performance agile processing of large-scale information. Inherently unstructured, distributed architecture, horizontal scaling.

Types of NoSQL Databases

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

NoSQL Advantages

Schema Agnostic – no upfront schema design. Horizontal Scaling – add cheap commodity servers. High Availability – masterless architecture. Performance – distributed processing at scale.

8RDBMS vs NoSQL vs NewSQL
FeatureRDBMSNoSQLNewSQL
SchemaFixed schemaSchema-freeBoth fixed & free
ConsistencyACID propertiesEventual consistencyACID properties
ScalabilityVertical (scale-up)HorizontalHorizontal
TransactionsComplex + joinsSimple onlyFully supported OLTP
Data velocityLow velocityHigh velocityHigh velocity
StructureCentralizedDecentralizedDistributed
ExamplesMySQL, PostgreSQLDynamoDB, MongoDBVoltDB, CockroachDB
NewSQL — Key Points

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
CockroachDB – Distributed, Standard SQL VoltDB – High speed, in-memory NuoDB – Distributed, cloud SingleStore – Real-time, high perf MemSQL – Fast analytics
9Big Data Processing Techniques

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.

10Hadoop Core

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.

HDFS — Hadoop Distributed File System
Key Facts about HDFS
  • 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.

MapReduce

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
MapReduce Execution Flow

JobTracker (on NameNode) = master, coordinates full execution | TaskTrackers (on DataNodes) = slaves, execute individual tasks | TaskTracker sends heartbeat + progress to JobTracker.

MapReduce Example
-- 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
YARN — Yet Another Resource Negotiator

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.

1
Client submits application
2
RM allocates container to start ApplicationMaster
3
AM registers with ResourceManager
4
AM negotiates containers from RM
5
AM notifies NodeManager to launch containers
6
Application code executes in container
7
AM un-registers with RM when complete
11Hadoop Versions 1.x → 2.x → 3.0
FeatureHadoop 1.xHadoop 2.xHadoop 3.0
Resource MgmtSingle JobTrackerYARN (RM + AppMaster)YARN + optimizations
ScalabilitySingle JobTracker bottleneckFlexible with YARNOngoing improvements
ProcessingMapReduce onlyMapReduce + others (Spark, Tez)All engines + optimizations
High AvailabilitySingle point of failureHA for NameNodeEnhanced HA
Fault ToleranceHDFS replication onlyHA configs for RM + NNFurther improvements
StorageBasic replicationHDFS FederationErasure Coding (storage efficient)
Java SupportJava 6 & 7Java 7Full Java 8 support
ContainersLimitedDocker containers with YARNDocker + Kubernetes
Hadoop 3.0 New Features

Erasure Coding – storage efficient alternative to replication | GPU Support – offload computations | Native Azure + Aliyun Storage | Improved Shell Scripting – no Java wrappers needed

12Hadoop Ecosystem Tools
ComponentTypePurpose
HDFSStorageDistributed file system, backbone of Hadoop
YARNResource MgmtResource allocation and job scheduling
MapReduceProcessingDistributed batch data processing
Apache SparkProcessingIn-memory real-time processing (100x faster than MR)
Apache PigScriptingHigh-level Pig Latin scripting for MapReduce
Apache HiveQueryingSQL-like HQL queries on HDFS data (data warehousing)
HBaseNoSQL DBDistributed NoSQL DB built on HDFS (real-time R/W)
ZooKeeperCoordinationDistributed cluster coordination and synchronization
OozieSchedulingWorkflow/job scheduler
KafkaStreamingDistributed event streaming platform
MahoutMLScalable machine learning algorithms on Hadoop
SqoopETLBulk data transfer between Hadoop and RDBMS
FlumeIngestionCollect/aggregate/move large amounts of log data
Apache Pig — Quick Summary

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.

Why Pig?

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)

Apache Hive — Quick Summary

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.

OLAP (not OLTP) Scalable Not for real-time queries High latency queries
HBase — Quick Summary

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.

ZooKeeper — Quick Summary

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 (/).

Apache Spark — Quick Summary

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.

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).

13Apache Cassandra

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.

Flexible Data Storage

All formats: structured, semi-structured, unstructured. Dynamic accommodation of structure changes.

CAP Theorem

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-offDescriptionExamples
CAAlways responds with consistent data; no partition toleranceMySQL, PostgreSQL
APDistributed, processes requests even in network partitionAmazon DynamoDB, Google Cloud Spanner
CPDistributed, drops requests instead of returning inconsistent dataApache HBase, MongoDB, Redis

Cassandra follows AP (Availability + Partition Tolerance) with BASE consistency (Basically Available Soft State Eventual Consistency).

Cassandra Architecture Components

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).

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.

Write Path in Cassandra
1
Client initiates write request
2
Written to Commit Log (write considered successful here)
3
Pushed to Mem-table (memory)
4
When Mem-table threshold reached → flushed to SSTable on disk (non-blocking)
Consistency Levels
LevelWrite RequirementRead Requirement
ONEAt least 1 replica commit log + MemtableResponse from closest replica
QUORUMQuorum of replicasResult from quorum with latest timestamp
LOCAL_QUORUMQuorum in same datacenter as coordinatorQuorum in same datacenter (reduces latency)
EACH_QUORUMQuorum in all datacentersQuorum in all datacenters
ALLAll replica nodes (highest consistency)All replicas must respond (lowest availability)
CQL — Cassandra Query Language
CQL Commands
-- 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
Collections, Counter, TTL

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.

TRACING

Detailed execution info. Identifies bottlenecks, latency, performance insights.

Counter + TTL + CSV
-- 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;
Primary Key & Partitioning in CQL
14MongoDB

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.

MongoDB Hierarchy

Database (= MySQL database) → Collection (= MySQL table, schema-less) → Document (= row, BSON key-value pairs) → Field (= column)

MongoDB vs RDBMS
MongoDBRDBMS
Non-relational, document-orientedRelational database
Dynamic/flexible schemaPredefined schema
Suitable for hierarchical storageNot suitable for hierarchical
CAP theorem (C, A, P)ACID properties
Much faster performanceSlower than MongoDB
Schema-less collectionsFixed table structure
MongoDB CRUD
MongoDB Operations
// 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.

15Apache Hive — Deep Dive

Data warehousing tool. Processes structured data in Hadoop. Uses HDFS for storage, MapReduce for execution, RDBMS for metadata. Developed at Facebook → Apache Hive.

Hive Architecture Components

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.

JDBC/ODBC

Java/app connectivity drivers. Thrift server for cross-language requests.

3 Types of MetaStore

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.

Hive Data Units

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.

File Formats in Hive
FormatTypeBest For
TextFileRow-based (default)Simple, human-readable. CSV/TXT. Each row = one line of text.
SequenceFileBinary key-value pairsCompressed binary. Supports: Uncompressed, Record compressed, Block compressed.
RCFileColumn-oriented (row groups)Read specific columns fast. Columns compressed separately. Saves space.
HiveQL Commands
Hive DDL & DML
-- 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';
Hive Partitioning

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
Partitioning Example
-- 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;
16Apache Pig — Deep Dive

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).

Pig Architecture
1
Parser

Syntax check, type checking. Output: DAG (Direct Acyclic Graph) of logical operators.

2
Optimizer

Logical optimizations (projection, pushdown) on the DAG.

3
Compiler

Compiles optimized plan into series of MapReduce jobs.

4
Execution Engine

Submits MapReduce jobs to Hadoop in sorted dependency order.

Pig Latin Data Model
TypeDescriptionExample
Atom (Field)Single value, stored as string, used as string or number'Rahul' or 50
TupleOrdered set of fields (like a row in RDBMS)(Rahul, 50)
BagUnordered set of tuples. Represented by {}{(Raja, 30), (Ali, 45)}
MapKey-value pairs. Key = chararray (unique). Represented by [][name#Raja, age#30]
RelationA bag of tuples. Unordered.Complete dataset
Pig Execution Modes

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
  • pig or pig -x mapreduce
Key Pig Latin Relational Operators
Pig Latin
-- 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';
FeaturePigHiveMapReduce
Language typeProcedural data flowDeclarative (SQL-like)Low-level Java
Used byProgrammers/ResearchersAnalystsJava developers
DataStructured + semi + unstructuredMostly structuredAny
SchemaOptionalMandatoryN/A
Code lines~10 for 200 Java linesSQL queries200+ lines
CompilationNot neededNot neededLong compile process
17Apache Spark — Deep Dive

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.

RDD — Resilient Distributed Dataset
RDD Properties

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()
Spark Architecture

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.

18Stream Data Model

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.

Data Stream Management System (DSMS)
DSMS Architecture

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).

Issues in Stream Processing
  • 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.
Stream Algorithm Approaches

Approximate Answers – preferred over exact for efficiency. Hashing Techniques – introduce randomness for approximate but close results. Acceptable to trade accuracy for real-time performance.

Stream Query Example
-- 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!
19Data Science

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.

Disciplines in Data Science
Computer Science (AI, Databases, HPC) Mathematics (Modeling) Statistics (Probability, Stochastic) Pattern Recognition Visualization Data Warehousing
Data Scientist Skills
  • Mathematics & Applied Mathematics
  • Applied Statistics / Data Analysis
  • Solid Programming (R, Python, Julia, SQL)
  • Data Mining & Machine Learning
  • Database Storage and Management
Real-World Applications

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!