Thursday, 16 November 2017

Analytic Functions in Hive - III

We will now take a look at more analytic functions continuing in the series. We will follow the post that we wrote before. For all our work, we will use the Mapr sandbox, MapR-Sandbox-For-Hadoop-5.2.0.

RANK as the name suggests ranks any measure in a query using sequential numbers starting from 1. If in the ranking process, a tie is encountered, then, the same rank is repeated for all values that tie and the next rank in sequence is used after skipping as many rank values as was repeated in the tie . Let us see that by means of an example. For starters, let us use the same hr.employees table used in the previous posts. We are interested only in the results of the below query:

select employee_id, last_name, department_id, salary from employees where employee_id <= 109 order by salary desc;

The results returned are shown below:  













The query returns ten records. Let us now run the first query using RANK shown below:

select employee_id, last_name, department_id, salary, rank() over (order by salary desc) as SALARY_RANK from employees where employee_id <= 109;

The results returned are shown below:  













The results are as written above: a tie is seen at 17000, so there is a repeat of ranks for 17000 and at the next value of 12008, rank value 3 is skipped for one repeat of 17000 and a rank of 4 is returned. Same is true for the salary value 9000 where rank of 6 is skipped.

DENSE_RANK is similar to RANK except that in case a of tie, the rank values are not skipped. Let us replace RANK with DENSE_RANK in above query to see this contrast.

select employee_id, last_name, department_id, salary, dense_rank() over (order by salary desc) as SALARY_DENSE_RANK from employees where employee_id <= 109;

The results returned are shown below: 













Results show that DENSE_RANK does not skip any values at all and ranks are repeated at ties. 

Let us add the partition keyword and see the results. The query using partition is show below:

select department_id, last_name, salary, rank() over (partition by department_id order by salary desc) as SALARY_RANK from employees where employee_id <= 109;

The results returned are shown below:













The results show that the RANK function is applied department wise. The same can be tried using DENSE_RANK as shown below:

select department_id, last_name, salary, dense_rank() over (partition by department_id order by salary desc)  as SALARY_DENSE_RANK from employees where employee_id <= 109;

The results returned are shown below:












The results are clearly in line with our understanding of DENSE_RANK as is seen in the ranking of Lorentz.

We will conclude this post with a query for 5 salaries as shown below:

select employee_id, last_name, department_id, salary from employees where employee_id <= 109 order by salary desc limit 5; 

The results returned are shown below:










Tuesday, 14 November 2017

Analytic Functions in Hive - II

In second part of the series on Analytic Functions in Hive, we will follow the blog that was written earlier for Oracle. For all our work, we will use the Mapr sandbox, MapR-Sandbox-For-Hadoop-5.2.0.

For starters, let us run the following query:

select count(*) from employees where department_id < 40;

The results returned are shown below:  













 The result is the same that we have got earlier.

Let us add the OVER keyword to this as shown below:

select count(*) over() from employees where department_id < 40;

The results returned are shown below:  























 
The results returned are the same as before.

The same result is now returned nine times. Since nothing is specified in the parenthesis following OVER, we see that OVER returns the results of COUNT nine times as there are nine rows that satisfy the filter clause without the COUNT and OVER clauses.

The same behaviour can be seen in the below query where we introduce a partition clause as shown below:

select department_id, count(*) over(partition by department_id) from employees where department_id < 40;

The results returned are shown below:  














The results returned are the same as before.

 A more meaningful query is shown below:

select distinct department_id, count(*) over(partition by department_id) from employees where department_id < 40;

The results returned are shown below: 













The results returned are not in line with the results got in the earlier blog for Oracle. While for the all previous queries, the results were the same, when we introduce the distinct keyword, the query in Hive gives incorrect results. After logging into the Mapr Virtual Machine as mapr/mapr, we can run the commands shown below to get the version of Hive as shown below:















Fortunately, we have a work around in the query below to get the correct result:

select department_id, count(*) from employees where department_id < 40 group by department_id; 

The results returned are shown below:









Now the results look good.


Now that we have seen how OVER() and OVER() with a PARTITION clause works, let us see next variant that can be used to Moving calculations. For all the variants shown hereafter, the calculations are dependent on the order of the rows of the result. The first query calculates the moving average
of the salary in the previous record and salary in current record:

select employee_id, first_name, last_name, salary, avg(salary) over (order by employee_id rows between 1 preceding and current row) as moving_avg_of_sal from employees where employee_id <= 105;

The results returned are shown below:












The results returned look the same that we have got before.

The moving average salary of the first row is the same as the salary of that row as there is no previous row. Others salaries are calculated according to the logic correctly.

The second query is similar to the first one with the only difference that the average is calculated based on three values: salary in previous row, salary in current row and salary in next row.

select employee_id, first_name, last_name, salary, avg(salary) over (order by employee_id rows between 1 preceding and 1 following) as moving_avg_of_sal from employees where employee_id <= 105; 

