Lecture 8 - Batch Processing with Hive

Updated 12 Nov 2026

Roadmap

  • Hive Concept
  • Hive Data Model
    • Table, Partition, Bucket
    • Data Type
    • File Format
  • Basic HiveQL
    • Database, Table
    • Load, Select
  • Hive Analytic Function
  • Hive Custom Function
  • Access Hive
  • Hive Processing Step
  • Apache Hue - GUI

MapReduce Issue

  • MapReduce is Key-Value with Map and Reduce stages. Need a certain level of understanding to develop a solution for a particular complex problem
  • Need to deploy code (jar) if the requirement changes
  • Need to know Java
  • Not for ad hoc operation
  • Difficult to optimize, requires high skill
  • → Need another tool to bridge and be easy to start using
    • Can we use SQL? All developers are familiar with it → Hive

Writing raw MapReduce is like building a custom machine every time you want to ask a new question. Hive is like a vending machine with SQL buttons — you just press "SELECT ... GROUP BY ..." and it builds the machine for you behind the scenes.


Apache Hive: Data Warehouse

  • Hive is a data warehousing package built on top of Hadoop
  • Hive is designed for Batch Processing — familiar, fast, scalable, and extensible
  • Its target users remain data analysts who are comfortable with SQL and who need to do ad hoc queries, summarization, and data analysis on Hadoop-scale data
  • You interact with Hive by issuing queries in a SQL-like language called HiveQL via Web GUI and JDBC
  • Key features:
    • Open Source
    • Multiple User
    • File Formats
    • Built-in function
    • External Table
    • Fast
    • Table Structure
    • ETL Support
    • Storage
    • Ad-hoc queries


Apache Hive: Example SQL

  • Hive helps with querying and managing large datasets real fast. It is an ETL tool for the Hadoop ecosystem
  • Three steps: create schema, load data, query
  1. Create schema (Schema on use)
CREATE TABLE zdcdata (uid string, time string, lon string, lat string, err int, alt double, pcode string, ccode string)
ROW FORMAT DELIMITED
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
STORED AS TEXTFILE;
  1. Load/Import data
load data local inpath '/data/zdcdata/20100802.csv'
overwrite into table zdcdata;
  1. Ready to use
select * from zdcdata where uid = '0051155';

"Schema on use" (a.k.a. schema-on-read): the CSV file just sits there as plain text. The CREATE TABLE is like putting a transparent grid overlay on top of the paper — Hive only interprets the columns when you read it.


Apache Hive is NOT a Database

  • Hive provides data query and analysis. Hive gives an interface like SQL to query data stored in various databases and file systems that integrate with Hadoop
  • Hive is not a database. No update, delete operation. Write once, Read many times
RDBMSHive
It is used to maintain databaseIt is used to maintain data warehouse
It uses SQL (Structured Query Language)It uses HQL (Hive Query Language)
Schema is fixed in RDBMSSchema varies in it
Normalized data is storedNormalized and de-normalized both types of data are stored
It doesn't support partitioning but indexIt supports automatic partition
Supports transactionNo transaction
Millisecond levelSecond to minute level

RDBMS is like a cashier's till — many tiny, fast, precise updates (transactions). Hive is like the year-end accounting archive — you rarely change old records, but you run big summaries over years of them, and it's fine if it takes minutes.


Hive Architecture

  • It stores schema in a database. It processes data in HDFS
  • Metastore: a service that stores the metadata information such as table schemas
  • Thrift: a thrift service is used to provide remote access from other processors
  • Components:
    • Hive clients: Thrift application → Hive Thrift Client; JDBC application → Hive JDBC Driver; ODBC application → Hive ODBC Driver
    • Hive services: CLI, Hive server, Hive Web Interface → Driver (Parser, Planner, Optimizer, Execution) → Metastore / FileSystem / JobClient
    • Hive Storage and Compute:
      • Metastore database → stores schema (Local, MySQL, PostgreSQL)
      • Hadoop cluster → processes data
  • SQL (e.g. Select * from table) enters through the client (e.g. JDBC application)

