Hive学习笔记

一、安装/连接Hive

安装Hive

安装都会,所以过程省略…

配置修改如下:

driver:驱动

url:数据库连接

username:用户名密码

password:用户名密码

${system}。。。:一共有三个,都需要修改

doAS:权限认证,改为false,不然无法操作。

<!--url-->
  <property>
    <name>javax.jdo.option.ConnectionURL</name>
    <value>jdbc:mysql://192.168.200.111:3306/hive?useSSL=true</value>
  </property>
  
  <!--Driver-->
  <property>
    <name>javax.jdo.option.ConnectionDriverName</name>
    <value>com.mysql.jdbc.Driver</value>
    <description>Driver class name for a JDBC metastore</description>
  </property>
  
  <!--username-->
  <property>
    <name>javax.jdo.option.ConnectionUserName</name>
    <value>root</value>
    <description>Username to use against metastore database</description>
  </property>
  
  <!--password-->
  <property>
    <name>javax.jdo.option.ConnectionPassword</name>
    <value>123456</value>
    <description>password to use against metastore database</description>
  </property>
  
  <!--querylog-->
  <property>
    <name>hive.querylog.location</name>
    <value>/home/hive/hive-data/querylog</value>
    <description>Location of Hive run time structured log file</description>
  </property>
  
  <!--exec-->
  <property>
    <name>hive.exec.local.scratchdir</name>
    <value>/home/hive/hive-data/exec</value>
    <description>Local scratch space for Hive jobs</description>
  </property>
  
  <!--download-->
  <property>
    <name>hive.downloaded.resources.dir</name>
    <value>/home/hive/hive-data/download</value>
    <description>Temporary local directory for added resources in the remote file system.</description>
  </property>
  
  <!--server2-->
  <property>
    <name>hive.server2.logging.operation.log.location</name>
    <value>/home/hive/hive-data/operation_logs</value>
    <description>Top level directory where operation logs are stored if logging functionality is enabled</description>
  </property>
  
  <!--doAS-->
  <property>
    <name>hive.server2.enable.doAs</name>
    <value>false</value>
    <description>
      Setting this property to true will have HiveServer2 execute
      Hive operations as the user making the calls to it.
    </description>
  </property>
#初始化
schematool -dbType mysql -initSchema

连接Hive

1.通过beeline连接(推荐)
#开启一个beeline客户端
[root@hadoop-1 ~]# hive --service hiveserver2 &
或者
//这是我喜欢的方式,直接后台运行一个beeline客户端
[root@hadoop-1 ~]# nohup hive --service hiveserver2 >> hiveserver2.log &

#进入beeline命令行
[root@hadoop-1 ~]# beeline

#通过beeline连接hive数据库
//这个hive2是我们开启的beeline客户端,10000是beeline的客户端的端口。
beeline>!connect jdbc:hive2://localhost:10000/db_01;
2.直接连接

缺点:不能同时开启多个hive命令行,而且,你要远程连接hive,还是得开启一个beeline客户端才能连接。

hive

3.通过thriftserver连接

#默认监听10000端口
start-thriftserver.sh

二、库

#创建库
0: jdbc:hive2://localhost:10000/db_01> create database db_test;
No rows affected (0.087 seconds)

#删除库
0: jdbc:hive2://localhost:10000/db_01> drop database db_test;
No rows affected (0.327 seconds)

三、表

表的分类

Hive的表,与普通关系型数据库,如mysql在表上有很大的区别,所有hive的表都是一个文件,它是基于Hadoop的文件系统来做的。

1.管理表(内部表)

默认创建的表都是所谓的管理表,有时也被称为内部表。因为这种表,Hive会(或多或少地)控制着数据的生命周期。Hive默认情况下会将这些表的数据存储在由配置项hive.metastore.warehouse.dir(例如,/user/hive/warehouse)所定义的目录的子目录下。 当我们删除一个管理表时,Hive也会删除这个表中数据。管理表不适合和其他工具共享数据。

