Hive是一个构建在hadoop之上的数据仓库,可将结构化的数据文件映射成表,并提供类SQL查询功能,用于查询的SQL语句会被转化为MapReduce作业,然后提交到Hadoop上运行。
数据类型
-- 创建数据库
create database db_hive;
create database if not exists db_hive;
-- 显示数据库
show databases;
-- 显示数据库信息
desc database db_hive;
desc database extended db_hive;
-- 切换当前数据库
use db_hive;
-- 修改数据库
alter database db_hive set dbproperties('createtime'='20200501');
-- 删除数据库
-- 空数据库
drop database db_hive;
drop database if exists db_hive;
-- 非空数据库,级联删除
drop database db_hive cascade;
创建表
CREATE [EXTERNAL] TABLE [IF NOT EXISTS] table_name
[(col_name data_type [COMMENT col_comment], ...)]
[COMMENT table_comment]
[PARTITIONED BY (col_name data_type [COMMENT col_comment], ...)]
[CLUSTERED BY (col_name, col_name, ...)
[SORTED BY (col_name [ASC|DESC], ...)] INTO num_buckets BUCKETS]
[ROW FORMAT row_format]
[STORED AS file_format]
[LOCATION hdfs_path]
(1)CREATE TABLE 创建一个指定名字的表。如果相同名字的表已经存在,则抛出异常;用户可以用 IF NOT EXISTS 选项来忽略这个异常。
(2)EXTERNAL关键字可以让用户创建一个外部表,在建表的同时指定一个指向实际数据的路径(LOCATION),Hive创建内部表时,会将数据移动到数据仓库指向的路径;若创建外部表,仅记录数据所在的路径,不对数据的位置做任何改变。在删除表的时候,内部表的元数据和数据会被一起删除,而外部表只删除元数据,不删除数据。
(3)COMMENT:为表和列添加注释。
(4)PARTITIONED BY创建分区表
(5)CLUSTERED BY创建分桶表
(6)SORTED BY不常用
(7)row format
ROW FORMAT
DELIMITED [FIELDS TERMINATED BY char] [COLLECTION ITEMS TERMINATED BY char]
[MAP KEYS TERMINATED BY char] [LINES TERMINATED BY char]
| SERDE serde_name [WITH SERDEPROPERTIES (property_name=property_value, property_name=property_value, ...)]
用户在建表的时候可以自定义SerDe或者使用自带的SerDe。如果没有指定ROW FORMAT 或者ROW FORMAT DELIMITED,将会使用自带的SerDe。在建表的时候,用户还需要为表指定列,用户在指定表的列的同时也会指定自定义的SerDe,Hive通过SerDe确定表的具体的列的数据。
SerDe是Serialize/Deserilize的简称,目的是用于序列化和反序列化。
(8)STORED AS指定存储文件类型
常用的存储文件类型:SEQUENCEFILE(二进制序列文件)、TEXTFILE(文本)、RCFILE(列式存储格式文件)
如果文件数据是纯文本,可以使用STORED AS TEXTFILE。如果数据需要压缩,使用 STORED AS SEQUENCEFILE。
(9)LOCATION :指定表在HDFS上的存储位置。
(10)LIKE允许用户复制现有的表结构,但是不复制数据。
创建表
(1)普通创建表
create table if not exists student2(
id int, name string
)
row format delimited fields terminated by '\t'
stored as textfile
location '/user/hive/warehouse/student2';
(2)根据查询结果创建表(查询的结果会添加到新创建的表中)
create table if not exists student3 as select id, name from student;
(3)根据已经存在的表结构创建表
create table if not exists student4 like student;
(4)查询表的类型
hive (default)> desc formatted student;
Table Type: MANAGED_TABLE
-- 查看表
show tables;
-- 删除表
drop table student;
-- 导入数据
load data local inpath '/opt/data/dept.txt' into table default.dept;
-- 修改表
alter table student set tblproperties('EXTERNAL'='TRUE');-- 修改内部表为外部表
-- 查看表类型
desc formatted student;
分区表
-- 创建分区表
create table dept_partition(
deptno int, dname string, loc string
)
partitioned by (month string)
row format delimited fields terminated by '\t';
-- 加载数据到分区表
hive (default)> load data local inpath '/opt/data/dept.txt' into table default.dept_partition partition(month='202001');
hive (default)> load data local inpath '/opt/data/dept.txt' into table default.dept_partition partition(month='202002');
-- 查询分区表
-- 单分区查询
select * from dept_partition where month = '202002';
-- 多分区联合查询
select * from dept_partition where month='202001'
union
select * from dept_partition where month='202002';
-- 增加分区
alter table dept_partition add partition(month='202003');
-- 删除分区
alter table dept_partition drop partition (month='202003');
-- 查看分区
show partitions dept_partition;
插入数据
load data local inpath '/opt/data/student.txt' into table default.student;
create table student(id int, name string) partitioned by (month string) row format delimited fields terminated by '\t';
-- 基本插入数据
insert into table student partition(month='201909') values(1,'李四');
-- 基本模式插入,根据单张表查询结果
insert overwrite table student partition(month='201908')
select id, name from student where month='201909';
-- 多插入模式,根据多张表查询结果
from student
insert overwrite table student partition(month='201907')
select id, name where month='201909'
insert overwrite table student partition(month='201906')
select id, name where month='201909';
create table if not exists student2
as select id, name from student;
create table if not exists student3(
id int, name string
)
row format delimited fields terminated by '\t'
location '/user/hive/warehouse/student3';
import table student4 partition(month='201909') from
'/user/hive/warehouse/export/student';
-- 全表查询
select * from emp;
-- 指定聚合查询
select count(*) cnt from emp;
-- where过滤,limit限制结果有几条数据
select * from emp where sal >1000 limit 3;
-- 模糊查询
select * from emp where sal LIKE '2%';
select * from emp where sal RLIKE '[2]';
-- distinct 去重
-- avg、sum、min、max 聚合
-- group by
--(1)计算emp表每个部门的平均工资
hive (default)> select t.deptno, avg(t.sal) avg_sal from emp t group by t.deptno;
--(2)计算emp每个部门中每个岗位的最高薪水
hive (default)> select t.deptno, t.job, max(t.sal) max_sal from emp t group by
t.deptno, t.job;
--(3)求每个部门的平均薪水大于2000的部门
hive (default)> select deptno, avg(sal) avg_sal from emp group by deptno having
avg_sal > 2000;
--(1)根据员工表和部门表中的部门编号相等,查询员工编号、员工名称和部门名称;
hive (default)> select e.empno, e.ename, d.deptno, d.dname from emp e join dept d
on e.deptno = d.deptno;
内连接:只有进行连接的两个表中都存在与连接条件相匹配的数据才会被保留下来。
select e.empno, e.ename, d.deptno from emp e join dept d on e.deptno = d.deptno;
左外连接:JOIN操作符左边表中符合WHERE子句的所有记录将会被返回。
select e.empno, e.ename, d.deptno from emp e left join dept d on e.deptno = d.deptno;
右外连接:JOIN操作符右边表中符合WHERE子句的所有记录将会被返回。
select e.empno, e.ename, d.deptno from emp e right join dept d on e.deptno = d.deptno;
满外连接:将会返回所有表中符合WHERE语句条件的所有记录。如果任一表的指定字段没有符合条件的值的话,那么就使用NULL值替代。
select e.empno, e.ename, d.deptno from emp e full join dept d on e.deptno = d.deptno;
注意:连接 n个表,至少需要n-1个连接条件。例如:连接三个表,至少需要两个连接条件。
-- 1、创建位置表
create table if not exists default.location(
loc int,
loc_name string
)
row format delimited fields terminated by '\t';
-- 2、导入数据
load data local inpath '/opt/module/datas/location.txt' into table default.location;
-- 3、多表连接查询
hive (default)>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连接对象启动一个MR任务。本例中会首先启动一个MR job对表e和表d进行连接操作,然后会再启动一个MR job将第一个MR job的输出和表l;进行连接操作。
注意:为什么不是表d和表l先进行连接操作呢?因为Hive总是按照从左到右的顺序执行的。
Order By:全局排序,一个Reducer
1.使用 ORDER BY 子句排序
ASC(ascend): 升序(默认)
DESC(descend): 降序
2.ORDER BY 子句在SELECT语句的结尾
--(1)查询员工信息按工资升序排列
select * from emp order by sal;
--(2)查询员工信息按工资降序排列
select * from emp order by sal desc;
-- 按照别名排序
-- 按照员工薪水的2倍排序
select ename, sal*2 twosal from emp order by twosal;
-- 多个列排序
-- 按照部门和工资升序排序
select ename, deptno, sal from emp order by deptno, sal ;
Sort By:每个Reducer内部进行排序,对全局结果集来说不是排序。
-- 1.设置reduce个数
set mapreduce.job.reduces=3;
-- 2.查看设置reduce个数
set mapreduce.job.reduces;
-- 3.根据部门编号降序查看员工信息
select * from emp sort by empno desc;
-- 4.将查询结果导入到文件中(按照部门编号降序排序)
insert overwrite local directory '/opt/module/datas/sortby-result'
select * from emp sort by deptno desc;
Distribute By:类似MR中partition,进行分区,结合sort by使用。
注意:Hive要求DISTRIBUTE BY语句要写在SORT BY语句之前。
对于distribute by进行测试,一定要分配多reduce进行处理,否则无法看到distribute by的效果。
--(1)先按照部门编号分区,再按照员工编号降序排序。
set mapreduce.job.reduces=3;
insert overwrite local directory '/opt/module/datas/distribute-result' select * from emp distribute by deptno sort by empno desc;
当distribute by和sorts by字段相同时,可以使用cluster by方式。
cluster by除了具有distribute by的功能外还兼具sort by的功能。但是排序只能是升序排序,不能指定排序规则为ASC或者DESC。
-- 以下两种写法等价
select * from emp cluster by deptno;
select * from emp distribute by deptno sort by deptno;
大多数语句都会触发 MapReduce, 少部分不会触发, select * from emp limit 5
就不会触发 MR,此时 Hive 只是简单的读取数据文件中的内容,然后格式化后进行输出。在需要执行 MapReduce 的查询中,你会发现执行时间可能会很长,这时你可选择开启本地模式。
-- 本地模式默认关闭,需要手动开启此功能
SET hive.exec.mode.local.auto=true;
启用后,Hive 将分析查询中每个 map-reduce 作业的大小,如果满足以下条件,则可以在本地运行它:
因为我们测试的数据集很小,所以你再次去执行上面涉及 MR 操作的查询,你会发现速度会有显著的提升。
笛卡尔积连接,这个连接日常的开发中可能很少遇到,且性能消耗比较大,基于这个原因,如果在严格模式下 (hive.mapred.mode = strict),Hive 会阻止用户执行此操作。
select * from emp join dept;
set hive.cli.print.header=true;
-- 进入hive cli后:
set hive.cli.print.header=true;
-- 此时显示的字段名带表名,可读性很差,继续在hive cli中:
set hive.resultset.use.unique.column.names=false;
1、对map端部分聚合,相当于combiner。控制程序如何进行聚合。默认值为 false。如果设置为 true,Hive 会在 map 阶段就执行一次聚合。这可以提高聚合效率,但需要消耗更多内存。
set hive.map.aggr = true;
2、数据倾斜的时候进行负载均衡。当设定为 true,生成的查询计划会有两个 MR Job。第一个 MR Job 中,Map 的输出结果集合会随机分布到 Reduce 中,每个Reduce 做部分聚合操作,并输出结果,这样处理的结果是相同的 Group By Key 有可能被分发到不同的 Reduce 中,从而达到负载均衡的目的;第二个 MR Job 再根据预处理的数据结果按照 Group By Key 分布到 Reduce 中(这个过程可以保证相同的 Group By Key 被分布到同一个 Reduce 中),最后完成最终的聚合操作。
set hive.groupby.skewindata=true;