Hive - Hive query

Query syntax:

[WITH CommonTableExpression (, CommonTableExpression)*]    (Note: Only available
 starting with Hive 0.13.0)
SELECT [ALL | DISTINCT] select_expr, select_expr, ...
  FROM table_reference
  [WHERE where_condition]
  [GROUP BY col_list]
  [ORDER BY col_list]
  [CLUSTER BY col_list
    | [DISTRIBUTE BY col_list] [SORT BY col_list]
  ]
 [LIMIT number]

1, the basic query (Select ... From)

1.1 full table and query specific columns

1. Full-table query

hive > select * from emp;

2. Select specific columns in the query

hive > select empno, ename from emp;

note:

    (1) SQL language is not case sensitive. 

    (2) SQL can be written in one or more rows

    (3) Keywords can not be abbreviated nor branch

    (4) each clause generally branches write. 

    (5) the use of statements indented to improve readability.

1.2 Aliases

  1. Renaming a column

  2. Ease of calculation

  3. Followed by a column name, you can also add the keyword 'AS' between the column names and aliases 

  4. Case practical operation

  Query name and department

hive > select ename AS name, deptno dn from emp;

1.3 Arithmetic Operators

Operators

description

A+B

A and B are added

A-B

A minus B

A*B

A and B are multiplied

A/B

A divided by B

A%B

A B I to take

A&B

A and B are bit-wise with

A|B

A and B or the bit-wise

A^B

A and B are bit-wise XOR

~A

A bitwise

 After check out the salaries for all employees plus 1 display.

hive > select sal +1 from emp;

1.4 Common Functions

  1. Seeking total number of rows (count)

hive > select count(*) cnt from emp;

  2. Seeking a maximum value of wages (max)

hive > select max(sal) max_sal from emp;

  3. Seeking the minimum wage (min)

hive > select min(sal) min_sal from emp;

  4. Wage required sum (sum)

hive > select sum(sal) sum_sal from emp;

  5. Averaging wages (avg)

hive > select avg(sal) avg_sal from emp;

1.5 Limit Statement

  A typical query returns multiple rows of data. LIMIT clause restricts the number of rows returned.

hive > select * from emp limit 5;

2, Where statement 

  1. Using the WHERE clause, the row does not satisfy the conditions to filter out

  2. Immediately WHERE clause FROM clause

  3. Case practical operation

  Check out all the staff salaries greater than 1000

hive > select * from emp where sal >1000;

2.1 Comparison operators (Between / In / Is Null)

1) described in the table below predicates operators, these operators can also be used and HAVING JOIN ... ON statements.

Operators

Supported data types

description

A=B

Basic data types

If A is equal to B returns TRUE, return FALSE conversely

A<=>B

Basic data types

If A and B are both NULL, then returns TRUE, and consistent with the results of other equal sign (=) operator, if either result is NULL is NULL

A<>B, A!=B

Basic data types

A or B is NULL NULL is returned; if A does not equal B, then return TRUE, otherwise returns FALSE

A<B

Basic data types

A or B is NULL, NULL is returned; if A is smaller than B, TRUE is returned, otherwise it returns FALSE

A<=B

Basic data types

A or B is NULL, NULL is returned; if A or less B, TRUE is returned, otherwise returns FALSE

A>B

Basic data types

A or B is NULL, NULL is returned; if A is greater than B, TRUE is returned, otherwise it returns FALSE

A>=B

Basic data types

A or B is NULL, NULL is returned; if A is greater than or equal B, TRUE is returned, otherwise it returns FALSE

A [NOT] BETWEEN B AND C

Basic data types

If A, B or C according to any one of NULL, the result to NULL. If the value of A is greater than B and equal to or less C, then the result is TRUE, otherwise it is FALSE. If you use the NOT keyword can reach the opposite effect.

A IS NULL

All data types

If A is equal to NULL, then returns TRUE, return FALSE conversely

A IS NOT NULL

All data types

If A is not equal to NULL, then returns TRUE, return FALSE conversely

IN (value 1, value 2)

All data types

Values ​​using the IN operator display list

A [NOT] LIKE B