2.外部表

EXTERNAL 关键字可以让用户创建一个外部表,在建表的同时指定一个指向实际数据的路径(location),Hive
创建内部表时,会将数据移动到数据仓库指向的路径;若创建外部表,仅记录数据所在的路径,不对数据的位置做任何改变。在删除表的时候,内部表的元数据和数据会被一起删除,而外部表只删除元数据,不删除数据。

create external table tb_site(id int, site string) sorted by textfile row format delimited'\t' location 'hdfs:///external-table';

管理表和外部表的使用场景:

每天将收集到的网站日志定期流入HDFS文本文件。在外部表(原始日志表)的基础上做大量的统计分析,用到的中间表、结果表使用内部表存储,数据通过SELECT+INSERT进入内部表。

3.分区表

有分区的表可以在创建的时候使用 partitioned by
语句。一个表可以拥有一个或者多个分区,每一个分区单独存在一个目录下。而且,表和分区都可以对某个列进行 partitioned by
操作,将若干个列放入一个桶(bucket)中。也可以利用sorted by 对数据进行排序。这样可以为特定应用提高性能。

分区表实际上就是对应一个HDFS文件系统上的独立的文件夹,该文件夹下是该分区所有的数据文件。Hive中的分区就是分目录,把一个大的数据集根据业务需要分割成小的数据集。在查询时通过WHERE子句中的表达式选择查询所需要的指定的分区,这样的查询效率会提高很多。

create table tb_site(id int, site string) partitioned by (pt string) sorted by textfile row format delimited'\t';

桶的概念,主要是为性能考虑,可以理解为对分区内列,进行再次划分,提高性能。在底层,一个桶其实是一个文件。如果桶划分过多,会导致文件数量暴增,一旦达到系统文件数量的上限,就杯具了。哪种是最优数量,这个我也不知道。

分区表实际是一个文件夹,表名即文件夹名。每个分区,实际是表名这个文件夹下面的不同文件。分区可以根据时间、地点等等进行划分。比如,每天一个分区,等于每天存每天的数据;或者每个城市,存放每个城市的数据。每次查询数据的时候,只要写下类似
where pt=2010_08_23这样的条件即可查询指定时间得数据。

总体而言,普通表,类似mysql的表结构,外部表的意义更多是指数据的路径映射。分区表,是最难以理解,也是最hive最大的优势。之后会专门针对分区表进行讲解。

#创建分区表dept_partition
//partitioned by (month string):按月分区
//row format delimited fields terminated by ',':指定行分隔符为逗号
//lines terminated by '\n':指定列分隔符为换行
create table dept_partition(deptno int, dname string, loc string)
    partitioned by (month string)
    row format delimited fields terminated by ','
    lines terminated by '\n';

#加载数据到分区表dept_partition,并指定分区为201811
load data local inpath '/root/dept_partition.txt' into table dept_partition partition(month='201811');

load data local inpath '/root/dept_partition.txt' into table dept_partition partition(month='201812');

//一样的,就是年
create table user_partition(deptno int, dname string, loc string)
    partitioned by (year string)
    row format delimited fields terminated by ','
    lines terminated by '\n';
    
load data local inpath '/root/dept_partition.txt' into table dept_partition partition(year='2017');

load data local inpath '/root/dept_partition.txt' into table dept_partition partition(year='2018');

#union查询多个分区表数据,会执行MapReduce
select * from user_partition where year=2017 union select * from user_partition where year=2018;

#删除一个分区
alter table dept_partition drop partition (month='201812');

#删除多个分区
alter table dept_partition drop partition (month='201812'),partition (month='201811');

#增加分区
alter table dept_partition add partition(month='201706');

#增加多个分区
alter table dept_partition add partition(month='201705') partition(month='201704');

#查看分区表dept_partition有多少个分区
show partitions dept_partition;