The results returned are shown below:  











The results returned are the same as before.

It is instructive to note that for the first and the last row in the result set, since there only two records, the averages of only two salaries are shown. 

The third query calculates the  moving average of salaries in all previous records.

select employee_id, first_name, last_name, salary, avg(salary) over (order by employee_id rows between unbounded preceding and current row) as moving_avg_of_sal from employees where employee_id <= 105;

The results returned are shown below:  










The results returned are the same as before.

We will next look at FIRST_VALUE. In the first query, we will fetch the lowest salary in departments with department_id 20 and 30. The query is shown below:

select employee_id, department_id, salary, first_value(salary) over (partition by department_id order by salary) as first_sal_in_dept from employees where department_id in (20,30);

The results returned are shown below:  












 As expected, we see that first_sal_in_dept gives the lowest salary in respective departments having department_ids 20 and 30.

We can fetch the highest salary by changing reversing the order of salary as shown below:

select employee_id, department_id, salary, first_value(salary) over (partition by department_id order by salary desc) as first_sal_in_dept from employees where department_id in (20,30);

The results returned are shown below:  













The results are on expected lines. In the case of LAST_VALUE, we get the same funny results we got in Oracle as shown below:

select employee_id, department_id, salary, last_value(salary) over (partition by department_id order by salary) as last_sal_in_dept from employees where department_id in (20,30);











For some reason, value in each row is considered the last value. To correct this, we have to add an additional clause indicating the extent of the application of LAST_VALUE like "rows between unbounded preceding and unbounded following". This will fetch the last value correctly as shown below where the highest salary is obtained:

select employee_id, department_id, salary, last_value(salary) over (partition by department_id order by salary rows between unbounded preceding and unbounded following) as last_sal_in_dept from employees where department_id in (20,30); 












In the same way, we can add desc keyword to the query as shown below to get the minimum salary in the two departments:

select employee_id, department_id, salary, last_value(salary) over (partition by department_id order by salary desc rows between unbounded preceding
and unbounded following) as last_sal_in_dept from employees where department_id in (20,30);












With this treatment of FIRST_VALUE and LAST_VALUE, we come to the close of the second part in this series.

Saturday, 11 November 2017

Analytic Functions in Hive - I


Now that we have written many articles on data related areas, it is time we look at Big Data. We will begin with an introduction to Hive.


Hive shares much in common with SQL, a fair share of analytical aspect of which we have already covered in a series before. In this post, we will try to rerun most the queries that we have attempted before. This will be useful for those who are looking to take a crack at Big Data. We will use sandbox provided by Mapr for all the Hive queries.

Before we start to run the queries, we will set up the tables that we will use as to demonstrate the analytic functions in Hive. Let us first get an extract of the employee table and department table from Oracle HR schema by performing an export in SQL developer in the form of .csv files containing data. These files can be imported into Mapr sandbox will be shown shortly. As a first step, set up the sandbox and navigate to http://127.0.0.1:8443/.
















Click on Launch Hue. On the "Quick Start Wizard - Hue™ 3.9.0 - The Hadoop UI" screen, click on File Browser to upload the data files exported earlier from Oracle.












On the File Browser screen, we can add the files using the Upload button. Once the files are uploaded, we can see the uploaded files at /user/mapr/ as shown below:










Since we have uploaded the files, we can now create tables based on the data. Navigate to "Metastore Manager" as shown below:













On the "Metastore Manager", click on Create a new file from a table. On the right hand side, enter the details as shown and click on Next button.














Examine the columns and data on the next screen and click Next button.













On the last screen in the process, ensure that "Use first row as column names" box is checked.  Note that based on the data, the data type is already suggested.














In the above screen, set the Column Type of DEPARTMENT_ID and COLUMN_ID columns to smallint. After this change change, the screen should look as below:
















Make any other modifications, if necessary. Otherwise, accept the other defaults and  click on Create Table button to create the table in Hive.

Once the process of table creation is over, we get to see below results.










Check out the Sample and Properties tab to see more details about the departments table.

In the same manner, let us try to create the employees table as well. On the way to the creation of this table, when we come to the last step to the table creation, we see that COMMISSION_PCT is a string and HIRE_DATE is not a date but a string.





















To correct this issue, we will create a staging table based on employee data file and then create a table in Hive that we will use for our queries. The reason for the intermediate staging table is that it will help us for any data clean up and help us with any data transformation so that the final table used for querying has the right schema and has the correct data.

The staging table will be in the form of an external table. But, the final table will be an internal table. The concept of external tables or internal tables in Hive is the same as it is in a relational database. Briefly, Hive does not manage the storage for an external table. Only the definition of an external table is maintained in Hive. So, if an external table is deleted, only the definition is deleted but not the data in the external file. On the other hand, both the definition and data are maintained in Hive for internal tables. So, if an internal table is deleted, both the definition and data are deleted.