STRING type

B is a simple SQL under a regular expression, if A, then its matching, TRUE is returned; otherwise returns FALSE. Expression B is as follows: 'x%' denotes A must start with a letter 'x', '% x' expressed with a letter A 'x' end, while the '% x%' represented with the letter A 'x', It may be at the beginning, end or middle of the string. If you use the NOT keyword can reach the opposite effect.

A RLIKE B, A REGEXP B

STRING type

B is a regular expression, if its matching A, TRUE is returned; otherwise returns FALSE. Matching using regular expressions in JDK interface, because regular basis also rule them. For example, the regular expression must match the entire string, and A, not just its string matching.

2) Case practical operation

(1) check out the salaries of all employees equal to 5000

hive > select * from emp where sal =5000;

(2) query wage in the employee information 500-1000

hive > select * from emp where sal between 500 and 1000;

(3) comm query information is empty of all employees

hive > select * from emp where comm is null;

(4) query wages and employee information 1500 5000

hive > select * from emp where sal IN (1500, 5000);

2.2 Like和RLike

1) use the LIKE operator to select similar values

2) the selection criteria may contain characters or numbers:

    % Represents zero or more characters (any characters).

    _ Represents one character.

3) RLIKE Hive in this clause is an extension function, which can be expressions of Java being the more powerful language to specify the matching criteria.

4) cases of practical operation

(1) Find the beginning of employee salary information 2

hive (default)> select * from emp where sal LIKE '2%';

(2)查找第二个数值为2的薪水的员工信息

hive (default)> select * from emp where sal LIKE '_2%';

(3)查找薪水中含有2的员工信息

hive (default)> select * from emp where sal RLIKE '[2]';

2.3 逻辑运算符(And/Or/Not)

操作符

含义

AND

逻辑并

OR

逻辑或

NOT

逻辑否

案例实操

(1)查询薪水大于1000,部门是30

hive > select * from emp where sal>1000 and deptno=30;

(2)查询薪水大于1000,或者部门是30

hive > select * from emp where sal>1000 or deptno=30;

(3)查询除了20部门和30部门以外的员工信息

hive > select * from emp where deptno not IN(30, 20);

3、分组

3.1 Group By语句

GROUP BY语句通常会和聚合函数一起使用,按照一个或者多个列队结果进行分组,然后对每个组执行聚合操作。

案例实操:

(1)计算emp表每个部门的平均工资

hive > select t.deptno, avg(t.sal) avg_sal from emp t group by t.deptno;

(2)计算emp每个部门中每个岗位的最高薪水

hive > select t.deptno, t.job, max(t.sal) max_sal from emp t group by t.deptno, t.job;

3.2 Having语句

1.having与where不同点

(1)where针对表中的列发挥作用,查询数据;having针对查询结果中的列发挥作用,筛选数据。

(2)where后面不能写分组函数,而having后面可以使用分组函数。

(3)having只用于group by分组统计语句。

2.案例实操

(1)求每个部门的平均薪水大于2000的部门

 求每个部门的平均工资

hive > select deptno, avg(sal) from emp group by deptno;

  求每个部门的平均薪水大于2000的部门

hive > select deptno, avg(sal) avg_sal from emp group by deptno having avg_sal > 2000;

4、Join语句

4.1 等值Join

Hive支持通常的SQL JOIN语句,但是只支持等值连接,不支持非等值连接。

案例实操

(1)根据员工表和部门表中的部门编号相等,查询员工编号、员工名称和部门编号;

hive > select e.empno, e.ename, d.deptno, d.dname from emp e join dept d on e.deptno = d.deptno;

4.2 表的别名

1.好处

(1)使用别名可以简化查询。

(2)使用表名前缀可以提高执行效率。

2.案例实操

合并员工表和部门表

hive > select e.empno, e.ename, d.deptno from emp e join dept d on e.deptno = d.deptno;

4.3 内连接

内连接:只有进行连接的两个表中都存在与连接条件相匹配的数据才会被保留下来。

hive > select e.empno, e.ename, d.deptno from emp e join dept d on e.deptno = d.deptno;