#查看分区表dept_partition结构
desc formatted dept_partition;

二级分区

1.创建二级分区表

hive (default)> create table dept_partition2(               deptno int, dname string, loc string               )               partitioned by (month string, day string)               row format delimited fields terminated by '\t';

2.正常的加载数据

(1)加载数据到二级分区表中

hive (default)> load data local inpath '/opt/module/datas/dept.txt' into table

 default.dept_partition2 partition(month='201709', day='13');

(2)查询分区数据

hive (default)> select * from dept_partition2 where month='201709' and day='13';

3.把数据直接上传到分区目录上,让分区表和数据产生关联的三种方式

(1)方式一:上传数据后修复

​ 上传数据

hive (default)> dfs -mkdir -p

 /user/hive/warehouse/dept_partition2/month=201709/day=12;

hive (default)> dfs -put /opt/module/datas/dept.txt  /user/hive/warehouse/dept_partition2/month=201709/day=12;

​ 查询数据(查询不到刚上传的数据)

hive (default)> select * from dept_partition2 where month='201709' and day='12';

执行修复命令

hive> msck repair table dept_partition2;

再次查询数据

hive (default)> select * from dept_partition2 where month='201709' and day='12';

​ (2)方式二:上传数据后添加分区

​ 上传数据

hive (default)> dfs -mkdir -p /user/hive/warehouse/dept_partition2/month=201709/day=11;

hive (default)> dfs -put /opt/module/datas/dept.txt /user/hive/warehouse/dept_partition2/month=201709/day=11;

​ 执行添加分区

hive (default)> alter table dept_partition2 add partition(month='201709', day='11');

​ 查询数据

hive (default)> select * from dept_partition2 where month='201709' and day='11';

​ (3)方式三:创建文件夹后load数据到分区

​ 创建目录

hive (default)> dfs -mkdir -p /user/hive/warehouse/dept_partition2/month=201709/day=10;

上传数据

hive (default)> load data local inpath '/opt/module/datas/dept.txt' into table dept_partition2 partition(month='201709',day='10');

查询数据

hive (default)> select * from dept_partition2 where month='201709' and day='10';

创建表

语法:

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]

create table test(
name string,
friends array<string>,
children map<string, int>,
address struct<street:string, city:string>
)
row format delimited fields terminated by ','
collection items terminated by '_'
map keys terminated by ':'
lines terminated by '\n';

###字段解释:
row format delimited fields terminated by ','  -- 列分隔符
collection items terminated by '_'  	--MAP STRUCT 和 ARRAY 的分隔符(数据分割符号)
map keys terminated by ':'				-- MAP中的key与value的分隔符
lines terminated by '\n';					-- 行分隔符

(1)CREATE TABLE 创建一个指定名字的表。如果相同名字的表已经存在,则抛出异常;用户可以用 IF NOT EXISTS 选项来忽略这个异常。

(2)EXTERNAL关键字可以让用户创建一个外部表,在建表的同时指定一个指向实际数据的路径(LOCATION),Hive创建内部表时,会将数据移动到数据仓库指向的路径;若创建外部表,仅记录数据所在的路径,不对数据的位置做任何改变。在删除表的时候,内部表的元数据和数据会被一起删除,而外部表只删除元数据,不删除数据。

(3)COMMENT:为表和列添加注释。

(4)PARTITIONED BY创建分区表

(5)CLUSTERED BY创建分桶表

(6)SORTED BY不常用

(7)ROW FORMAT

用户在建表的时候可以自定义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允许用户复制现有的表结构,但是不复制数据。

#重命名表
alter table emp rename to tb_emp;

增加/修改/替换列信息

#查询分区表结构
hive> desc dept_partition;

#查询表结构
hive> desc tb_user;

#添加列
hive (default)> alter table dept_partition add columns(deptdesc string);

#更新列
hive (default)> alter table dept change column loc loc_id int;

