[Solved] Hive : Optimize a long running Query

EverSQL Database Performance Knowledge Base

Hive : Optimize a long running Query

A simple Hive SQL query run on a 50GB size employee log table is running for hours.

select dept,count(distinct emp_id) from emp_log group by dept;    

There are just 4-5 departments and a huge number of employees per department.

It was run with Hive 0.14 + Tez on 1TB memory. Is there any way to optimize this code block for better performance?

Modification 1
Tested with collect_list replacing distinct.

SELECT dept, size(collect_list(emp_id)) nb_emps FROM emp_log GROUP BY dept

Got the below error,
Status: Failed Vertex failed, vertexName=Reducer 2,vertexId=vertex_1446976653619_0043_1_02, diagnostics=[Task failed,taskId=task_1446976653619_0043_1_02_000282, diagnostics=[TaskAttempt 0 failed, info=[Error: Failure while running task:java.lang.RuntimeException: java.lang.OutOfMemoryError: Java heap space

How to optimize this SQL query?

The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:

  1. Description of the steps you can take to speed up the query.
  2. The optimal indexes for this query, which you can copy and create in your database.
  3. An automatically re-written query you can copy and execute in your database.
The optimization process and recommendations:
  1. Create Optimal Indexes (modified query below): The recommended indexes are an integral part of this optimization effort and should be created before testing the execution duration of the optimized query.
  2. Explicitly ORDER BY After GROUP BY (modified query below): By default, the database sorts all 'GROUP BY col1, col2, ...' queries as if you specified 'ORDER BY col1, col2, ...' in the query as well. If a query includes a GROUP BY clause but you want to avoid the overhead of sorting the result, you can suppress sorting by specifying 'ORDER BY NULL'.
Optimal indexes for this query:
ALTER TABLE `emp_log` ADD INDEX `emp_log_idx_dept` (`dept`);
The optimized query:
SELECT
        emp_log.dept,
        count(DISTINCT emp_log.emp_id) 
    FROM
        emp_log 
    GROUP BY
        emp_log.dept 
    ORDER BY
        NULL

Related Articles



* original question posted on StackOverflow here.