Create a folder called employees to hold the employees.csv by clicking on New button and then Directory menu item as shown below:










Then, drag and drop the employees.csv file into the employees folder. The final directory structure should be as shown below:










Click on Hive under Query Editor menu to navigate to the Hive Query Editor.











On the Query Editor, click in the empty space below the query on the right to enter new queries.









Enter below query and click on Execute button:

CREATE EXTERNAL TABLE IF NOT EXISTS staging_employees (EMPLOYEE_ID SMALLINT, FIRST_NAME STRING, LAST_NAME STRING, EMAIL STRING, PHONE_NUMBER STRING, HIRE_DATE STRING, JOB_ID STRING, SALARY SMALLINT, COMMISSION_PCT DOUBLE, MANAGER_ID SMALLINT, DEPARTMENT_ID TINYINT) COMMENT 'Staging table for employee data' ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' LOCATION '/user/mapr/employees' TBLPROPERTIES ("skip.header.line.count"="1");










Once executed, we get result as shown below:












Validate the data in staging table by running below query:

 SELECT COUNT(*) FROM STAGING_EMPLOYEES;













Once we have the staging table, we need to transform the HIRE_DATE column from a string to DATE datatype. So, we create the final table called employees with the correct datatypes and then populate it with data from the staging_employees table.

CREATE TABLE IF NOT EXISTS employees (EMPLOYEE_ID SMALLINT, FIRST_NAME STRING, LAST_NAME STRING, EMAIL STRING, PHONE_NUMBER STRING, HIRE_DATE DATE, JOB_ID STRING, SALARY SMALLINT, COMMISSION_PCT DOUBLE, MANAGER_ID SMALLINT,DEPARTMENT_ID TINYINT) COMMENT 'Table holding employee details';













Then, add the data using below query:

INSERT INTO employees SELECT EMPLOYEE_ID, FIRST_NAME, LAST_NAME, EMAIL, PHONE_NUMBER, TO_DATE(FROM_UNIXTIME(UNIX_TIMESTAMP(HIRE_DATE,'dd-MMM-yy'))), JOB_ID, SALARY, COMMISSION_PCT, MANAGER_ID, DEPARTMENT_ID FROM staging_employees;














Now that we have data in both employees and department table, we can go ahead with analytic functions in Hive. We will be largely drawing from the queries that we have written before in the case of Oracle.

The first one will be the group by clause:

select job_id, sum(salary) from employees where department_id < 40 group by (job_id);

The results are shown below and they are the same that we have got earlier.











Let us try to run below query having ROLLUP keyword:

select job_id, sum(salary) from employees where department_id < 40 group by rollup(job_id);

We get below error:









We will write a work around as show below:

select job_id, sum(salary) from employees where department_id < 40 group by (job_id) 
union 
select null, sum(salary) from employees where department_id < 40;


The results are shown below and they are the same that we have got earlier.












For cube too, we have to implement a work around.

Below grouping set will not run as an error will be thrown like earlier in the case of ROLLUP.






 
The query that will mimic the grouping set query is:

select null, job_id, sum(salary) from employees where department_id < 40 group by job_id
union
select department_id, null, sum(salary) from employees where department_id < 40 group by department_id; 


The results are shown below and they are the same that we have got earlier.












Likewise, the equivalent of below query

select department_id, job_id, sum(salary) from employees where department_id < 40 group by grouping sets (department_id,job_id,());

in Hive will be:

select null, job_id, sum(salary) from employees where department_id < 40 group by job_id
union
select department_id, null, sum(salary) from employees where department_id < 40 group by department_id
union
select null, null, sum(salary) from employees where department_id < 40;


The results are shown below and they are the same that we have got earlier.













ROLLUP and CUBE are used in a different way as shown in the next queries. For example, a query with ROLLUP is shown below:

select department_id, job_id, sum(salary) from employees where department_id < 40 group by department_id, job_id with rollup;

Running this gives below result:











The same results are shown if we run below query:

select department_id, job_id, sum(salary) from employees where department_id < 40 group by department_id,job_id
union
select department_id, null, sum(salary) from employees where department_id < 40 group by department_id
union
select null, null, sum(salary) from employees where department_id < 40;














A query using CUBE is shown below:

select department_id, job_id, sum(salary) from employees where department_id < 40 group by department_id, job_id with cube;

The results are shown below:















The same results are shown if we run below query:

select department_id, job_id, sum(salary) from employees where department_id < 40 group by department_id,job_id
union
select null, job_id, sum(salary) from employees where department_id < 40 group by job_id
union
select department_id, null, sum(salary) from employees where department_id < 40 group by department_id
union
select null, null, sum(salary) from employees where department_id < 40;

















We will continue with this topic in the next part of this series.