alter table dept change column loc_id loc string;

#替换列
hive (default)> alter table dept_partition replace columns(deptno string, dname string, loc string);


#删除表
hive (default)> drop table dept_partition;

注:ADD是代表新增一字段,字段位置在所有列后面(partition列前),REPLACE则是表示替换表中所有字段。

复制表

#携带数据和表结构
create table tt as select * from users ;
#不带数据,只有表结构
create table tt like users ;

启用/禁用 表与count

#不允许删除
alter table tb_user enabled no_drop;
#允许删除
alter table tb_user disable no_drop;

四、加载数据

Hive不支持一条一条的用insert语句进行插入操作,也不支持update的操作。数据是以load的方式,加载到建立好的表中。数据一旦导入,则不可修改。要么drop掉整个表,要么建立新的表,导入新的数据。

1.load data到指定的表

语法:

hive> load data [local] inpath '/opt/module/datas/student.txt' overwrite | into table student [partition (partcol1=val1,)];

(1)load data:示加载数据

(2)local:表示从本地加载数据到hive表;否则从HDFS加载数据到hive表

(3)inpath:表示加载数据的路径

(4)overwrite:表示覆盖表中已有数据,否则表示追加

(5)into table:表示加载到哪张表

(6)student:表示具体的表

(7)partition:表示上传到指定分区

创建数据表:

必须指定数据分隔符,不然查询数据表全都是NULL。

每行数据以tab键隔开,以换行键结尾:

create table tb_user(id int, name string,age int) row format delimited fields terminated by ' ' lines terminated by '\n' stored as textfile;

每行数据以,键隔开,以换行键结尾:

create table tb_user(id int, name string,age int) row format delimited fields terminated by ',' lines terminated by '\n' stored as textfile;

导入本地数据到hive表中

创建本地数据:

vi a.txt

1,小花,29
2,小明,26
3,小凡,20
4,张三,21

导入本地数据到hive表中:

load data local inpath '/root/a.txt' into table tb_user;

导入HDFS数据到hive表中

创建HDFS的数据:

vi b.txt

1,computer
2,iphone
3,computer
4,iphone

hdfs dfs -put /root/b.txt /testfile

导入HDFS数据到hive表中:

load data inpath '/testfile/b.txt' into table tb_site;

2.load到指定表的分区

直接将file,加载到指定表的指定分区。表本身必须是分区表,如果是普通表,导入会成功,但是数据实际不会被导入。

语法:

LOAD DATA LOCAL INPATH '/home/admin/test/test.txt' OVERWRITE INTO TABLE test_1 PARTITION(pt=’xxxx)  

load数据,hive支持文件夹的方式,将文件夹内的所有文件,都load到指定表中。Hdfs会将文件系统内的某文件夹路径内的文件,分散到不同的实际物理地址中。这样,在数据量很大的时候,hive支持读取多个文件载入,而不需要限定在唯一的文件中。

3.insert+select

//子查询

语法:

Standard syntax:
INSERT OVERWRITE TABLE tablename1 [PARTITION (partcol1=val1, partcol2=val2 ...)] select_statement1 FROM from_statement 
 
Hive extension (multiple inserts):
FROM from_statement
INSERT OVERWRITE TABLE tablename1 [PARTITION (partcol1=val1, partcol2=val2 ...)] select_statement1
[INSERT OVERWRITE TABLE tablename2 [PARTITION ...] select_statement2] ...
 
Hive extension (dynamic partition inserts):
INSERT OVERWRITE TABLE tablename PARTITION (partcol1[=val1], partcol2[=val2] ...) select_statement FROM from_statement

这个的用法,和上面两种直接操作file的方式,截然不同。从sql语句本身理解,就是把查询到的数据,直接导入另外一张表。

附加:

  • insert into 语句:
hive> insert into table account select id,age,name from account_tmp;

  • insert overwrite语句:
hive> insert overwrite table account2 select id,age,name from account_tmp;

也就是说 overwrite会覆盖现有的数据,而into是直接将数据写入库。

如果需要的是去重的数据,那么应该选择overwrite作为插入的方式。

4.alter表,对分区操作

语法:

ALTER TABLE table_name ADD  
      partition_spec [ LOCATION 'location1' ]   
      partition_spec [ LOCATION 'location2' ] ...

5.导出hive数据

会执行MapReduce。

#导出数据到本地
insert overwrite local directory '/root/student' select * from test;
##结果
[root@hadoop-1 student]# cat 000000_0 
songsongbingbinglilixiao song18xiaoxiao song19hui long guanbeijing
yangyangcaicaisusuxiao yang18xiaoxiao yang19chao yangbeijing

#将查询的结果格式化导出到本地
insert overwrite local directory '/root/student' ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t' select * from test;
##结果
[root@hadoop-1 student]# cat 000000_0 
songsong	bingbinglili	xiao song18xiaoxiao song19	hui long guanbeijing
yangyang	caicaisusu	xiao yang18xiaoxiao yang19	chao yangbeijing

#将查询的结果导出到HDFS上(没有local)
insert overwrite local directory '/student' ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t' select * from test;

6.Hadoop命令导出到本地

hive (default)> dfs -get /user/hive/warehouse/student/month=201709/000000_0 /opt/module/datas/export/student3.txt;

7.Hive Shell 命令导出

基本语法:(hive -f/-e 执行语句或者脚本 > file)

[root@hadoop-1 student]# bin/hive -e 'select * from default.student;' >

 /opt/module/datas/export/student4.txt;

8.Export导出到HDFS上

hive (default)> export table default.student to '/user/hive/warehouse/export/student';

9.清除表中数据(Truncate)

注意:Truncate只能删除管理表,不能删除外部表中数据

hive (default)> truncate table student;

五、查询

常用函数

1.求总行数(count)
hive (default)> select count(*) cnt from emp;

2.求工资的最大值(max)
hive (default)> select max(sal) max_sal from emp;

3.求工资的最小值(min)
hive (default)> select min(sal) min_sal from emp;

4.求工资的总和(sum)
hive (default)> select sum(sal) sum_sal from emp; 

5.求工资的平均值(avg)
hive (default)> select avg(sal) avg_sal from emp;

Limit语句

典型的查询会返回多行数据。LIMIT子句用于限制返回的行数。

hive (default)> select * from emp limit 5;

Where语句

1.使用WHERE子句,将不满足条件的行过滤掉

2.WHERE子句紧随FROM子句

3.案例实操

查询出薪水大于1000的所有员工

hive (default)> select * from emp where sal >1000;

比较运算符

1)查询出薪水等于5000的所有员工
hive (default)> select * from emp where sal =5000;2)查询工资在5001000的员工信息
hive (default)> select * from emp where sal between 500 and 1000;3)查询comm为空的所有员工信息
hive (default)> select * from emp where comm is null;4)查询工资是15005000的员工信息
hive (default)> select * from emp where sal IN (1500, 5000);

like/rlike

(1)查找以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]';

逻辑运算符

(1)查询薪水大于1000,部门是30
hive (default)> select * from emp where sal>1000 and deptno=30;

(2)查询薪水大于1000,或者部门是30
hive (default)> select * from emp where sal>1000 or deptno=30;

(3)查询除了20部门和30部门以外的员工信息
hive (default)> select * from emp where deptno not IN(30, 20);

Group By语句

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;

Having语句

1.having与where不同点

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

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

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

2.案例实操

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

求每个部门的平均工资

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

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

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

Join语句

等值Join

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

join…on