4.4 左外连接

左外连接:JOIN操作符左边表中符合WHERE子句的所有记录将会被返回。

hive (default)> select e.empno, e.ename, d.deptno from emp e left join dept d on e.deptno = d.deptno;

4.5 右外连接

右外连接:JOIN操作符右边表中符合WHERE子句的所有记录将会被返回。

hive > select e.empno, e.ename, d.deptno from emp e right join dept d on e.deptno = d.deptno;

4.6 满外连接

满外连接:将会返回所有表中符合WHERE语句条件的所有记录。如果任一表的指定字段没有符合条件的值的话,那么就使用NULL值替代。

hive > select e.empno, e.ename, d.deptno from emp e full join dept d on e.deptno = d.deptno;

4.7 多表连接

注意:连接 n个表,至少需要n-1个连接条件。例如:连接三个表,至少需要两个连接条件。

数据准备

1700	Beijing
1800	London
1900	Tokyo

1.创建位置表

create table if not exists default.location(
    loc int,
    loc_name string
)
row format delimited fields terminated by '\t';

2.导入数据

hive > load data local inpath '/opt/module/datas/location.txt' into table default.location;

3.多表连接查询

hive >SELECT e.ename, d.deptno, l. loc_name

FROM   emp e

JOIN   dept d

ON     d.deptno = e.deptno

JOIN   location l

ON     d.loc = l.loc;

        大多数情况下,Hive会对每对JOIN连接对象启动一个MapReduce任务。本例中会首先启动一个MapReduce job对表e和表d进行连接操作,然后会再启动一个MapReduce job将第一个MapReduce job的输出和表l;进行连接操作。

        注意:为什么不是表d和表l先进行连接操作呢?这是因为Hive总是按照从左到右的顺序执行的

5、排序

5.1 全局排序(Order By)

Order By:全局排序,一个MapReduce

  1.使用 ORDER BY 子句排序

  ASC(ascend): 升序(默认)

  DESC(descend): 降序

  2.ORDER BY 子句在SELECT语句的结尾

  3.案例实操

  (1)查询员工信息按工资升序排列

hive > select * from emp order by sal;

  (2)查询员工信息按工资降序排列

hive > select * from emp order by sal desc;

5.2 按照别名排序

按照员工薪水的2倍排序

hive > select ename, sal*2 twosal from emp order by twosal;

5.3 多个列排序

按照部门和工资升序排序

hive > select ename, deptno, sal from emp order by deptno, sal ;

5.4 每个MapReduce内部排序(Sort By)

Sort By:每个MapReduce内部进行排序,对全局结果集来说不是排序

1.设置reduce个数

hive > set mapreduce.job.reduces=3;

2.查看设置reduce个数

hive > set mapreduce.job.reduces;

3.根据部门编号降序查看员工信息

hive > select * from emp sort by empno desc;

4.将查询结果导入到文件中(按照部门编号降序排序)

hive > insert overwrite local directory '/opt/module/datas/sortby-result' select * from emp sort by deptno desc;

5.5 分区排序(Distribute By)

Distribute By:类似MR中partition,进行分区,结合sort by使用。

注意,Hive要求DISTRIBUTE BY语句要写在SORT BY语句之前。

对于distribute by进行测试,一定要分配多reduce进行处理,否则无法看到distribute by的效果。

案例实操:

1)先按照部门编号分区,再按照员工编号降序排序。

hive > set mapreduce.job.reduces=3;

hive > insert overwrite local directory '/opt/module/datas/distribute-result' select * from emp distribute by deptno sort by empno desc;

5.6 Cluster By

当distribute by和sorts by字段相同时,可以使用cluster by方式。

cluster by除了具有distribute by的功能外还兼具sort by的功能。但是排序只能是倒序排序,不能指定排序规则为ASC或者DESC。

1)以下两种写法等价

hive > select * from emp cluster by deptno;

hive > select * from emp distribute by deptno sort by deptno;

注意:按照部门编号分区,不一定就是固定死的数值,可以是20号和30号部门分到一个分区里面去。

6 分桶及抽样查询

