HIVE Efficient Queries and JOINS OPTIMIZATION
For Efficient Queries:
In real time we will query lot of data to mining the
important pattern which results in Improving the business.We always come across
lot of problems in optimizing the jobs.
1)Data
Layout (Partitions and Buckets)
2)Data Sampling (Bucket and Block sampling) and 3)Data
Processing (Bucket Map Join and Parallel execution)
1 Partitions on Hive tables : We have to observe on which part of our table
will undergo for search. So,on that columns it is good to create partitions
which stops MR job to launch for scanning entire file.
Bucketing
Hive Tables: We can optimize joins
by bucketing ‘similar’ IDs so Hive can minimise the processing steps, and
reduce the data needed to parse and compare for join operations.
Bucket Sampling:
We often want to query
large table joins for a sample. We may want to try out complex queries or
explore the data, and we want to do this iteratively, swiftly, and not process
the whole data set. This is particularly difficult because of the joining of
the tables since only very little data may overlap on independent samples from
two tables. Ideally we would want to sample the relevant data on both tables
and join it, i.e. ensure that we sample the same itinerary IDs from both tables
and not sets with no or little overlap. The bucketing on the join column
enables us to join specific buckets from two tables with data overlapping on
the join column. Effectively, we execute exactly one part of the complete join
operation and only incur the cost of it. The hashing function on the ID has the
additional benefit of a (somewhat) random nature providing a representative
sample.
Block
Sampling: Block sampling provides a powerful syntax to
define various ways of sampling the data in a table with the TABLE SAMPLE statement. We can use it to sample a certain percentage, number of bytes, or
rows of the data. We can use the sampling to approximate information like
average distance between origin and destination of our itineraries. A query
using 1% of the data using TABLE SAMPLE(1 PERCENT) on a large table will give us
a near perfect answer and use up to only a hundredth of the resource and return
the result one to two magnitudes faster.
Parallel
Execution: Hadoop can execute map
reduce jobs in parallel and several queries executed on Hive make automatically
use of this parallelism. However, single, complex Hive queries commonly are
translated to a number of map reduce jobs that are executed by default
sequentially. Often though some of a query’s map reduce stages are not
interdependent and could be executed in parallel. They then can take advantage
of spare capacity on a cluster and improve cluster utilization while at the
same time reduce the overall query executions time. The configuration in Hive
to change this behavior is a merely switching a single flag SET hive.exce.parallel=true;.
DISTRIBUTE BY…SORT BY v. ORDER BY
In Hive, ORDER BY is not a very
fast operation because it forces all the data to go into the same reducer node.
By doing this, Hive ensures that the entire dataset is totally ordered.
However, sometimes we do not require total ordering. For
example, suppose you have a table called user_action_table where each row
has user_id, action, and time. Your goal is to order them by
time per user_id.
If you are doing this with
ORDER BY, you would run
SELECT time,user_id,action FROM user_action_table ORDER BY
user_id,time
However, you can achieve
the same result with
SELECT time,user_id,action FROM user_action_table DISTRIBUTE BY
user_id SORT BY time
This is because all the
rows belonging to the same user_id go to the same reducer (“DISTRIBUTE BY
user_id”) and in each reducer, rows are sorted by time (“SORT BY time”). This
is faster than the other query because it uses multiple reducers as opposed to
a single reducer.
JOINS OPTIMIZATION
Hive,
like other SQL databases, allows users to join various tables. Joins; however,
can be computationally expensive, especially on big tables, and that’s
precisely why they deserve an entire tip of their own!
1
2
|
hive> CREATE TABLE t1 (id INT, name STRING, age INT);
hive> CREATE TABLE t2 (id INT, name STRING, age INT);
|
A
join query on the above tables would look like:
1
2
3
4
5
6
7
8
9
|
hive> SELECT
t1.id,
t1.name,
t1.age,
t2.name,
t2.age
FROM
t1
JOIN
t2 ON (t1.id = t2.id)
|
We
will now enumerate some of the best practices to use when performing joins in
Hive.
Equity Joins
Hive only supports
equality joins. This is primarily because it’s rather difficult to express
non-equality join conditions in MapReduce.
Stream
Table(Largest table last)
The
earlier example shows an inner join between two tables. Given that inner joins
are commutative; however, should the user prefer having t1 as the
left table and t2 as the right table or vice-versa? The answer to
this question lies in understanding how Hive compiles a join query to
MapReduce. In the MapReduce job for regular inner joins, mappers run on both
tables, emitting out records from that need to be joined by evaluating any UDFs
in the query and filtering out any records based on the where clause. Then the
shuffle phase is run which “shuffles” the keys based on the join key (idin
above example). Subsequently, in the reduce phase, essentially a cross-product
takes place between records from
each table
that have the same join key. During this reduce phase, records from all tables
but the last table (in the join query) are buffered in memory while the records
from query’s last table are streamed into the reducer. Consequently, in order
to reduce the memory required by reducers, it’s recommended to put the largest
tables last to ensure their records are streamed into the reducers.