示例:
0: jdbc:hive2://localhost:10000/db_01> select * from tb_user join tb_site on tb_user.id=tb_site.id;
###结果
+-------------+---------------+--------------+-------------+----------------+--+
| tb_user.id  | tb_user.name  | tb_user.age  | tb_site.id  |  tb_site.desc  |
+-------------+---------------+--------------+-------------+----------------+--+
| 1           | 小花            | 19           | 1           | www.liuzhaopo  |
| 2           | 张三            | 20           | 2           | lewis.org.cn   |
+-------------+---------------+--------------+-------------+----------------+--+

#内连接
//只有进行连接的两个表中都存在与连接条件相匹配的数据才会被保留下来。
select tb_user.id,tb_user.name,tb_user.age,tb_site.desc from tb_user join tb_site on tb_user.id=tb_site.id;
###结果
+-------------+---------------+--------------+----------------+--+
| tb_user.id  | tb_user.name  | tb_user.age  |  tb_site.desc  |
+-------------+---------------+--------------+----------------+--+
| 1           | 小花            | 19           | www.liuzhaopo  |
| 2           | 张三            | 20           | lewis.org.cn   |
+-------------+---------------+--------------+----------------+--+

#左外连接
//join操作符左边表中符合WHERE子句的所有记录将会被返回。
select tb_user.id,tb_user.name,tb_user.age,tb_site.desc from tb_user left join tb_site on tb_user.id=tb_site.id;

#右外连接
//join操作符右边表中符合WHERE子句的所有记录将会被返回。
select tb_user.id,tb_user.name,tb_user.age,tb_site.desc from tb_user right join tb_site on tb_user.id=tb_site.id;

#满外连接
//将会返回所有表中符合WHERE语句条件的所有记录。如果任一表的指定字段没有符合条件的值的话,那么就使用NULL值替代。
select tb_user.id,tb_user.name,tb_user.age,tb_site.desc from tb_user full join tb_site on tb_user.id=tb_site.id;

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

##数据:location.txt
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.导入数据
load data local inpath '/opt/module/datas/location.txt' into table default.location;

3.多表连接查询
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总是按照从左到右的顺序执行的。

笛卡尔积

1.笛卡尔积会在下面条件下产生

(1)省略连接条件

(2)连接条件无效

(3)所有表中的所有行互相连接

0: jdbc:hive2://localhost:10000/bdb_01> select name,age,desc from tb_user,tb_site;

+-------+------+----------------+--+
| name  | age  |      desc      |
+-------+------+----------------+--+
| 小花    | 19   | www.liuzhaopo  |
| 张三    | 20   | www.liuzhaopo  |
| 小花    | 19   | lewis.org.cn   |
| 张三    | 20   | lewis.org.cn   |
+-------+------+----------------+--+

连接谓词中不支持or

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

= d.deptno or e.ename=d.ename; 错误的

每个MapReduce内部排序(Sort By)

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

​ 1.设置reduce个数

hive (default)> set mapreduce.job.reduces=3;

2.查看设置reduce个数

hive (default)> set mapreduce.job.reduces;

0: jdbc:hive2://localhost:10000/bdb_01> set mapreduce.job.reduces;
+---------------------------+--+
|            set            |
+---------------------------+--+
| mapreduce.job.reduces=-1  |
+---------------------------+--+
1 row selected (0.016 seconds)

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

hive (default)> select * from emp sort by empno desc;

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

hive (default)> insert overwrite local directory ‘/opt/module/datas/sortby-result’

select * from emp sort by deptno desc;

分桶表数据存储

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

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

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

数据准备:d.txt

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

#创建分桶表
create table stu_buck(id int, name string)
clustered by(id) 
into 4 buckets
row format delimited fields terminated by '\t';

#查询创建的分桶表的信息,截取一段,桶的个数是4
0: jdbc:hive2://localhost:10000/bdb_01> desc formatted stu_buck;
| Num Buckets:                  | 4                                                     
0: jdbc:hive2://localhost:10000/bdb_01> 