6.1 分桶表数据存储

分区针对的是数据的存储路径;分桶针对的是数据文件。

分区提供一个隔离数据和优化查询的便利方式。不过,并非所有的数据集都可形成合理的分区,特别是之前所提到过的要确定合适的划分大小这个疑虑。

分桶是将数据集分解成更容易管理的若干部分的另一个技术。

数据准备

1001	ss1
1002	ss2
1003	ss3
1004	ss4
1005	ss5
1006	ss6
1007	ss7
1008	ss8
1009	ss9
1010	ss10
1011	ss11
1012	ss12
1013	ss13
1014	ss14
1015	ss15
1016	ss16

2.创建分桶表时,数据通过子查询的方式导入

(1)先建一个普通的stu表

create table stu(
    id int, 
    name string
)
row format delimited fields terminated by '\t';

(2)向普通的stu表中导入数据

load data local inpath '/opt/module/datas/student.txt' into table stu;

(3)清空stu_buck表中数据

truncate table stu_buck;
select * from stu_buck;

(4)导入数据到分桶表,通过子查询的方式

insert into table stu_buck select id, name from stu;

(5)需要设置一个属性即可分桶成功

hive > set hive.enforce.bucketing=true;

hive > set mapreduce.job.reduces=-1;

hive > insert into table stu_buck select id, name from stu;

(6)查询分桶的数据

hive > select * from stu_buck;
OK
stu_buck.id     stu_buck.name
1004    ss4
1008    ss8
1012    ss12
1016    ss16
1001    ss1
1005    ss5
1009    ss9
1013    ss13
1002    ss2
1006    ss6
1010    ss10
1014    ss14
1003    ss3
1007    ss7
1011    ss11
1015    ss15

6.2 分桶抽样查询

        对于非常大的数据集,有时用户需要使用的是一个具有代表性的查询结果而不是全部结果。Hive可以通过对表进行抽样来满足这个需求。

查询表stu_buck中的数据。

      hive > select * from stu_buck tablesample(bucket 1 out of 4 on id);

注:tablesample是抽样语句,语法:TABLESAMPLE(BUCKET x OUT OF y) 。

        y必须是table总bucket数的倍数或者因子。hive根据y的大小,决定抽样的比例。例如,table总共分了4份,当y=2时,抽取(4/2=)2个bucket的数据,当y=8时,抽取(4/8=)1/2个bucket的数据。

        x表示从哪个bucket开始抽取,如果需要取多个分区,以后的分区号为当前分区号加上y。例如,table总bucket数为4,tablesample(bucket 1 out of 2),表示总共抽取(4/2=)2个bucket的数据,抽取第1(x)个和第3(x+y)个bucket的数据。

注意:x的值必须小于等于y的值,否则

FAILED: SemanticException [Error 10061]: Numerator should not be bigger than denominator in sample clause for table stu_buck

7、其他常用查询函数

7.1 空字段赋值

  1. 函数说明

      NVL:给值为NULL的数据赋值,它的格式是NVL( string1, replace_with)。它的功能是如果string1为NULL,则NVL函数返回replace_with的值,否则返回string1的值,如果两个参数都为NULL ,则返回NULL。

     2.数据准备:采用员工表

     3.查询:如果员工的comm为NULL,则用-1代替

hive > select nvl(comm,-1) from emp;
OK
_c0
20.0
300.0
500.0
-1.0
1400.0
-1.0
-1.0
-1.0
-1.0
0.0
-1.0
-1.0
-1.0
-1.0

     4.查询:如果员工的comm为NULL,则用领导id代替 

hive > select nvl(comm,mgr) from emp;
OK
_c0
20.0
300.0
500.0
7839.0
1400.0
7839.0
7839.0
7566.0
NULL
0.0
7788.0
7698.0
7566.0

7.2 CASE WHEN

1. 数据准备

name

dept_id

sex

悟空

A

大海

A

宋宋

B

 

 

凤姐

A

婷姐

B

婷婷

B

2.需求

求出不同部门男女各多少人。结果如下:

A     2       1
B     1       2

3.创建本地emp_sex.txt,导入数据