The Metastore is the library catalog (which book is where, what's in it); HDFS is the actual shelves of books; the Driver is the librarian who reads your request, plans the route, and sends helpers (YARN jobs) to fetch the data.


How It Works

  • SQL (e.g. Select * from table) is submitted from the UI. Steps:
    1. executeQuery: UI → Driver
    2. getPlan: Driver → Compiler
    3. getMetaData: Compiler → Metastore
    4. sendMetaData: Metastore → Compiler
    5. sendPlan: Compiler → Driver
    6. executePlan: Driver → Execution Engine
      • 6.1 executeJob: Execution Engine → YARN (Hadoop MAP/REDUCE); metaDataOps for DDLs: Execution Engine ↔ Metastore
      • 6.2 jobDone: YARN → Execution Engine
      • 6.3 dfs operations: Execution Engine ↔ Name Node (HDFS)
    7. fetchResults: UI ↔ Driver
    8. sendResults: Execution Engine → Driver
    9. fetchResults: Execution Engine ← HDFS
  • On the Hadoop side, YARN launches MAP/REDUCE TASKS on Task Trackers (Map) (Map Operator Tree, SerDe Deserialize) and Task Trackers (Reduce) (Reduce Operator Tree, SerDe Serialize), which read/write to HDFS (Name Node, Data Nodes)
  • Source: https://www.geeksforgeeks.org/architecture-and-working-of-hive/

Like ordering at a restaurant: you (UI) give your order to the waiter (Driver), who asks the chef (Compiler) to plan the dish using the recipe book (Metastore), then the kitchen staff (YARN map/reduce tasks) cook using ingredients from the pantry (HDFS), and the waiter brings back the result.


How It Works: Example Run

  • Running a HiveQL query in the Hive CLI:
hive> select PDATE, count(*) as total, count(distinct vehicle_id) as totalvehicle
    > from taxi_raw_data
    > group by pdate order by pdate;
  • Output shows Hive turning the query into a job on YARN (Tez):
Query ID = hadoop_20231004175709_cccf2bf2-04fb-4c39-9974-8799cd12723b
Total jobs = 1
Launching Job 1 out of 1
Tez session was closed. Reopening...
Session re-established.
Status: Running (Executing on YARN cluster with App id application_1696437795605_0003)
 
        VERTICES      MODE        STATUS  TOTAL  COMPLETED  RUNNING  PENDING  FAILED  KILLED
Map 1 .......... container     SUCCEEDED      9          9        0        0       0       0
Reducer 2 ...... container     SUCCEEDED      2          2        0        0       0       0
Reducer 3 ...... container     SUCCEEDED      1          1        0        0       0       0
VERTICES: 03/03  [==========================>>] 100%  ELAPSED TIME: 40.72 s
OK
pdate       total    totalvehicle
2018-08-01  3181459  5931
2018-08-02  2781095  5942
Time taken: 54.471 seconds, Fetched: 2 row(s)
  • Note: one SQL query became 1 Map vertex (9 tasks) + 2 Reducer vertices — Hive wrote the MapReduce/Tez job for you
  • Time is in seconds (≈54 s), consistent with "second to minute level"

Hive Data Model

  • Hive stores data in the form of a table. Each table has a corresponding directory in HDFS. Default path is /apps/hive/warehouse (EMR: /user/hive/warehouse)
  • Data is serialized and stored as files within that directory
  • Data models contain components: Databases, Tables, Partitions, Buckets
  • Mapping Hive → HDFS:
    • CREATE DATABASE des431; → Database → directory des431.db
    • CREATE TABLE datalog ... → Table → directory datalog
    • Partitions → sub-directories
    • Buckets → files
    • If no partition, files are on the directory directly. No sub-directory
CREATE DATABASE des431;
 
CREATE TABLE datalog
ROW FORMAT
DELIMITED FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
STORED AS TEXTFILE

Database = a filing cabinet, Table = a drawer, Partition = folders inside the drawer (e.g. one per date), Bucket = a fixed number of files inside each folder.


Hive Data Model: Table

  • There are 3 types of tables in Hive: Internal, External and Temporary
    • Internal table (Managed Table): like a normal database table where data can be stored and queried on. On dropping the table, the data also gets deleted, and data is lost forever
    • External tables: stored outside Hive. They can access data stored in sources such as remote HDFS locations, S3, Azure Storage Volumes. Drop table will not delete data
    • Temporary table: created and exists only within the current session; upon exiting the session it will be removed and cannot be accessed in another session
  • Supports custom fields and lines terminated such as comma (,), semicolon (;), newline (\n) or tab (\t)
  • Supports fixed length file: WITH SERDEPROPERTIES ("input.regex" = "(.{10})(.{10})(.{10})(.2})")
  • Supports skip header: TBLPROPERTIES ("skip.header.line.count"="1");

Internal table = you own the house; demolish it (DROP) and everything inside is gone. External table = you rent a view of someone else's warehouse (S3); you can tear up your rental contract (DROP) but the goods stay there.


Hive Table: File Format

  • It supports file formats: RCFILE (Record Columnar File), SEQUENCEFILE, ORC, TEXT FILE, Parquet
  • ORC is recommended
  • File size comparison (Dataset: TPC-DS Scale 500):
    • Text: 585 GB (original size)
    • RCFile: 505 GB (14% smaller)
    • Parquet (Impala): 221 GB (62% smaller)
    • ORCFile (Hive 12): 131 GB (78% smaller)
  • Why ORC is smaller/faster:
    • Larger block sizes
    • Columnar format arranges columns adjacent within the file for compression & fast access
  • ORC file layout: a series of 250 MB Stripes, each with Index Data, Row Data (stored column by column: Column 1 … Column 8), and Stripe Footer; then a File Footer and Postscript

  • Size reduction can be computed as:

Reduction=Original−NewOriginal×100%\boxed{\text{Reduction} = \frac{\text{Original} - \text{New}}{\text{Original}} \times 100\%}

  • e.g. ORC: 585−131585×100%≈78%\frac{585 - 131}{585} \times 100\% \approx 78\%

Row format (TEXT) is like storing each student's whole report card together; columnar (ORC) is like storing all the "Math" scores together, all the "English" scores together — similar values sit side by side, so they compress well, and if you only need Math you skip everything else.


Hive Data Model: Table Example

  • Hive has a default database named "default". If no db is specified, default will be used
  • Example: select * from calls_sample limit 100 in the Hive query editor reads the table calls_sample, which lives in HDFS at apps > hive > warehouse > calls_sample, containing data file 000000_0 (73.3 MB)


Hive Data Model: Partition

  • Hive partitions are used to split the larger table into several smaller parts based on one or multiple columns (partition key, for example, date, state etc.)
  • Hive internally splits the records based on the partition key and stores each partition data into a sub-directory of the table's directory on HDFS. The name of the directory would be the partition key and its value
  • Hive does not have index but uses partition instead
/user/hive/warehouse/logs
├── dt=2001-01-01/
│   ├── country=GB/
│   │   ├── file1
│   │   └── file2
│   └── country=US/
│       └── file3
└── dt=2001-01-02/
    ├── country=GB/
    │   └── file4
    └── country=US/
        ├── file5
        └── file6

Partitioning is like organizing photos into folders by date: if you want photos from 2001-01-01, you open just that folder instead of scrolling through every photo you own (this is called partition pruning).


Hive Data Model: Example with Partition

  • Specifying the database is the best practice; partition helps to access data faster
Select *
from d4r.dataset2_by_uid
Where pdt = '2017-01-01'
  • HDFS layout:
    • warehouse > d4r.db → Database name
    • dataset2_by_uid → Table name
    • pdt=2017-01-01, pdt=2017-01-02, … → Partition name by date
    • 000000_0, 000001_0, 000002_0, 000003_0 → Data files, split by reduce


Hive Data Model: Bucket

  • Hive Bucketing or Clustering is a technique to split the data into more manageable files (by specifying the number of buckets to create). The value of the bucketing column will be hashed by a user-defined number into buckets
CREATE TABLE products (product_id string, brand string, size string, discount float, price float)
PARTITIONED BY (gender string, category string, color string)
CLUSTERED BY (price) INTO 50 BUCKETS;
  • Here: partition by gender → category → color (directories), then bucket by price (files)
  • Bucket assignment (hash-based):

bucket=hash(bucketing column value) mod Nbuckets\boxed{\text{bucket} = \text{hash}(\text{bucketing column value}) \bmod N_{\text{buckets}}}

Partition = sort mail into a pigeonhole per city (number of holes depends on the data). Bucket = within each pigeonhole, split letters into exactly 50 trays using a formula on the price — a fixed number of trays no matter how many distinct values there are.


Hive Data Model: Data Type

  • Hive supports primitive data types and complex data types such as Array, Map, Struct
  • Timestamp format is 'YYYY-MM-DD HH:MM:SS'
  • Missing / no data is represented with NULL
  • Primitive data types:
    • NUMERIC: TinyInt, SmallInt, Integer, BigInt, Float, Double, Decimal, Numeric
    • DATE TIME: Timestamp, Date, Interval
    • STRING: String, Varchar, Char
    • MISC.: Boolean, Binary
  • Complex data types:
    • ARRAY: LIST — collection of similar data
    • MAP: SET — key-value combination
    • STRUCT: MULTI-SET — collection of different data
    • UNION: similar to UNION in C — holds one data type
  • Source: https://bigdatansql.com/2021/01/11/apache-hive-complex-data-types-part-1/


Hive Data Model: Complex Data Type Examples

  • Array — e.g. Alice: 60, 70, 65, 72, 81
CREATE TABLE student_array (student STRING,
  marks_in_all_subjects ARRAY<INT>);
 
Select marks_in_all_subjects[0]
  • Map — e.g. Alice: Maths:60, Science:70, Physics:65, Chemistry:72
CREATE TABLE student_map (student STRING,
  marks MAP<STRING, INT>);
 
Select marks['Maths']
  • Struct — e.g. Alice: 87, 2nd Street, Alba Towers, 67011
CREATE TABLE student_struct (name STRING,
  address STRUCT<house_no:INT, street:STRING, building:STRING, zip:INT>);
 
Select address.zip

Array = a numbered list (access by position [0]), Map = a dictionary (access by key ['Maths']), Struct = a mini-form with named fields (access by .zip).


HiveQL

  • Hive Query Language (HiveQL) is a query language for Hive to process and analyze structured data in a Metastore. It is based on the SQL-92 standard
  • Common practice:
    • No update, no delete, no transaction
    • To update, create a new table with insert from select
    • Use partition for faster query
    • Date format is 'YYYY-MM-DD HH:MM:SS'
  • Hive SQL Semantics:
    • Hive 0.10: SELECT, LOAD, INSERT from query; Expressions in WHERE and HAVING; GROUP BY, ORDER BY, SORT BY; Sub-queries in FROM clause; GROUP BY, ORDER BY; CLUSTER BY, DISTRIBUTE BY; ROLLUP and CUBE; UNION; LEFT, RIGHT and FULL INNER/OUTER JOIN; CROSS JOIN, LEFT SEMI JOIN
    • Hive 0.11: Windowing functions (OVER, RANK, etc.)
    • Future: INTERSECT, EXCEPT, UNION DISTINCT; Sub-queries in WHERE (IN/NOT IN, EXISTS/NOT EXISTS); Sub-queries in HAVING


SQL vs HiveQL

FeatureSQLHiveQL
UpdatesUPDATE, INSERT, DELETEINSERT OVERWRITE TABLE (populates whole table or partition)
TransactionsSupportedNot supported
IndexesSupportedNot supported
LatencySub-secondMinutes
Data typesIntegral, floating point, fixed point, text and binary strings, temporalIntegral, floating point, boolean, string, array, map, struct
FunctionsHundreds of built-in functionsDozens of built-in functions
Multitable insertsNot supportedSupported
Create table as selectNot valid SQL-92, but found in some databasesSupported
SelectSQL-92Single table or view in the FROM clause. SORT BY for partial ordering. LIMIT to limit number of rows returned. HAVING not supported
JoinsSQL-92 or variants (join tables in the FROM clause, join condition in the WHERE clause)Inner joins, outer joins, semi joins, map joins. SQL-92 syntax, with hinting
SubqueriesIn any clause. Correlated or noncorrelatedOnly in the FROM clause. Correlated subqueries not supported
ViewsUpdatable. Materialized or nonmaterializedRead-only. Materialized views not supported
Extension pointsUser-defined functions. Stored proceduresUser-defined functions. MapReduce scripts
  • Note: this comparison is from an older Hive version; newer Hive versions added things like HAVING and subqueries in WHERE (see "Hive SQL Semantics" above)

HiveQL Commands

  • Data Definition Language (DDL)
    • CREATE DATABASE
    • CREATE TABLE, ALTER TABLE
    • SHOW TABLE, DESCRIBE
  • Data Manipulation Language (DML)
    • LOAD TABLE
    • INSERT
  • Data Query Language (DQL)
    • SELECT
    • GROUP BY
    • JOIN
  • Analytic Functions
    • RANK
    • ROW_NUMBER
    • CUME_DIST
    • PERCENT_RANK
    • NTILE
  • Windowing Functions
    • LEAD, LAG
    • OVER with a PARTITION
  • Built-in functions
    • Date Functions, String Functions
    • So many…

DDL = building the shelves (structure), DML = putting goods on the shelves (data), DQL = asking questions about what's on the shelves.


HiveQL Syntax: Database, Table

  • Create database
CREATE DATABASE [IF NOT EXISTS] userdb;
DROP DATABASE userdb;   -- to drop specific databases
SHOW DATABASES;         -- to see list of all databases
USE userdb;             -- use this database instead of the default
  • Create table (general syntax; [...] = optional)
CREATE [TEMPORARY] [EXTERNAL] TABLE [IF NOT EXISTS] [db_name.] table_name
[(col_name data_type [COMMENT col_comment], ...)]
[PARTITIONED BY (col_name data_type [COMMENT 'col_comment'], ...)]
[COMMENT table_comment]
[ROW FORMAT row_format]
[LOCATION 'hdfs_path']
[STORED AS file_format]

HiveQL Syntax: Table

  • Create internal table
CREATE TABLE employee (id int, name String, salary String, destination String)
ROW FORMAT DELIMITED
FIELDS TERMINATED BY '\t'  -- tab symbol
LINES TERMINATED BY '\n'   -- newline symbol
STORED AS TEXTFILE;
  • Create external table (uses LOCATION to point at existing data)
CREATE TABLE employee (id int, name String, salary String, destination String)
ROW FORMAT DELIMITED
FIELDS TERMINATED BY '\t'  -- tab symbol
LINES TERMINATED BY '\n'   -- newline symbol
LOCATION '/user/hive/data/employee_external';
  • Note: in standard HiveQL the keyword is CREATE EXTERNAL TABLE ... (the slide omits EXTERNAL)

  • Create table from select (CTAS)

CREATE TABLE emp_filter AS SELECT id,name FROM emp.employee WHERE gender = 'F';
  • Some more commands
SHOW TABLES;            -- to see list of all tables under current database
DESCRIBE employee;      -- see definition of this table
DROP TABLE employee;    -- delete this table including data
  • Load data to table
LOAD DATA [LOCAL] INPATH 'filepath' [OVERWRITE] INTO TABLE tablename
[PARTITION (partcol1=val1, partcol2=val2 ...)]
LOAD DATA LOCAL INPATH '/home/user/sample.txt'   -- this is a path in local computer
OVERWRITE INTO TABLE employee;
 
LOAD DATA INPATH '/home/user/sample_hdfs.txt'    -- this is a path in HDFS
OVERWRITE INTO TABLE employee;
  • LOCAL = file is on the local machine (copied in); without LOCAL = file is already in HDFS (moved in)
  • OVERWRITE = replace existing data in the table/partition

HiveQL Syntax: Table Partition

  • Create table with partition column
CREATE TABLE employee (id int, name String, salary String, destination String)
PARTITIONED BY (dept string)
ROW FORMAT DELIMITED
FIELDS TERMINATED BY '\t'  -- tab symbol
LINES TERMINATED BY '\n'   -- newline symbol
STORED AS TEXTFILE;
  • Load data to partition
LOAD DATA LOCAL INPATH '/DATA/DEPT_ENG.CSV'
OVERWRITE INTO TABLE EMPLOYEE PARTITION (DEPT='ENGINEER');
 
LOAD DATA LOCAL INPATH '/DATA/DEPT_SALES.CSV'
OVERWRITE INTO TABLE EMPLOYEE PARTITION (DEPT='SALES');
 
LOAD DATA LOCAL INPATH '/DATA/DEPT_PRODUCT.CSV'
OVERWRITE INTO TABLE EMPLOYEE PARTITION (DEPT='PRODUCT');
  • Each load creates a sub-directory like employee/dept=ENGINEER/
  • The partition column (dept) is not listed in the column list — it lives in the directory name

HiveQL Syntax: Select

  • SELECT statement is used to retrieve the data from a table
SELECT [ALL | DISTINCT] select_expr, select_expr, ...
FROM table_reference
[WHERE where_condition]
[GROUP BY col_list]
[HAVING having_condition]
[CLUSTER BY col_list | [DISTRIBUTE BY col_list] [SORT BY col_list]]
[LIMIT number];
SELECT * FROM employee WHERE salary>30000;
SELECT COUNT(DISTINCT eid) from employee;
SELECT DEPT, COUNT(*) AS TOTAL FROM EMPLOYEE GROUP BY DEPT ORDER BY TOTAL DESC;
SELECT eid,salary FROM employee limit 1000;
SELECT avg(salary) FROM employee;

HiveQL Syntax: Select — Example Query Execution

  • Example: SELECT COUNT(1) FROM cite; goes through 4 stages:
    1. Hive QL — the query is submitted
    2. Prepare MapReduce Job — Hive decides number of reducers
    3. Submit Job — job is sent to the cluster (Job Tracker)
    4. Execute MapReduce Job — map progresses 0% → 100%, then reduce 0% → 100%
    5. Return Result
hive> SELECT COUNT(1) FROM cite;
Total MapReduce jobs = 1
Number of reduce tasks determined at compile time: 1
In order to change the average load for a reducer (in bytes):
  set hive.exec.reducers.bytes.per.reducer=<number>
In order to limit the maximum number of reducers:
  set hive.exec.reducers.max=<number>
In order to set a constant number of reducers:
  set mapred.reduce.tasks=<number>
Starting Job = job_200908250716_0001, Tracking URL = http://ip-10-244-199-143.ec2.internal:50030/jobdetails.jsp?jobid=job_200908250716_0001
Kill Command = /usr/lib/hadoop/bin/hadoop job -Dmapred.job.tracker=ip-10-244-199-143.ec2.internal:9001 -kill job_200908250716_0001
 map = 0%,  reduce =0%
 map = 12%,  reduce =0%
 map = 25%,  reduce =0%
 ...
 map = 99%,  reduce =0%
 map = 100%,  reduce =0%
 map = 100%,  reduce =67%
 map = 100%,  reduce =100%
Ended Job = job_200908250716_0001
OK
16522439
Time taken: 85.153 seconds
  • Notice reduce only starts after map reaches 100% — same as MapReduce from Lecture 6

HiveQL Syntax: JOIN

  • Hive supports 4 types of JOIN operation:
    • INNER JOIN: select records that have matching values in both tables
    • LEFT JOIN: all the values from the left table, plus the matched values from the right table
    • RIGHT JOIN: all the values from the right table, plus the matched values from the left table
    • FULL JOIN: selects all records that match either left or right table records

  • Example tables:

CUSTOMERS

IDNameAgeAddressSalary
1Ross32Ahmedabad2000
2Rachel25Delhi1500
3Chandler23Kota2000
4Monika25Mumbai6500

ORDERS

OIDDateCustomer_IDAmount
1022016-10-08 00:00:0033000
1002016-10-08 00:00:0031500
1012016-11-20 00:00:0021560
1032015-05-20 00:00:0042060
SELECT c.ID, c.NAME, c.AGE, o.AMOUNT
FROM CUSTOMERS c JOIN ORDERS o ON (c.ID = o.CUSTOMER_ID);
 
SELECT c.ID, c.NAME, o.AMOUNT, o.DATE
FROM CUSTOMERS c LEFT OUTER JOIN ORDERS o ON (c.ID = o.CUSTOMER_ID);
 
SELECT c.ID, c.NAME, o.AMOUNT, o.DATE
FROM CUSTOMERS c RIGHT OUTER JOIN ORDERS o ON (c.ID = o.CUSTOMER_ID);
 
SELECT c.ID, c.NAME, o.AMOUNT, o.DATE
FROM CUSTOMERS c FULL OUTER JOIN ORDERS o ON (c.ID = o.CUSTOMER_ID);
  • Worked out:
    • INNER JOIN → 4 rows: Chandler (3000), Chandler (1500), Rachel (1560), Monika (2060). Ross is dropped (no orders)
    • LEFT OUTER JOIN → same 4 rows + Ross with NULL amount/date
    • RIGHT OUTER JOIN → the 4 orders (every order has a matching customer here)
    • FULL OUTER JOIN → all 4 matched rows + Ross with NULL

Think of a party guest list (CUSTOMERS) and a gift log (ORDERS). INNER = only guests who brought gifts. LEFT = every guest, gift or not (NULL if none). RIGHT = every gift, even if we don't know who brought it. FULL = everyone and everything.


Hive Analytic Function

  • Analytic functions or Window functions in Hive are functions used to compute an aggregate value from a table, or a set of rows, based on a defined partition window
  • These functions usually consist of an over() keyword which helps in defining the window, and an optional list of columns for ordering
  • Examples of some analytic functions include lead, lag, sum, min, max etc.
  • Difference:
    • Aggregated Functions – GROUP BY (i.e. AVG(), Count(), etc.): many rows collapse into one result row
    • Window Functions – OVER, PARTITION BY, ORDER BY: every row is kept, and each row gets its own computed value (Σ) attached

GROUP BY is like asking "what's the class average?" — you get one number. A window function is like writing the class average next to each student's name on the report sheet — every student stays on the list.


Hive Analytic Function: Window (AVG per Partition)

  • For each film find an average rating for all films released in the same year
SELECT F.ID, F.RELEASE_YEAR, F.CATEGORY_ID, F.RATING,
       AVG(RATING) OVER (PARTITION BY RELEASE_YEAR) AS YEAR_AVG
FROM FILMS F
idrelease_yearcategory_idratingyear_avg
1201518.008.50
2201528.508.50
3201539.008.50
4201628.208.30
5201618.408.30
6201727.007.00
  • Year = 2015 ⇒ avg(rating)=8.00+8.50+9.003=8.5\text{avg(rating)} = \frac{8.00 + 8.50 + 9.00}{3} = 8.5
  • Year = 2016 ⇒ avg(rating)=8.20+8.402=8.3\text{avg(rating)} = \frac{8.20 + 8.40}{2} = 8.3
  • Year = 2017 ⇒ avg(rating)=7.0\text{avg(rating)} = 7.0
  • Formula for the window average of partition PP:

year_avg(r)=1∣P∣∑i∈Pratingi,P={ i:release_yeari=release_yearr }\boxed{\text{year\_avg}(r) = \frac{1}{|P|}\sum_{i \in P} \text{rating}_i, \quad P = \{\, i : \text{release\_year}_i = \text{release\_year}_r \,\}}


Hive Analytic Function: Window (RANK per Partition)

  • For each film find its ranking position within its release year
SELECT f.id, f.release_year, f.category_id, f.rating,
       RANK() OVER (PARTITION BY release_year ORDER BY rating DESC) AS year_rank
FROM films f
idrelease_yearcategory_idratingyear_rank
1201518.003
2201528.502
3201539.001
4201628.202
5201618.401
6201727.001
  • Ranking restarts at 1 for each year (each partition)

Hive Analytic Function: Window (General RANK)

  • For each film find its general ranking position (No Partition, all data)
SELECT f.id, f.release_year, f.category_id, f.rating,
       RANK() OVER (ORDER BY rating DESC) AS general_rank
FROM films f
idrelease_yearcategory_idratinggeneral_rank
1201518.005
2201528.502
3201539.001
4201628.204
5201618.403
6201727.006
  • No PARTITION BY → the whole table is one window

PARTITION BY = ranking students within each classroom; no partition = ranking everyone in the whole school.


Hive Analytic Function: LEAD, LAG

  • LEAD: an analytics function used to return the data from the next set of rows
  • LAG: returns the data from the previous data set
  • Syntax: lag(col, offset, default) / lead(col, offset, default) — default is the default value if no data (otherwise NULL)
monthsoldlag(sold) OVER(ORDER BY month)lead(sold) OVER(ORDER BY month)lag(sold, 2, 0) OVER(ORDER BY month)lead(sold, 2, 0) OVER(ORDER BY month)
1500NULL3000400
23005004000100
3400300100500500
41004005003000
5500100NULL4000

  • In formula form (rows ordered by month, offset kk):

LAG(x,k)t=xt−k,LEAD(x,k)t=xt+k\boxed{\text{LAG}(x, k)_t = x_{t-k}, \qquad \text{LEAD}(x, k)_t = x_{t+k}}

  • If t−kt-k or t+kt+k is out of range → returns the default (NULL if not given)

LAG = looking in the rear-view mirror ("how much did we sell last month?"); LEAD = looking through the windshield ("how much will we sell next month?"). Great for computing month-over-month change: sold - lag(sold).


Hive Built-in Function

  • Mathematical: abs, round, floor, ceil, sqrt, hex, sin, cos, tan
  • Collection: size, array_contain, sort_array
  • Type Conversion: cast, binary
  • Date: unix_timestamp, to_date, year, month, day, weekofyear, extract, datediff, dateadd
  • Conditional: if, isnull, case when, nvl
  • String: concat, encode, instr, length, trim, substr, upper
  • Data Masking: mask, mask_first_n, mask_hash
  • Statistics: sum, count, avg, stddev_pop, corr, percentile, histogram_numeric, ntile
  • Source: https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF

Hive: User-Defined Function

  • User-Defined Function (UDF)
    • UDF operates on a row and produces a row as its output. Most functions, such as mathematical and string functions, are of this type
    • One-to-one mapping
    • e.g. Concat("Foo", "bar")
  • User-Defined Aggregate Function (UDAF)
    • UDAF performs a function on multiple input rows and creates a single output row. COUNT and SUM are examples of these aggregate functions
    • Many-to-one mapping
    • e.g. Sum(item)
  • User-Defined Table-generating Function (UDTF)
    • UDTF runs on a single row and produces multiple rows as a table as output
    • One-to-many mapping
    • e.g. Explode([1,2,3])

UDF:1→1,UDAF:n→1,UDTF:1→n\boxed{\text{UDF}: 1 \to 1, \qquad \text{UDAF}: n \to 1, \qquad \text{UDTF}: 1 \to n}

UDF = a stamp (one paper in, one stamped paper out). UDAF = a shredder-and-scale (many papers in, one total weight out). UDTF = a photocopier that splits a booklet into pages (one booklet in, many pages out).


Hive: Custom Function Development

  • Steps:
    1. Develop function (UDF, UDAF, UDTF)
    2. Create Jar Library
    3. Upload to Hive directory
    4. Load to Hive using "ADD JAR"
    5. Create temporary function on Hive
    6. Add extra files to Hive using "ADD FILE" (if necessary)
    7. Execute query

ADD JAR /hadoop/hive/lib/mobilitylib.jar;
create temporary function ExtractStayPoint as 'com.apichon.mobility.hive.udf.ExtractStayPoint';
create temporary function FindPolygon as 'com.apichon.mobility.hive.udf.FindPolygon';
create temporary function StayCluster as 'com.apichon.mobility.hive.udf.StayCluster';
ADD FILE /hadoop/data/odaiba.csv;
SELECT uid,dt,lon,lat,err,alt,pcode,ccode from zdcdata
where pcode = '13' and FindPolygon(lon,lat,'odaiba.csv') =1;
  • Here FindPolygon(lon, lat, 'odaiba.csv') is a custom Java UDF that checks whether a GPS point lies inside the polygon defined in odaiba.csv

Access Hive for Processing Data

  • Hive supports multiple ways to interact with it:
    • Hive Command line (CLI, Hive, Beeline)
      • For manual process, initial data, ad-hoc query
    • GUI (via Ambari, Hue)
      • For manual process, initial data, ad-hoc query, easy to start, control access
    • Java program
      • For automated process, run pipeline processing with multiple queries and logic
    • Python script
      • For automated process, run pipeline processing with multiple queries and logic
  • HiveServer2 is a necessary service for remote connection to Hive
    • Beeline, JDBC, ODBC → HiveServer2 → MetaStore (MySQL) + Hadoop Cluster
    • Hive CLI connects directly to the MetaStore and the Hadoop Cluster (no HiveServer2)

HiveServer2 is like the front desk of a hotel — guests calling from outside (JDBC/ODBC/Beeline) go through it. The Hive CLI is like a staff member already inside the building who walks straight to the rooms.


Access Hive: Hive Command Line (CLI)

  • Connect to the Hadoop cluster with ssh (need credential)
  • Run the hive command to process data
$ hive
Logging initialized using configuration in file:/etc/hive/2.6.5.1100-53/0/hive-log4j.properties
hive> SET hive.cli.print.header=true;
hive> select vehicleid,dt from taxi_itic limit 5;
vehicleid       dt
ap2i0sE4rnP5wftUf6mWgAqb5gU     2018-12-04 00:00:01
s6iN8GJhvvcSnseyMWr/xXPnpe8     2018-12-03 23:57:50
285NxDjewwx+QA+sxoKwng1y4mY     2018-12-03 23:58:03
1vPXjzX9eYasEXlEzUg3B00TKjY     2018-12-04 00:00:04
l2o/cAk8eZWEW+d1pCzKhqFN6EM     2018-12-03 23:57:45
Time taken: 0.106 seconds, Fetched: 5 row(s)
  • SET hive.cli.print.header=true; → show column names in the output

Access Hive: GUI

  • Ambari → Hive View 2.0
  • Tabs: QUERY, JOBS, TABLES, SAVED QUERIES, UDFs, SETTINGS
  • Select a database (e.g. default), type a query (e.g. select * from calls limit 5), click Execute, and view RESULTS / LOG / VISUAL EXPLAIN / TEZ UI
  • Ambari menu views: YARN Queue Manager, Files View, Hive View, Hive View 2.0, Tez View


Access Hive: Java Program

  • Java will remote connect to Hive via JDBC Hive Driver
  • Make sure HiveServer2 is running. Normally running on port 10000
  • Configure firewall to allow incoming access to the Hive port
  • JDBC connection URL string: jdbc:hive://ip-address:port/database
  • Example connection string: "jdbc:hive[2]://localhost:10000/userdb"
  • Required libraries:
    • hive-jdbc
    • hadoop-common
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.DriverManager;
 
public class HiveQL {
  private static String driverName = "org.apache.hadoop.hive.jdbc.HiveDriver";
 
  public static void main(String[] args) throws SQLException {
 
        Class.forName(driverName); // Register driver and create driver instance
        Connection con = DriverManager.getConnection("jdbc:hive://localhost:10000/userdb", "", ""); // get connection
 
        Statement stmt = con.createStatement(); // create statement
        Resultset res = stmt.executeQuery("SELECT * FROM employee WHERE salary>30000;"); // execute statement
 
        System.out.println("Result:");
        System.out.println(" ID \t Name \t Salary \t Designation");
 
        while (res.next()) {
          System.out.println(res.getInt(1) + " " + res.getString(2) + " " + res.getDouble(3) + " " + res.getString(4));
        }
 
        con.close();
  }
}
  • Flow: register driver → get connection → create statement → execute query → loop over ResultSet → close

Access Hive: Python Script

  • There are multiple library options: PyHive, Impala, JDBC wrapper (Jaydebeapi3)
from pyhive import hive
 
host_name = "localhost"
port = 10000
user = "admin"
password = "password"
database="userdb"
 
def hiveconnection(host_name, port, user,password, database):
    conn = hive.Connection(host=host_name, port=port, username=user, password=password,
                           database=database, auth='CUSTOM')
 
    cur = conn.cursor()
    cur.execute('SELECT * FROM employee WHERE salary>30000 limit 5')
    result = cur.fetchall()
 
    return result
 
# Call above function
output = hiveconnection(host_name, port, user,password, database)
print(output)

Java/Python access is like setting up a robot that phones the Hive front desk (HiveServer2, port 10000) every night and runs the same list of queries automatically — that's a pipeline.


Hive Processing Steps

  1. Prepare EMR with Hive Environment
  2. Upload data to Hadoop (EMR)
  3. Connect to Hive CLI with ssh
  4. Create table and import data
  5. Calculate statistics for data quality check
  6. Preprocessing (if necessary)
  7. Ready for analysis

1. Prepare EMR with Hive Environment

  • Create or clone your EMR cluster
  • Make sure to have:
    • Hadoop, Tez, Hive, Hue, Pig
    • Spark, Livy
    • JupyterHub, Zeppelin
  • Wait until status shows Waiting
  • Example (EMR release emr-7.9.0, Custom application bundle): Hadoop 3.4.1, Hive 3.1.3, Hue 4.11.0, JupyterHub 1.5.0, Livy 0.8.0, Pig 0.17.0, Spark 3.5.5, Tez 0.10.2, Zeppelin 0.11.1
  • Capacity: 1 Primary, 2 Core, 0 Task

  • EMR also provides a Web GUI for each service on Hadoop
  • Replace the URL with your EMR URL (Primary node public DNS)
  • We normally check:
    • Hadoop HDFS NameNode
    • YARN ResourceManager
    • Hue for Hive access
ApplicationPort
HDFS Name Node:9870/
Hue:8888/
JupyterHub:9443/ (https)
Livy:8998/
Resource Manager:8088/
Spark History Server:18080/
Tez UI:8080/tez-ui
Zeppelin:8890/
  • URL pattern: http://<primary node public DNS>:<port>/


2. Upload Data to Hadoop (EMR)

  • Windows — FileZilla Client:
    • Connect to EMR using FileZilla Client
    • Specify IP address (Primary node public DNS), port: 22
    • Specify User: hadoop and Private Key (PEM from AWS Details of the lab learner)
    • In Site Manager: Protocol = SFTP – SSH File Transfer Protocol, Logon Type = Key file
    • Create directory data under /home/hadoop, then upload the files (e.g. 20180801.csv.out, 20180802.csv.out)

  • Mac — terminal with SCP command:
    • Connect to EMR using the terminal with SCP
    • Check the primary node public DNS
    • Use user: hadoop and Private Key (PEM from AWS Details of the lab learner)
scp -i pem_file file_to_upload hadoop@<primary node public DNS>:/home/hadoop/<path>/
 
# EX:
scp -i pem_file 20180801.csv.out hadoop@<primary node public DNS>:/home/hadoop/data/
scp -i pem_file 20180802.csv.out hadoop@<primary node public DNS>:/home/hadoop/data/

SCP is like a secure courier: -i pem_file is your ID badge, hadoop@<DNS> is the recipient's address, and /home/hadoop/data/ is the mailbox on the cluster.


3. Connect to Hive CLI with ssh

  • Connect to EMR with ssh with user: hadoop
  • Run command hive to access the Hive shell
  • Run initial commands:
    • Show header
    • Enable dynamic partition
$ hive
Logging initialized using configuration in file:/etc/hive/2.6.5.1100-53/0/hive-log4j.properties
hive> set hive.cli.print.header=true;
hive> set hive.exec.dynamic.partition.mode=nonstrict;
hive> set hive.exec.dynamic.partition=true;

  • Dynamic partition = Hive decides the partition value from the data itself (e.g. from a column in a SELECT), instead of you typing PARTITION (pdate='...') manually
  • nonstrict mode allows all partition columns to be dynamic

4. Create Table and Import Data

  • Create database and create table for storing raw taxi data
  • Database: taxidb
  • Table: taxi_raw_data with partition: date
create database taxidb;
Use taxidb;
 
CREATE TABLE taxi_raw_data (vehicle_id string, gps_valid int, lat double, lon double, gps_time string, speed double, heading int, meter int, engine int)
PARTITIONED BY (PDATE string)
ROW FORMAT DELIMITED
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
STORED AS TEXTFILE;
  • Import data (one partition per day)
load data local inpath '/home/hadoop/data/20180801.csv.out' overwrite into table taxi_raw_data
partition (pdate='2018-08-01');
 
load data local inpath '/home/hadoop/data/20180802.csv.out' overwrite into table taxi_raw_data
partition (pdate='2018-08-02');
  • Check data
SELECT PDATE, count(*) as total, count(distinct vehicle_id) as totalvehicle
FROM taxi_raw_data
GROUP BY PDATE
ORDER BY PDATE;
  • Expected result (from the earlier "How It Works" run): 2018-08-01 → 3,181,459 records / 5,931 vehicles; 2018-08-02 → 2,781,095 records / 5,942 vehicles

4. Create Table and Import Data: Check Result

  • Running the check query in the Hive CLI:
hive> select PDATE,count(*) as total, count(distinct vehicle_id) as totalvehicle
    > from taxi_raw_data
    > group by pdate order by pdate;
Status: Running (Executing on YARN cluster with App id application_1696437795605_0003)
Map 1 .......... container     SUCCEEDED      9          9   ...
Reducer 2 ...... container     SUCCEEDED      2          2   ...
Reducer 3 ...... container     SUCCEEDED      1          1   ...
VERTICES: 03/03  [==========================>>] 100%  ELAPSED TIME: 40.72 s
OK
pdate       total    totalvehicle
2018-08-01  3181459  5931
2018-08-02  2781095  5942
Time taken: 54.471 seconds, Fetched: 2 row(s)


5. Calculate Statistics for Data Quality Check

  1. How many data in the system?
Select count(*) from taxi_raw_data;
  1. How many days of data?
Select count(distinct to_date(gps_time)) from taxi_raw_data;
  1. How many data for each day?
Select to_date(gps_time) as dateonly, count(*) from taxi_raw_data group by to_date(gps_time)
order by dateonly;
  1. How many unique taxis for each day?
Select to_date(gps_time) as dateonly, count(distinct vehicle_id) from taxi_raw_data group by
to_date(gps_time);
  1. Find min, max, avg speed by hour
select hour(gps_time) as hour24,
       min(speed) as min_speed, max(speed) as max_speed, avg(speed) as avg_speed
from taxi_raw_data
group by hour(gps_time)
order by hour24;
  • Note: these use to_date(gps_time) (date from the actual GPS timestamp) instead of the partition pdate → helps detect records whose real date doesn't match the file/partition date (a data quality issue)

Data quality check is like counting the groceries after delivery: how many items, how many days' worth, per-day counts, and "does anything look weird?" (e.g. a taxi going 500 km/h).


6. Preprocessing (if necessary)

  • Here are some examples of preprocessing tasks:

  • Clear data issue

    • Convert date time format
    • Clear missing data: null, zero
    • Clear noise data: location (latitude, longitude) out of scope, incorrect time
  • Mapping data

    • Mapping geo location to administrative boundary
    • Aggregate data to be more meaningful, such as creating trips with customer and no customer
  • Recall the Hive way to "update": create a new table with insert from select, e.g. a cleaned table built from the raw table with filters in WHERE


7. Ready for Analysis

  • Taxi Data Analytics
    • Daily active taxi
    • Average distance for taxi trip with customer
    • Average time/distance for taxi with no customer
    • Hotspot area for pickup/drop off customer
    • Customer demand by time period
    • Income analysis by trips

Apache Hue (Hadoop User Experience)

  • It is a web-based interactive query editor that enables you to interact with databases and data warehouses. Data architects, SQL developers, and data engineers use Hue to create data models, clean data to prepare it for analysis, and to build and test SQL scripts
  • Hue is integrated with Apache Hive. You can access Hue from EMR (port 8888)
  • Architecture: Hue UI ↔ Hue Server ↔ Hue DB; Hue Server connects to apps:
    • Job Browser → YARN, JobTracker (Hue Plugins)
    • Job Designer, Oozie Editor → Oozie
    • Pig Editor → Pig
    • File Browser → HDFS
    • Beeswax (Hive UI) → HiveServer2, Hive Metastore
    • Metastore Manager → Hive Metastore
    • Cloudera Impala Query UI → Cloudera Impala
    • Shell (Sqoop2, HBase, Pig) → HBase, Sqoop2

Hue is the "dashboard of the car" for Hadoop — instead of opening the hood (ssh + CLI), you get buttons and screens for queries, files, and jobs.


Hue: Hive Editor

  • User-friendly and convenient Hive query capabilities, enabling you to select different Hive databases, write HQL statements, submit query tasks, and view results with ease
  • Open via Query → Editor → Hive (other editors: Scala, PySpark, R, Spark Submit Jar, Spark Submit Python, Text)
  • Left panel: Database lists (e.g. default, tpds, tpds_orc); click a database to see its tables and columns
  • Write a query (e.g. select * from tpds.date_dim limit 5;), click Run (▶), and see the Results tab (also Query History, Saved Queries, Query Builder)

  • Example in taxidb: running the check query
SELECT PDATE, count(*) as total, count(distinct vehicle_id) as totalvehicle
FROM taxi_raw_data
GROUP BY PDATE
ORDER BY PDATE;
  • Left panel shows table taxi_raw_data with columns: vehicle_id (string), gps_valid (int), lat (double), lon (double), gps_time (string), speed (double), heading (int), meter (int), engine (int), pdate (string)
  • Log shows Map/Reducer progress (e.g. Map 1: 10/10 Reducer 2: 1(+1)/2 Reducer 3: 0(+1)/1); results: 2018-08-01 → 3181459 / 5931, 2018-08-02 → 2781095 / 5942 (37.39 s)

  • Results can be shown as a chart: TYPE = Bars, X-AXIS = pdate, Y-AXIS = totalvehicle → bar chart of ~5.9k vehicles for each of 2018-08-01 and 2018-08-02


Hue: HDFS Access and File Browsing

  • Hue's web UI makes it easy to view files and folders in HDFS and perform operations such as creation, download, upload, copy, modification, and deletion
  • Entry: left menu Browsers → Files
  • File Browser actions:
    • Actions menu → Rename, Move, Copy, Change owner/group, Change permissions, Summary, Compress
    • Move to trash → delete a file
    • Upload → upload a file
    • New → create a file / directory


Hue: Job Management

  • Click the Jobs tab on the right (top bar) to enter the job management page — access YARN job lists. Then click a job type tab at the top to view and manage jobs
  • Job Browser tabs: Jobs, Workflows, Schedules, Bundles, SLAs, Livy
  • Filters: user, Succeeded / Running / Failed in the last N days; Kill button for running jobs
  • Example completed job: HIVE-... by user hadoop, Type TEZ, Status SUCCEEDED, Progress 100%, Duration 5m 12s


Summary

  • Hive Concept
  • Hive Data Model
    • Table, Partition, Bucket
    • Data Type
    • File Format: ORC
  • Basic HiveQL
    • Database, Table
    • Load, Select
  • Hive Analytic Function
    • Windows, Lead, Lag
  • Hive Custom Function
  • Access Hive
    • CLI, Python, Java, Web
  • Hive Processing Step
  • Apache Hue - GUI

Big picture: Hive = "SQL on top of Hadoop". You define a table (schema on read) over files in HDFS, Hive's Driver compiles your HiveQL into MapReduce/Tez jobs on YARN, and you use partitions/buckets/ORC to make it fast. Hue is the friendly web window into all of it.