#加载数据到创建的分桶表
load data local inpath '/root/d.txt' into table  stu_buck;

#查看数据
0: jdbc:hive2://localhost:10000/bdb_01> select * from stu_buck;
+--------------+----------------+--+
| stu_buck.id  | stu_buck.name  |
+--------------+----------------+--+
| 1001         | ss1            |
| 1002         | ss2            |
| 1003         | ss3            |
| 1004         | ss4            |
| 1005         | ss5            |
| 1006         | ss6            |
| 1007         | ss7            |
| 1008         | ss8            |
| 1009         | ss9            |

桶抽样查询

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

查询表stu_buck中的数据。

hive (default)> 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

六、函数

系统内置函数

1.查看系统自带的函数

hive> show functions;

2.显示自带的函数的用法

hive> desc function upper;

3.详细显示自带的函数的用法

hive> desc function extended upper;

七、数据倾斜

合理设置Map数

1)通常情况下,作业会通过input的目录产生一个或者多个map任务。

主要的决定因素有:input的文件总个数,input的文件大小,集群设置的文件块大小。

2)是不是map数越多越好?

答案是否定的。如果一个任务有很多小文件(远远小于块大小128m),则每个小文件也会被当做一个块,用一个map任务来完成,而一个map任务启动和初始化的时间远远大于逻辑处理的时间,就会造成很大的资源浪费。而且,同时可执行的map数是受限的。

3)是不是保证每个map处理接近128m的文件块,就高枕无忧了?

答案也是不一定。比如有一个127m的文件,正常会用一个map去完成,但这个文件只有一个或者两个小字段,却有几千万的记录,如果map处理的逻辑比较复杂,用一个map任务去做,肯定也比较耗时。

针对上面的问题2和3,我们需要采取两种方式来解决:即减少map数和增加map数;

小文件进行合并

在map执行前合并小文件,减少map数:CombineHiveInputFormat具有对小文件进行合并的功能(系统默认的格式)。HiveInputFormat没有对小文件合并功能。

set hive.input.format= org.apache.hadoop.hive.ql.io.CombineHiveInputFormat;

复杂文件增加Map数

当input的文件都很大,任务逻辑复杂,map执行非常慢的时候,可以考虑增加Map数,来使得每个map处理的数据量减少,从而提高任务的执行效率。

增加map的方法为:根据computeSliteSize(Math.max(minSize,Math.min(maxSize,blocksize)))=blocksize=128M公式,调整maxSize最大值。让maxSize最大值低于blocksize就可以增加map的个数。

1.执行查询

hive (default)> select count(*) from emp;

Hadoop job information for Stage-1: number of mappers: 1; number of reducers: 1

2.设置最大切片值为100个字节

hive (default)> set mapreduce.input.fileinputformat.split.maxsize=100;

hive (default)> select count(*) from emp;

Hadoop job information for Stage-1: number of mappers: 6; number of reducers: 1

合理设置Reduce数

1.调整reduce个数方法一

(1)每个Reduce处理的数据量默认是256MB

hive.exec.reducers.bytes.per.reducer=2560000002)每个任务最大的reduce数,默认为1009

hive.exec.reducers.max=10093)计算reducer数的公式

N=min(参数2,总输入数据量/参数1)

2.调整reduce个数方法二

在hadoop的mapred-default.xml文件中修改

设置每个job的Reduce个数

set mapreduce.job.reduces = 15;

3.reduce个数并不是越多越好

1)过多的启动和初始化reduce也会消耗时间和资源;

2)另外,有多少个reduce,就会有多少个输出文件,如果生成了很多个小文件,那么如果这些小文件作为下一个任务的输入,则也会出现小文件过多的问题;

在设置reduce个数的时候也需要考虑这两个原则:处理大数据量利用合适的reduce数;使单个reduce任务处理数据量大小要合适;

欢迎关注我的动态

欢迎关注我的个人博客网站www.liuzhaopo.top

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值