Module 4 Notes
Module 4 Notes
UNIT-V
MapReduce Working
Objective:
To familiarize with the working of Map Reduce in Hadoop.
Syllabus:
MapReduce Working
Classic MapReduce, Job submission, Job Initialization, Task Assignment, Task
execution, Progress and status
updates, Job completion, Shuffle and sort on Map and Reduce side, Configuration
tuning, Map Reduce types,
1) If this configuration property is set to local, the default, then the local job
runner is used. This runner runs the whole job in a single JVM.
IV-II SEMESTER 2018-19 CSE
Big Data 2
2)It’s designed for testing and for running MapReduce programs on small
datasets.
3) If [Link] is set to a colon-separated host and port pair, then
the property is interpreted as a jobtracker address, and the runner
submits the job to the jobtracker at that address.
5.1 Classic MapReduce (MapReduce 1)
2. The jobtracker, which coordinates the job run. The jobtracker is a Java
application whose main class is JobTracker.
3. The tasktrackers, which run the tasks that the job has been split
into. Tasktrackers are Java applications whose main class is
TaskTracker.
Fig : How Hadoop runs a MapReduce job using the classic framework
IV-II SEMESTER 2018-19 CSE
Big Data 3
1. Job Submission
2. Job Initialization
3. Task Assignment
4. Task Execution
6. Task Completion
5.2 Job Submission
The submit() method on Job creates an internal JobSummitter instance and
calls submitJobInternal() on it (step 1 in Figure).
After submitted the job, waitForCompletion() polls the job’s progress once a
second and reports the progress to the console.
When the job is complete, if it was successful, the job counters are
displayed. Otherwise, the error that caused the job to fail is logged to the
console.
▪ Asks the jobtracker for a new job ID (by calling getNewJobId() on obTracker)
(step 2).
▪ Checks the output specification of the job. For example, if the output
directory has not been specified or it already exists, the job is not submitted
and an error is thrown to the MapReduce program.
▪ Computes the input splits for the job. If the splits cannot be computed,
because the input paths don’t exist, for example, then the job is not
submitted and an error is thrown to the MapReduce program.
▪ Copies the resources needed to run the job, including the job JAR file, the
configuration file, and the computed input splits, to the jobtracker’s
filesystem in a directory named after the job ID.
▪ The job JAR is copied with a high replication factor (controlled by the
[Link] property, which defaults to 10) so that there are
lots of copies across the cluster for the tasktrackers to access when they
run tasks for the job (step 3).
▪ Tells the jobtracker that the job is ready for execution (by calling
submitJob() on JobTracker) (step 4).
Initialization involves
creating an object to represent the job being run, which encapsulates its
tasks, and
1. To create the list of tasks to run, the job scheduler first retrieves the input
splits computed by the client from the shared filesystem (step 6).
4. Tasks are given IDs at this point. In addition to the map and reduce tasks,
two further tasks are created: a job setup task and a job cleanup task.
5. These are run by tasktrackers and are used to run code to setup the job
before any map tasks run, and to clean up after all the reduce tasks are
complete.
6. The OutputCommitter that is configured for the job determines the code to
be run, andby default this is a FileOutputCommitter.
7. For the job setup task it will create the final output directory for the job and
the temporary working space for the task output, and for the job cleanup
task it will delete the temporary working space for the task output.
5.4 Task Assignment
• Tasktrackers run a simple loop that periodically sends heartbeat method
calls to the jobtracker.
• Heartbeats tell the jobtracker that a tasktracker is alive, but they also
double as a channel for messages.
• Before it can choose a task for the tasktracker, the jobtracker must choose a
job to select the task from. There are various scheduling algorithms but the
default one simply maintains a priority list of jobs.
• Having chosen a job, the jobtracker now chooses a task for the job.
Tasktrackers have a fixed number of slots for map tasks and for reduce
tasks:
Ex: a tasktracker may be able to run two map tasks and two reduce tasks
simultaneously. (The precise number depends on the number of cores and
the amount of memory on the tasktracker)
• The default scheduler fills empty map task slots before reduce task slots, so
if the tasktracker has at least on empty map task slot, the jobtracker will
select a map task; otherwise, it will select a reduce task.
• To choose a reduce task, the jobtracker simply takes the next in its list of
yet-to-be-run reduce tasks, since there are no data locality considerations.
• In the optimal case, the task is data-local, that is, running on the same node
that the split resides on.
• Alternatively, the task may be rack-local: on the same rack, but not the same
node, as the split. Some tasks are neither data-local nor rack-local and
retrieve their data from a different rack from the one they are running on.
• You can tell the proportion of each type of task by looking at a job’s
counters.
• Now that the tasktracker has been assigned a task, the next step is for it to
run the task.
• First, it localizes the job JAR by copying it from the shared filesystem to the
tasktracker’s filesystem.
It also copies any files needed from the distributed cache by the application
to the local disk.
• Second, it creates a local working directory for the task, and un-jars the
contents of the JAR into this directory.
• The child process communicates with its parent through the umbilical
interface. This way it informs the parent of the task’s progress every few
seconds until the task is complete.
• Each task can perform setup and cleanup actions, which are run in the same
JVM as the task itself, and are determined by the OutputCommitter for the
job
• The cleanup action is used to commit the task, which in the case of file-based
jobs means that its output is written to the final location for that task.
• The commit protocol ensures that when speculative execution is enabled, only
one of the duplicate tasks is committed and the other is aborted.
Fig : The relationship of the Streaming and Pipes executable to the tasktracker
and its child
• Both Streaming and Pipes run special map and reduce tasks for the purpose
of launching the user-supplied executable and communicating with it (Fig).
• In the case of Streaming, the Streaming task communicates with the process
(which may be written in any language) using standard input and output
streams.
• The Pipes task, on the other hand, listens on a socket and passes the C++
process a port number in its environment, so that on startup, the C++
process can establish a persistent socket connection back to the parent Java
Pipes task.
• In both cases, during execution of the task, the Java process passes input
key-value pairs to the external process, which runs it through the user-
defined map or reduce function and passes the output key-value pairs back
to the Java process.
• MapReduce jobs are long-running batch jobs, taking anything from minutes
to hours to run.
• Progress reporting is important for the user to get feedback on how the job
is progressing.
• These statuses change over the course of the job, they get communicated
back to the client regarding progress by displaying
• For map tasks, the proportion of the input that has been processed.
• If a task reports progress, it sets a flag to indicate that the status change
should be sent to the tasktracker.
• The flag is checked in a separate thread every three seconds, and if set it
notifies the tasktracker of the current task status.
• The status of all the tasks being run by the tasktracker is sent in the call.
• Counters are sent less frequently than every five seconds, because they can
be relatively high-bandwidth.
• Finally, the Job receives the latest status by polling the jobtracker every
second.
• When the jobtracker receives a notification that the last task for a job is
complete it changes the status for the job to “successful.”
• Then, when the Job polls for status, it learns that the job has completed
successfully, it prints a message to tell the user and then returns from the
waitForCompletion() method.
• Last, the jobtracker cleans up its working state for the job and instructs
tasktrackers to do the same (so intermediate output is deleted, for example).
• MapReduce makes the guarantee that the input to every reducer is sorted
by key.
• The process by which the system performs the sort—and transfers the map
outputs to the reducers as inputs—is known as the shuffle.
• When the map function starts producing output, it is not simply written to
disk. The process is more involved, and takes advantage of buffering writes
in memory and doing some presorting for efficiency reasons.
• Map outputs will continue to be written to the buffer while the spill takes
place, but if the buffer fills up during this time, the map will block until the
spill is complete.
• Before it writes to disk, the thread first divides the data into partitions
corresponding to the reducers to send.
• Running the combiner function makes more compact map output, so less
data to write to local disk and to transfer to the reducer.
• Each time the memory buffer reaches the spill threshold, a new spill file is
created
• Before the task is finished, the spill files are merged into a single partitioned
and sorted output file.
• If there are at least three spill files then the combiner is run again before the
output file is written.
• The output file’s partitions are made available to the reducers over HTTP.
• The maximum number of worker threads used to serve the file partitions is
controlled by the [Link] property. The default of 40 may
need increasing for large clusters running large jobs.
Shuffle and sort on Reduce Side
The map output file is sitting on the local disk of the machine that ran the map
task. The reduce task needs the map output for its particular partition from
several map tasks across the cluster.
There are three phases for reducer 1) copy phase 2) sort phase 3) reduce phase.
1)Copy phase:
• The map tasks may finish at different times, so the reduce task starts
copying their outputs as soon as each completes.
• The reduce task has a small number of copier threads so that it can fetch
map outputs in parallel.
• The default is five threads, but this number can be changed by setting
the [Link] property.
• The map outputs are copied to reduce task JVM’s memory otherwise,
they are copied to disk.
• When all the map outputs have been copied, the reduce task moves into
the sort phase.
2)Sort phase:
• In this phase merge the map outputs, maintaining their sort
ordering.
• These five files into a single sorted file, the merge saves a trip to disk
by directly feeding the reduce function. This final merge can come
from a mixture of in-memory and on-disk segments.
3)Reduce phase:
• During the reduce phase, the reduce function is invoked for each key
in the sorted output.
• There is a trade-off, in that you need to make sure that your map and
reduce functions get enough memory to operate.
• The amount of memory given to the JVMs in which the map and reduce
tasks run is set by the [Link] property.
• To make this as large as possible for the amount of memory on your task
nodes.
On the map side
• The best performance can be obtained by avoiding multiple spills to disk;
one is optimal.
• If you can estimate the size of your map outputs, then you can set the
[Link].* properties appropriately to minimize the number of spills.
• By default, this does not happen, since for the general case all the memory
is reserved for the reduce function.
• The map input key and value types (K1 and V1) are different from the map
output types (K2 and V2).
• The reduce input must have the same types as the map output, although
the reduce output types may be different again (K3 and V3).
The Java API mirrors this general form:
public class Mapper<KEYIN, VALUEIN, KEYOUT, VALUEOUT> {
// ...
IOException, InterruptedException {
// ...
}
}
• The context objects are used for emitting key-value pairs, so they are
parameterized by the output types, so that the signature of the write()
method is:
• The map output types and the reduce input types must match
If combiner function is used, then it is the same form as the reduce function
(and is an implementation of Reducer), except its output types are the
intermediate key and value types (K2 and V2), so they can feed the reduce
function:
• The partition function operates on the intermediate key and value types (K2
and V2), and returns the partition index.
In Java:
}
5.11 Input Formats
Hadoop can process many different types of data formats, from flat text files
to databases.
• Each split is divided into records, and the map processes each record—a
key-value pair—in turn.
• It provides two things: a place to define which files are included as the input
to a job, and an implementation for generating splits for the input files.
FileInputFormat input paths:
• The input to a job is specified as a collection of paths, which offers great
flexibility in constraining the input to a job.
• To exclude certain files from the input, you can set a filter using the
setInputPathFilter() method
public static void setInputPathFilter(Job job, Class<? extends
PathFilter> filter)
• FileInputFormat splits only large files. Here “large” means larger than an
HDFS block. The split size is normally the size of an HDFS block.
Preventing splitting:
• There are a couple of ways to ensure that an existing file is not split.
First way is to increase the minimum split size to be larger than the largest
file in your system. Second way is to subclass the concrete subclass of
FileInputFormat that you want to use, to override the isSplitable() method to
return false.
TextInputFormat:
• TextInputFormat is the default InputFormat. Each record is a line of input.
• The key, a LongWritable, is the byte offset within the file of the beginning of
the line.
• The value is the contents of the line, excluding any line terminators
(newline, carriage return), and is packaged as a Text object.
KeyValueTextInputFormat:
• TextInputFormat’s keys, being simply the offset within the file, are not
normally very useful.
NLineInputFormat:
• N refers to the number of lines of input that each mapper receives.
• With N set to one, each mapper receives exactly one line of input.
[Link] property controls the value of
N.
Ex: N is two, then each split contains two lines. One mapper will receive the
first two key-value pairs:
And another mapper will receive the second two key-value pairs:
• SequenceFileAsTextInputFormat: SequenceFileAsTextInputFormat is
a variant of
• SequenceFileAsBinaryInputFormat: SequenceFileAsBinaryInputFormat
is a variant of
1) Text Output:
• The default output format, TextOutputFormat, writes records as lines of
text.
• Its keys and values may be of any type, since TextOutputFormat turns
them to strings by calling toString() on them.
• SequenceFileAsBinaryOutputFormat:
SequenceFileAsBinaryOutputFormat is the counterpart to
SequenceFileAsBinaryInput Format, and it writes keys and values in raw
binary format into a SequenceFile container.
3) Multiple Outputs:
• There is one file per reducer, and files are named by the partition number:
part-r-00000, partr-00001, etc.
Zero reducers: There are no partitions, as the application needs to run only
map tasks.
One reducer: It can be convenient to run small jobs to combine the output
of previous jobs into a single file when the amount of data is small enough
to be processed.
MultipleOutputs:
• MultipleOutputs allows you to write data to files whose names are derived
from the output keys and values.
• This allows each reducer (or mapper in a map-only job) to create more than
a single file.
• File names are of the form name-m-nnnnn for map outputs and name-r-
nnnnn for reduce outputs
• The part number ensures that outputs written from different partitions
Lazy Output:
• FileOutputFormat subclasses will create output (part-r-nnnnn) files, even if
they are empty.
• Some applications prefer that empty files not be created, which is where
LazyOutputFormat helps.
• It is a wrapper output format that ensures that the output file is Output
Formats created only when the first record is emitted for a given partition.
Database Output:
UNIT-V
Assignment-Cum-Tutorial Questions
SECTION-A
Objective Questions
1. Number of mappers is decided by the_____________. [ ]
A) Mapper specified by the programmer C) Input Splits
B) Available Mapper slots D) Input Format.
2. Map Reduce job can be written in_________. [ ]
A) Java C) Pyton
B) Ruby D) Any Language which can read from input stream
3. YARN also called as_________________. [ ]
A)MapReduce1 B) MapReduce2 C) MapReduce3 D) None
4. Expansion of YARN___ Yet Another Resource Navigator [T/F]
5. Classic MapReduce frame work also called as______ [ ]
A)MapReduce1 B) MapReduce2 C) MapReduce3 D) None
6. Input to every reducer is sorted by________ [ ]
A) Value B) key C) Both key-value pair D) key or value
7. The process of that performs sort and transfers the map outputs to the
reducers as input is ____________. [ ]
A) sort B) copy C) shuffle D) transfer
8. The default buffer size________. [ ]
A) 100MB B)64MB C)512MB D)128MB
9. Processing a whole file as a record by using isSplitable method that return
false. [T/F]
10. Number of copier threads can be changed by setting_____property.
[Link] amount of memory given to the JVM in which the map and reduce tasks
run is set by the ___________ property. [ ]
A) [Link] C) [Link]
B) [Link] D) None
12. Spills are written in ___________ fashion. [ ]
A) Sequence B) Round-Robin C) FCFS D) None
SECTION-B
SUBJECTIVE QUESTIONS
1. Define shuffle and sort? Why it is required?
2. Write the general form of map and reduce functions and also writ the JAVA API
mirrors this general form.
3. Explain Map side Tuning properties in configuration tuning.
4. What constitutes progress in MapReduce? Explain
5. Illustrate reduce side tasks in shuffle and sort
6. What is input split? How to represent input splits? Which methods are used to
get location and length of input splits.
7. Explain how to control split size with example.
8. Elaborate classic frame work to run a Mapreduce job in Hadoop
9. Draw and explain inputformat class hierarch
10. Differentiate TextInputFormat and KeyValueTextInputFormat
11. List the Reduce-side tuning properties in configuration tuning.
12. How status updates are propagated through the MapReduce 1 system
13. Draw and explain outputformat class hierarchy
14. List the Binary output formats supported by hadoop.
15. Examine the relationship of streaming and pipes executable to the tasktracker
and its child.
HIVE
HIVE
Hive is not
A relational database
A design for online transaction processing(OLTP)
A language for real time queries and row level updates
Features of hive
It stores schema in a database and processed data into HDFS
It is designed for OLAP
It provides SQL type language for querying called HiveQL or HQL
It is familiar, fast, scalable, and extensible
The shell is the primary way that we will interact with Hive, by issuing
commands in HiveQL. HiveQL is Hive’s query language, a dialect of SQL. It is
heavily influenced by MySQL, so if you are familiar with MySQL you should feel
at home using Hive.
When starting Hive for the first time, we can check that it is working by
listing its tables: there should be none. The command must be terminated with
a semicolon to tell Hive to execute it: Ex: hive> SHOW TABLES;
OK
Time taken: 10.425 seconds
Features of shell
It is possible to run the hive shell in non-interactive mode. The –f option runs
the commands in the specified file, ex: script.q,
% hive -f script.q
For short scripts, you can use the -e option to specify the commands inline, in
which case the final semicolon is not required:
% hive -e 'SELECT * FROM dummy'
OK
Other useful Hive shell features include the ability to run commands on the
host operating system by using a! Prefix to the command and the ability to
access Hadoop filesystems using the dfs command
5.2 Hive Services
The Hive shell is only one of several services that you can run using the hive
command.
You can specify the service to run using the --service option. Type hive –service
help to get a list of available service names; the most useful are described
below.
1. cli
The command line interface to Hive (the shell). This is the default service.
2. hiveserver
Runs Hive as a server exposing a Thrift service, enabling access from a range of
clients written in different languages. Applications using the Thrift, JDBC, and
ODBC connectors need to run a Hive server to communicate with Hive. Set the
HIVE_PORT environment variable to specify the port the server will listen on
(defaults to 10,000).
3. hwi
The Hive Web Interface.
4. Jar
The Hive equivalent to hadoop jar, a convenient way to run Java
applications that includes both Hadoop and Hive classes on the
classpath.
5. metastore
Using this service, it is possible to run the metastore as a standalone (remote)
process.
The Hive Thrift Client makes it easy to run Hive commands from a wide range
of programming languages. Thrift bindings for Hive are available for C++, Java,
PHP, Python, and Ruby.
JDBC Driver
Hive provides a Type 4 (pure Java) JDBC driver, defined in the class
[Link]. When configured with a JDBC URI of
The metastore is divided into two pieces: a service and the backing
store for the data. There are 3 different metastore configurations
1. Embedded metastore
By default, the metastore service runs in the same JVM as the Hive
service and contains an embedded Derby database instance backed by
the local disk. This is called the embedded metastore configuration
a simple way to get started with Hive
only one embedded Derby database can access the database files on disk
at any one time, which means you can only have one Hive session
if we open another session it attempts to open a connection to the
metastore i.e., trying to start a second session gives the error
o
This brings better manageability and security, since the database
tier can be completely firewalled off, and the clients no longer need
the database credentials.
Schema on read makes longer time for query execution
Transactions:
Hive doesnot support transactions.
Data Types
• Primitives include
1) numeric
2) boolean
3) string,
4) timestamp
1) arrays
2) maps
3) structures
then the table, including its metadata and its data, is deleted.
An external table behaves differently. You control the creation and deletion of
the data.
LOCATION '/user/tom/external_table';
Hive organizes tables into partitions, a way of dividing a table into coarse-
grained parts based on the value of a partition column, such as date. Tables or
partitions may further be subdivided into buckets, to give extra structure to the
data that may be used for more efficient queries.
Partitions
Hive organizes tables in to partitions.
[Link]-II-Semester 2018-19 CSE
BigData 12
A table named Tab1 contains employee data such as id, name, dept, and
yoj , need to retrieve the details of all employees who joined in 2012.
• if you partition the employee data with the year and store it in a separate
file, it reduces the query processing time.
1, gopal, TP,2012
2, kiran,HR,2012
3, kaleel,SC,2013
4,Prasanth,SC,20
/tab1/employeedata/2012/file2/tab1/employeedata/2013/file3
1, gopal, TP, 2012 3, kaleel,SC, 2013
Adding a Partition :-
We can add partitions to a table by altering the
table hive> ALTER TABLE employee
Renaming a Partition
Show Partition
Dropping a Partition
Buckets
It is a mechanism to query and examine random samples of data
[Link]-II-Semester 2018-19 CSE
BigData 14
Break data into a set of buckets based on a hash function of a ―bucket
column
Capability to execute queries on a sub-set of random data
Doesn’t automatically enforce bucketing
User is required to specify the number of buckets by
setting # of reducer Create and use table with Buckets
There are two dimensions that govern table storage in Hive: the row
format and the file format. The row format dictates how rows, and the
fields in a particular row, are stored
The file format dictates the container format for fields in a row. The
simplest format is a plain text file, but there are row-oriented and
column-oriented binary formats available,too.
The default storage format: Delimited text
When you create a table with no ROW FORMAT or STORED AS clauses,
the default format is delimited text, with a row per line.
The default row delimiter is not a tab character, but the Control-A
character from the set of ASCII control codes
The choice of Control-A, sometimes written as ^A in documentation,
came about since it is less likely to be a part of the field text than a tab
character.
>FROM
source;
Another way
• Multitable insert
it’s possible to have multiple INSERT clauses in the same query.
multitable insert is more efficient than multiple INSERT statements,
the source table need only be scanned once to produce the multiple,
disjoint outputs hive> FROM records2
There is a single source table (records2), but three tables to hold the
results from three different queries over the source.
The new table’s column definitions are derived from the columns
retrieved by the
SELECT
clause
Example
FROM source;
Alter TableAlter the attributes of a table such as changing its table
name, changing column names, adding columns, and deleting or
replacing columns.
Syntax
hive> ALTER TABLE employee REPLACE COLUMNS ( eid INT empid Int,
ename STRING name String);
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];
Examples:
DISTRIBUTE BY year
SORT BY year ASC, temperature
DESC;
hive> SELECT * FROM employee LIMIT 4;
5.8 querying data
Sorting and Aggregating
Sorting data in Hive can be achieved by use of a standard ORDER BY clause,
but there is a catch. ORDER BY produces a result that is totally sorted, as
expected, but to do so it sets the number of reducers to one, making it very
inefficient for large datasets.
In some cases, you want to control which reducer a particular row goes to,
typically so you can perform some subsequent aggregation. This is what Hive’s
DISTRIBUTE BY clause does. Here’s an example to sort the weather dataset by
year and temperature
SORT BY produces a sorted file per reducer.
hive> FROM records2
> SELECT year, temperature
> DISTRIBUTE BY year
import sys
> AS year,
temperature; 1949
111 1949 78 1950 0
1950 22
1950 -11
Before running the query, we need to register the script with Hive. This is so
Hive knows to ship the file to the Hadoop cluster
The query itself streams the year, temperature, and quality fields as a tab-
separated line to the is_good_quality.py script, and parses the tab-separated
output into year and temperature fields to form the output of the query.
This example has no reducers. If we use a nested form for the query, we can
specify a map and a reduce function. This time we use the MAP and REDUCE
keywords, but SELECT TRANSFORM in both cases would have the same
result. The source for the max_temperature_reduce.py script is shown in
Example
FROM
(FROMrecos
2
AS year, temperature)
map_output REDUCE year,
temperature USING
'max_temperature_reduce.py'
AS year, temperature;
Views
A view is a sort of ―virtual table that is defined by a SELECT statement.
Views can be used to present data to users in a different way to the way
it is actually stored on disk.
Views may also be used to restrict users access to particular subsets of
tables that they are authorized to see.
First create table and then insert data into it
Create View
Show views
Drop a view
hive> drop view
1stid;
Joins
JOIN is a clause that is used for combining specific fields from two tables
by using values common to each one.
used to combine records from two or more tables in the database.
similar to SQL JOINS.
There are different types of joins given as follows:
o
JOIN
o
LEFT OUTER JOIN
o
RIGHT OUTER JOIN
o
FULL OUTER JOIN
Can join multiple tables
Default join Is Inner join
Rows that do not have matches are not included in the result
The simplest kind of join is the inner join, where each match in the input
tables results in a row in the output table it is being joined to (things): hive>
SELECT * FROM sales;
joe 2
Hank 4
Ali 0
Eve 3
Hank 2
hive> SELECT * FROM things;
2 Tie
4 Coat
3 Hat
1 Scarf
hive> SELECT sales.*, things.*
Joe 2 2 Tie
Hank 2 2 Tie
Eve 3 3 Hat
Hank 4 4 Coat
The table in the FROM clause (sales) is joined with the table in the JOIN
clause (things), using the predicate in the ON clause
Hive only supports equijoins, which means that only equality can be
used in the join predicate, which here matches on the id column in both
tables.
the row for Ali did not appear in the output, since the ID of the item she
purchased was not present in the things table
Left Outer Join
Outer joins allow you to find non matches in the tables being joined.
If we change
the join type to LEFT OUTER JOIN, then the query will return a row for
every row in the left table (sales), even if there is no corresponding row in
the table it is being joined to (things):
Joe 2
Hank 4
Ali 0
Eve 3
Hank 2
2 Tie
4 Coat
3 Hat
1 Scarf
The row for Ali is now returned, and the columns from the things table are
NULL, since there is no match.
i.e Row from the first table are included whether they have a match or not.
Columns from the unmatched(second) table are set to null.
Right Outer Join
Opposite of Left Outer Join, Rows from the second table are included no
matter what. Columns from the unmatched (first) table are set to null.
all items from the things table are included, even those that weren’t
purchased by anyone
(a scarf):
hive> SELECT * FROM sales;
Joe 2
Hank 4
Ali 0
Eve 3
Hank 2
2 Tie
4 Coat
3 Hat
1 Scarf
We can perform left outer join on the two tables as follows:
hive> SELECT sales.*, things.*
Joe 2 2 Tie
Han 2 2
k Tie
Eve 3 3 Hat
Coa
Hak 4 4 t
Full Outer Join
Rows from both sides are includes. For unmatched rows the columns
from the other table are set to null
In full outer join, the output has a row for each row from both tables in
the join:
Ali
Joe
HanEve
Hank
0 NULL NULL
2 2 Tie
2 2 Tie
3 3 Hat
4 4 Coat
Subqueries
A subquery is a SELECT statement that is embedded in another SQL
statement.
Hive has limited support for subqueries
The query finds the mean maximum temperature for every year and weather
station:
FROM (
) mt
GROUP BY station, year;
The subquery is used to find the maximum temperature for each
station/date combination,
the outer query uses the AVG aggregate function to find the average of
the maximum temperature readings for each station/date combination.
The outer query accesses the results of the subquery like it does a table,
which is why the subquery must be given an alias (mt).
The columns of the subquery have to be given unique names so that the
outer query can refer to them.
5.9 User-Defined functions
Write the query that can’t be expressed easily using built-in functions.
Write a User-Defined Function(UDF) .
Easy to plug in own processing code and invoke it from a Hive Query.
There are 3 types of UDF in Hive
1) Regular UDFs
Operates on a single row and produces a single row as its output. Ex:
Mathematical and String functions
Write a User-Defined Function(UDF) .
Easy to plug in own processing code and invoke it from a Hive Query.
There are 3 types of UDF in Hive
2) Regular UDFs
Operates on a single row and produces a single row as its output. Ex:
Mathematical and String functions
4) UDAF (User-defined aggregate functions)
o
works on multiple input rows and creates a single output row.
o
Aggregate functions include such functions as COUNT and MAX.
UNIT-VI
Assignment-Cum-Tutorial Questions
SECTION-A
Objective Questions
1. Which of the following command sets the value of a particular configuration
variable [ ]
A) Set-v B) set <key>=<value> C) set D) reset
2. Which of the following operator executes a shell command from the Hive
shell? [ ]
A) | B) ! C^ D) +
3. Which of the following will remove the resource(s) from the distributed
cache? [ ]
A) Delete FILE[S] <filepath>*
B) Delete JAR[S]<filepath>*
C) Delete ARCHIVE[S]<filepath>*
D) All
4. ________ is a shell utility which can be used to run Hive queries in either
interactive or batch mode. [ ]
A) $HIVE/bin/hive
B) $HIVE_HOME/hive
C) $HIVE_HOME/bin/hive
D) All
5. Which of the following is a command line option? [ ]
A) –d,-define <key=value>
B) –e,-define<key=value>
C) –f,-define<key=value>
D) None
6. Hive uses___________ for logging [ ]
A)logj4 B) log41 C) log4i D) log4j
7. Hive Server2 introduced in HIVE 0.11 has new CLI called [ ]
A) BeeLine B) SQLLine C)HIVELine D) CLILine
8. Hcatalog is installed with HIVE, starting with HIVE relase [ ]
A) 0.10.0 B) 0.9.0 C)0.11.0 D)0.1.20
9. _____ supports a new command shell Beeline that works with HIVE Server2.
[ ]
A) HiveServer2 B) HiveServer3 C) HiveServer4 D) None
10. In _______ mode HiveServer2 only accepts valid Thrift calls. [ ]
A) Remote B) HTTP C) Embedded D) Interactive
11. Hive specific commands can be run from Beeline, When the Hive _____
driver is used. [ ]
A) ODBC B) JDBC C) ODBC-JDBC D) ALL
12. The ___ allow users to read or write Avro data s Hive Table [ ]
A) AvroSerde B) HiveSerde C) SQLSerde D) None
13. Starting in Hive_____ the Avro schema can be inferred from the hive table
schema. [ ]
A) 0.14 B) 0.12 C) 0.13 D) 0.11
14. Which of the following data type is supported by HIVE [ ]
A) map B) record C) string D) enum
15. which of the following data type is converted to Array prior to Hive 0.12.0
[ ]
A) map B) long C) float D) bytes
[Link]-backed tables can simply be created by using _________ in a DDL
statement. [ ]
A) “STORED AS AVERO” C. –STORED AS AVROHIVE
B) –STORED AS HIVE D. –STORED AS SERED
17. Types that may be null must be defined as a ___________ of that type and
NULL within AVRO. [ ]
A) Union B) intersection C) Set D) All
18. use_____ and embed the schema in the create statement [ ]
A) [Link] B) [Link] C) [Link] D) All
19. Serialization of string columns uses a____ to form unique column values.
A) Footer B) STRIPES C) Dictionary D) Index
20. Hive uses________ -Style escaping within the strings [ ]
A) C B) JAVA C) python D) Scala
SECTION-B
SUBJECTIVE QUESTIONS
1. What is hive? List the features of hive?
2. List out hive Services
3. What is metastore? What are different types of metastores?
4. What are megastore configuration properties?
5. Comapre the SQL and HIVEQL
6. List out Hive Data Types?
7. Explain about partitions and buckets?
8. Outline about Querying Data?
9. What are user-defined functions?
10. Explain joins?
11. Explain about HIVEQL in Hadoop System
12. Illustrate the HIVE Shell?
13. Describe about the tables in HIVE.
14. Explain about HIVE architecture?
15. Compare HIVE with traditional database?
16. Elaborate on HIVE QL data manipulation and queries in details
17. Discuss about the relationship between HIVE clients and HIVE Services
with a neat diagram?
18. Explain in detail about Map side and Reduce Side joins.