[root@master datas]$ vi emp_sex.txt

悟空 A 男
大海 A 男
宋宋 B 男
凤姐 A 女
婷姐 B 女
婷婷 B 女

4.创建hive表并导入数据

create table emp_sex(
    name string,
    dept_id string,
    sex string
)
row format delimited fields terminated by "\t";
load data local inpath '/opt/module/datas/emp_sex.txt' into table emp_sex;

5.按需求查询数据

select
  dept_id,
  sum(case sex when '男' then 1 else 0 end) male_count,
  sum(case sex when '女' then 1 else 0 end) female_count
from
  emp_sex
group by
  dept_id;

7.2 行转列

1.相关函数说明

CONCAT(string A/col, string B/col…):返回输入字符串连接后的结果,支持任意个输入字符串;

CONCAT_WS(separator, str1, str2,...):它是一个特殊形式的 CONCAT()。第一个参数为剩余参数间的分隔符。分隔符可以是与剩余参数一样的字符串。如果分隔符是 NULL,返回值也将为 NULL。这个函数会跳过分隔符参数后的任何 NULL 和空字符串。分隔符将被加到被连接的字符串之间;

COLLECT_SET(col):函数只接受基本数据类型,它的主要作用是将某字段的值进行去重汇总,产生array类型字段。

2.数据准备

name

constellation

blood_type

孙悟空

白羊座

A

大海

射手座

A

宋宋

白羊座

B

猪八戒

白羊座

A

凤姐

射手座

A

3.需求

把星座和血型一样的人归类到一起。结果如下:

射手座,A            大海|凤姐
白羊座,A            孙悟空|猪八戒
白羊座,B            宋宋

4.创建本地constellation.txt,导入数据

[root@master datas]$ vim constellation.txt
孙悟空	白羊座	A
大海	射手座	A
宋宋	白羊座	B
猪八戒   白羊座	A
凤姐	射手座	A

5.创建hive表并导入数据

create table person_info(
    name string, 
    constellation string, 
    blood_type string
) 
row format delimited fields terminated by "\t";
load data local inpath “/opt/module/datas/person_info.txt” into table person_info;

6.按需求查询数据

select
    t1.base,
    concat_ws('|', collect_set(t1.name)) name
from
    (select
        name,
        concat(constellation, ",", blood_type) base
    from
        person_info) t1
group by
    t1.base;

7.3 列转行

1.函数说明

EXPLODE(col):将hive一中复杂的array或者map结构拆分成多行。

LATERAL VIEW

用法:LATERAL VIEW udtf(expression) tableAlias AS columnAlias

解释:用于和split, explode等UDTF一起使用,它能够将一列数据拆成多行数据,在此基础上可以对拆分后的数据进行聚合。

2.数据准备

movie

category

《疑犯追踪》

悬疑,动作,科幻,剧情

《Lie to me》

悬疑,警匪,动作,心理,剧情

《战狼2》

战争,动作,灾难

3.需求

将电影分类中的数组数据展开。结果如下:

《疑犯追踪》      悬疑
《疑犯追踪》      动作
《疑犯追踪》      科幻
《疑犯追踪》      剧情
《Lie to me》    悬疑
《Lie to me》    警匪
《Lie to me》    动作
《Lie to me》    心理
《Lie to me》    剧情
《战狼2》        战争
《战狼2》        动作
《战狼2》        灾难

4.创建本地movie.txt,导入数据

[root@master datas]$ vim movie.txt
《疑犯追踪》	悬疑,动作,科幻,剧情
《Lie to me》	悬疑,警匪,动作,心理,剧情
《战狼2》	战争,动作,灾难

5.创建hive表并导入数据

create table movie_info(
    movie string, 
    category array<string>
) 
row format delimited fields terminated by "\t"
collection items terminated by ",";
load data local inpath "/opt/module/datas/movie.txt" into table movie_info;

6.按需求查询数据

select
    movie,
    category_name
from 
    movie_info lateral view explode(category) table_tmp as category_name;

 

 

 

Guess you like

Origin blog.csdn.net/qq_41544550/article/details/92152498