Alternatively,
you can specify a hint in your query about which table to stream. In the above
example, if t1 is larger than t2, your query the hint for
streaming t1 would look like:
1
2
3
4
5
6
7
8
9
10
|
hive> SELECT
/*+
STREAMTABLE(t1) */
t1.id,
t1.name,
t1.age,
t2.name,
t2.age
FROM
t1
JOIN
t2 ON (t1.id = t2.id)
|
MAP
Joins
If one of the tables
in the join query is small enough to fit in memory, we recommend you to use map
join. Map join is a special type of join where the smaller table is loaded in
memory and the join is performed in the map phase of the MapReduce job. Since
no reducers are required, map joins are much faster compared to regular joins.
In the above example,
if t1 is small enough to fit in memory, the map join query would look
like:
1
2
3
4
5
6
7
8
9
10
|
hive> SELECT
/*+
MAPJOIN(t1) */
t1.id,
t1.name,
t1.age,
t2.name,
t2.age
FROM
t1
JOIN
t2 ON (t1.id = t2.id)
|
Starting Hive 0.7,
there is no need to specify the query hint (i.e. /*+ MAPJOIN(t1) */) for
map joins. Set the hive.auto.convert.join property to true in
hive-site.xml or your Hive CLI session, and Hive will use a conditional task to
determine if it is possible to run a map join instead of a regular join. If so,
it will run a map-join; if not, a regular join is run.
There are many topics
related to Hive joins like bucketed and sort-merge joins, left semi joins,
deciding between what goes in the “in” clause and what goes in the “where”
clause of an outer join query.
More Elaborated Way.(Thru Diagrams)
Using the Distributed Cache
Hive-1641 solves this scaling problem. The basic idea of optimization is to create a new MapReduce local task just before the original join MapReduce task. This new task reads the small table data from HDFS to an in-memory hash table. After reading, it serializes the in-memory hash table into a hashtable file. In the next stage, when the MapReduce task is launching, it uploads this hashtable file to the Hadoop distributed cache, which populates these files to each mapper's local disk. So all the mappers can load this persistent hashtable file back into memory and do the join work as before. The execution flow of the optimized map join is shown in figure 2. After optimization, the small table needs to be read just once. Also if multiple mappers are running on the same machine, the distributed cache only needs to push one copy of the hashtable file to this machine.
Since map join is faster than the common join, it's better to run the map join whenever possible. Previously, Hive users needed to give a hint in the query to specify the small table. For example,
select /*+mapjoin(a)*/ * from src1 x join src2 y on x.key=y.key;.
This isn't a good user experience because sometimes the user may give the wrong hint or may not give any hint at all. It's much better to convert the common join into a map join without user hints.
Converting Joins to Map Joins Based on Size
Hive-1642 solves this problem by converting the common join into a map join automatically. For the map join, the query processor should know which input table is the big table. The other input tables are recognized as the small tables during the execution stage, and these tables need to be held in the memory. However, in general, the query processor has no idea of input file size during compilation time because some of the tables may be intermediate tables generated from sub-queries. So the query processor can only figure out the input file size during the execution time.

As shown in figure 3, the left side flow shows the previous common join execution flow, which is very straightforward. On the other side, the right side flow is the new common join execution flow. During compilation time, the query processor generates a conditional task containing a list of tasks; one of these tasks gets resolved to run during execution time. First, the original common join task should be put into the task list. Then the query processor generates a series of map join tasks by assuming each of the input tables may be the big table. For example,
select * from src1 x join src2y on x.key=y.key. Because both tables src2 and src1 can be the big table, the processor generates two map join tasks, with one assuming src1 is the big table and the other assuming src2 is the big table.
During the execution stage, the conditional task knows the exact file size of each input table, even if the table is an intermediate one. If all the tables are too large to be converted into map join, then just run the common join task as previously. If one of the tables is large and others are small enough to run map join, then the conditional task will pick the corresponding map join local task to run. By this mechanism, it can convert the common join into a map join automatically and dynamically.
Currently, if the total size of small tables is larger than 25MB, then the conditional task will choose the original common join to run. 25MB is a very conservative number and you can change this number with set hive.smalltable.filesize.
No comments:
Post a Comment