前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >大数据技术之_08_Hive学习_04_压缩和存储(Hive高级)+ 企业级调优(Hive优化)

大数据技术之_08_Hive学习_04_压缩和存储(Hive高级)+ 企业级调优(Hive优化)

作者头像
黑泽君
发布2019-03-11 14:59:18
1K0
发布2019-03-11 14:59:18
举报

第8章 压缩和存储(Hive高级)

8.1 Hadoop源码编译支持Snappy压缩

8.1.1 资源准备

1、CentOS联网   配置CentOS能连接外网。Linux虚拟机 ping www.baidu.com 是畅通的。 注意:采用root角色编译,减少文件夹权限出现问题。 2、jar包准备(hadoop源码、JDK8、maven、protobuf) (1)hadoop-2.7.2-src.tar.gz (2)jdk-8u144-linux-x64.tar.gz (3)snappy-1.1.3.tar.gz (4)apache-maven-3.0.5-bin.tar.gz (5)protobuf-2.5.0.tar.gz

8.1.2 jar包安装

注意:所有操作必须在root用户下完成。 1、JDK解压、配置环境变量JAVA_HOME和PATH,验证java -version(如下都需要验证是否配置成功)

[root@hadoop101 software]# tar -zxf jdk-8u144-linux-x64.tar.gz -C /opt/module/
[root@hadoop101 software]# vim /etc/profile
#JAVA_HOME
export JAVA_HOME=/opt/module/jdk1.8.0_144
export PATH=$PATH:$JAVA_HOME/bin
[root@hadoop101 software]# source /etc/profile

验证命令:java -version

2、Maven解压、配置 MAVEN_HOME 和 PATH

[root@hadoop101 software]# tar -zxvf apache-maven-3.0.5-bin.tar.gz -C /opt/module/
[root@hadoop101 software]# vim /etc/profile
#MAVEN_HOME
export MAVEN_HOME=/opt/module/apache-maven-3.0.5
export PATH=$PATH:$MAVEN_HOME/bin
[root@hadoop101 software]# source /etc/profile

验证命令:mvn -version

8.1.3 编译源码

1、准备编译环境

[root@hadoop101 software]# yum install svn
[root@hadoop101 software]# yum install autoconf automake libtool cmake
[root@hadoop101 software]# yum install ncurses-devel
[root@hadoop101 software]# yum install openssl-devel
[root@hadoop101 software]# yum install gcc*

2、编译安装snappy

[root@hadoop101 software]# tar -zxvf snappy-1.1.3.tar.gz -C /opt/module/
[root@hadoop101 module]# cd snappy-1.1.3/
[root@hadoop101 snappy-1.1.3]# ./configure
[root@hadoop101 snappy-1.1.3]# make
[root@hadoop101 snappy-1.1.3]# make install

# 查看snappy库文件
[root@hadoop101 snappy-1.1.3]# ls -lh /usr/local/lib | grep snappy

3、编译安装protobuf

[root@hadoop101 software]# tar -zxvf protobuf-2.5.0.tar.gz -C /opt/module/
[root@hadoop101 module]# cd protobuf-2.5.0/
[root@hadoop101 protobuf-2.5.0]# ./configure 
[root@hadoop101 protobuf-2.5.0]# make 
[root@hadoop101 protobuf-2.5.0]# make install

# 查看protobuf版本以测试是否安装成功
[root@hadoop101 protobuf-2.5.0]# protoc --version

4、编译hadoop native

[root@hadoop101 software]# tar -zxvf hadoop-2.7.2-src.tar.gz
[root@hadoop101 software]# cd hadoop-2.7.2-src/
[root@hadoop101 software]# mvn clean package -DskipTests -Pdist,native -Dtar -Dsnappy.lib=/usr/local/lib -Dbundle.snappy

执行成功后,/opt/software/hadoop-2.7.2-src/hadoop-dist/target/hadoop-2.7.2.tar.gz 即为新生成的支持snappy压缩的二进制安装包。

8.2 Hadoop压缩配置

8.2.1 MR支持的压缩编码

为了支持多种压缩/解压缩算法,Hadoop引入了编码/解码器,如下表所示。

压缩性能的比较:

http://google.github.io/snappy/ On a single core of a Core i7 processor in 64-bit mode, Snappy compresses at about 250 MB/sec or more and decompresses at about 500 MB/sec or more.

8.2.2 压缩参数配置

  要在Hadoop中启用压缩,可以配置如下参数(mapred-site.xml文件中):

8.3 开启Map输出阶段压缩

  开启 map 输出阶段压缩可以减少 job 中 map 和 Reduce task 间数据传输量。具体配置如下: 案例实操: 1、开启hive中间传输数据压缩功能

hive (default)> set hive.exec.compress.intermediate=true;

2、开启mapreduce中map输出压缩功能

hive (default)> set mapreduce.map.output.compress=true;

3、设置mapreduce中map输出数据的压缩方式

hive (default)> set mapreduce.map.output.compress.codec=org.apache.hadoop.io.compress.SnappyCodec;

4、执行查询语句

hive (default)> select count(ename) name from emp;

5、浏览器端查看历史服务器中的设置是否生效

8.4 开启Reduce输出阶段压缩

  当 Hive 将输出写入到表中时,输出内容同样可以进行压缩。属性 hive.exec.compress.output 控制着这个功能。用户可能需要保持默认设置文件中的默认值 false,这样默认的输出就是非压缩的纯文本文件了。用户可以通过在查询语句或执行脚本中设置这个值为 true,来开启输出结果压缩功能。 案例实操: 1、开启hive最终输出数据压缩功能

hive (default)> set hive.exec.compress.output=true;

2、开启mapreduce最终输出数据压缩

hive (default)> set set hive.exec.compress.output=true;

3、设置mapreduce最终数据输出压缩方式

hive (default)> set mapreduce.output.fileoutputformat.compress.codec=org.apache.hadoop.io.compress.SnappyCodec;

4、设置mapreduce最终数据输出压缩为块压缩(默认是行压缩RECORD)

hive (default)> set mapreduce.output.fileoutputformat.compress.type=BLOCK;

5、浏览器端查看历史服务器中的设置是否生效

6、测试一下输出结果是否是压缩文件

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

查看,是压缩文件

[atguigu@hadoop102 snappy-result]$ pwd
/opt/module/datas/snappy-result
[atguigu@hadoop102 snappy-result]$ ll
总用量 4
-rw-r--r--. 1 atguigu atguigu 446 2月  27 22:53 000000_0.snappy

8.5 文件存储格式

  Hive支持的存储数的格式主要有:TEXTFILE 、SEQUENCEFILE、ORC、PARQUET。

8.5.1 列式存储和行式存储

  如上图所示左边为逻辑表,右边第一个为行式存储,第二个为列式存储。 1、行存储的特点   查询满足条件的一整行数据的时候,列存储则需要去每个聚集的字段找到对应的每个列的值,行存储只需要找到其中一个值,其余的值都在相邻地方,所以此时行存储查询的速度更快。 2、列存储的特点   因为每个字段的数据聚集存储,在查询只需要少数几个字段的时候,能大大减少读取的数据量;每个字段的数据类型一定是相同的,列式存储可以针对性的设计更好的压缩算法。 TEXTFILE和SEQUENCEFILE的存储格式都是基于行存储的。 ORC和PARQUET是基于列式存储的。

8.5.2 TextFile格式

  默认格式,数据不做压缩,磁盘开销大,数据解析开销大。可结合Gzip、Bzip2使用,但使用Gzip这种方式,hive不会对数据进行切分,从而无法对数据进行并行操作。

8.5.3 Orc格式

  Orc (Optimized Row Columnar)是Hive 0.11版里引入的新的存储格式。   如下图所示可以看到每个Orc文件由1个或多个stripe组成,每个stripe250MB大小,这个Stripe实际相当于RowGroup概念,不过大小由4MB->250MB,这样应该能提升顺序读的吞吐率。每个Stripe里有三部分组成,分别是Index Data,Row Data,Stripe Footer:

  1)Index Data:一个轻量级的index,默认是每隔1W行做一个索引。这里做的索引应该只是记录某行的各字段在Row Data中的offset(偏移量)。   2)Row Data:存的是具体的数据,先取部分行,然后对这些行按列进行存储。对每个列进行了编码,分成多个Stream来存储。   3)Stripe Footer:存的是各个Stream的类型,长度等信息。   每个文件有一个File Footer,这里面存的是每个Stripe的行数,每个Column的数据类型信息等;每个文件的尾部是一个PostScript,这里面记录了整个文件的压缩类型以及FileFooter的长度信息等。在读取文件时,会seek到文件尾部读PostScript,从里面解析到File Footer长度,再读FileFooter,从里面解析到各个Stripe信息,再读各个Stripe,即从后往前读。

8.5.4 Parquet格式

  arquet是面向分析型业务的列式存储格式,由Twitter和Cloudera合作开发,2015年5月从Apache的孵化器里毕业成为Apache顶级项目。   Parquet文件是以二进制方式存储的,所以是不可以直接读取的,文件中包括该文件的数据和元数据,因此Parquet格式文件是自解析的。   通常情况下,在存储Parquet数据的时候会按照Block大小设置行组的大小,由于一般情况下每一个Mapper任务处理数据的最小单位是一个Block,这样可以把每一个行组由一个Mapper任务处理,增大任务执行并行度。Parquet文件的格式如下图所示。

  上图展示了一个Parquet文件的内容,一个文件中可以存储多个行组,文件的首位都是该文件的Magic Code,用于校验它是否是一个Parquet文件,Footer length记录了文件元数据的大小,通过该值和文件长度可以计算出元数据的偏移量,文件的元数据中包括每一个行组的元数据信息和该文件存储数据的Schema信息。除了文件中每一个行组的元数据,每一页的开始都会存储该页的元数据,在Parquet中,有三种类型的页:数据页、字典页和索引页。数据页用于存储当前行组中该列的值,字典页存储该列值的编码字典,每一个列块中最多包含一个字典页,索引页用来存储当前行组下该列的索引,目前Parquet中还不支持索引页

8.5.5 主流文件存储格式对比实验

  从存储文件的压缩比和查询速度两个角度对比。

存储文件的压缩比测试: 1、测试数据   将log.data上传至hdfs中的/opt/module/datas目录下 2、TextFile (1)创建表,存储数据格式为TEXTFILE

create table log_text(
track_time string,
url string,
session_id string,
referer string,
ip string,
end_user_id string,
city_id string
)
row format delimited fields terminated by '\t'
stored as textfile;

(2)向表中加载数据(load命令本质是put,存储的格式是TextFile)

load data local inpath '/opt/module/datas/log.data' into table log_text;

(3)查看表中数据大小

dfs -du -h /user/hive/warehouse/log_text;
+-------------------------------------------------+--+
|                   DFS Output                    |
+-------------------------------------------------+--+
| 18.1 M  /user/hive/warehouse/log_text/log.data  |
+-------------------------------------------------+--+

3、Orc (1)创建表,存储数据格式为Orc

create table log_orc(
track_time string,
url string,
session_id string,
referer string,
ip string,
end_user_id string,
city_id string
)
row format delimited fields terminated by '\t'
stored as orc;

(2)向表中加载数据(不能使用load方式加载数据,需要insert into方式,即一定要通过MapReduce任务加载数据)

insert into table log_orc select * from log_text;

(3)查看表中数据大小

dfs -du -h /user/hive/warehouse/log_orc;
+-----------------------------------------------+--+
|                  DFS Output                   |
+-----------------------------------------------+--+
| 2.8 M  /user/hive/warehouse/log_orc/000000_0  |
+-----------------------------------------------+--+

3、Parquet (1)创建表,存储数据格式为parquet

create table log_parquet(
track_time string,
url string,
session_id string,
referer string,
ip string,
end_user_id string,
city_id string
)
row format delimited fields terminated by '\t'
stored as parquet;

(2)向表中加载数据

insert into table log_parquet select * from log_text;

(3)查看表中数据大小

dfs -du -h /user/hive/warehouse/log_parquet;
+----------------------------------------------------+--+
|                     DFS Output                     |
+----------------------------------------------------+--+
| 13.1 M  /user/hive/warehouse/log_parquet/000000_0  |
+----------------------------------------------------+--+

存储文件的压缩比总结:ORC > Parquet > textFile


存储文件的查询速度测试: 1、TextFile

select count(*) from log_text;
+---------+--+
|   _c0   |
+---------+--+
| 100000  |
+---------+--+
1 row selected (20.145 seconds)

2、ORC

select count(*) from log_orc;
+---------+--+
|   _c0   |
+---------+--+
| 100000  |
+---------+--+
1 row selected (20.44 seconds)

3、Parquet

select count(*) from log_parquet;
+---------+--+
|   _c0   |
+---------+--+
| 100000  |
+---------+--+
1 row selected (17.945 seconds)

存储文件的查询速度总结:查询速度相近。 小结:在公司的Hive中对数据压缩使用的压缩格式是snappy,存储文件的格式使用的ORC格式。

8.6 存储和压缩结合

8.6.1 修改Hadoop集群具有Snappy压缩方式

1、查看hadoop checknative命令使用

[atguigu@hadoop102 hadoop-2.7.2]$ hadoop
Usage: hadoop [--config confdir] [COMMAND | CLASSNAME]
  CLASSNAME            run the class named CLASSNAME
 or
  where COMMAND is one of:
  fs                   run a generic filesystem user client
  version              print the version
  jar <jar>            run a jar file
                       note: please use "yarn jar" to launch
                             YARN applications, not this command.
  checknative [-a|-h]  check native hadoop and compression libraries availability
  distcp <srcurl> <desturl> copy file or directories recursively
  archive -archiveName NAME -p <parent path> <src>* <dest> create a hadoop archive
  classpath            prints the class path needed to get the
  credential           interact with credential providers
                       Hadoop jar and the required libraries
  daemonlog            get/set the log level for each daemon
  trace                view and modify Hadoop tracing settings

Most commands print help when invoked w/o parameters.

2、查看hadoop支持的压缩方式

[atguigu@hadoop102 hadoop-2.7.2]$ hadoop checknative
19/02/27 19:18:38 WARN bzip2.Bzip2Factory: Failed to load/initialize native-bzip2 library system-native, will use pure-Java version
19/02/27 19:18:38 INFO zlib.ZlibFactory: Successfully loaded & initialized native-zlib library
Native library checking:
hadoop:  true /opt/module/hadoop-2.7.2/lib/native/libhadoop.so
zlib:    true /lib64/libz.so.1
snappy:  false 
lz4:     true revision:99
bzip2:   false 
openssl: false Cannot load libcrypto.so (libcrypto.so: 无法打开共享对象文件: 没有那个文件或目录)!

3、将编译好的支持Snappy压缩的hadoop-2.7.2.tar.gz包导入到hadoop102的/opt/software/中 4、解压hadoop-2.7.2.tar.gz到当前路径

[atguigu@hadoop102 hadoop-snappy]$ pwd
/opt/software/hadoop-snappy
[atguigu@hadoop102 hadoop-snappy]$ tar -zxvf hadoop-2.7.2.tar.gz

5、进入到/opt/software/hadoop-snappy/hadoop-2.7.2/lib/native路径可以看到支持Snappy压缩的动态链接库

[atguigu@hadoop102 native]$ pwd
/opt/software/hadoop-snappy/hadoop-2.7.2/lib/native
[atguigu@hadoop102 native]$ ll
总用量 5188
-rw-r--r--. 1 atguigu atguigu 1210260 9月   1 2017 libhadoop.a
-rw-r--r--. 1 atguigu atguigu 1487268 9月   1 2017 libhadooppipes.a
lrwxrwxrwx. 1 atguigu atguigu      18 2月  27 20:00 libhadoop.so -> libhadoop.so.1.0.0
-rwxr-xr-x. 1 atguigu atguigu  716316 9月   1 2017 libhadoop.so.1.0.0
-rw-r--r--. 1 atguigu atguigu  582048 9月   1 2017 libhadooputils.a
-rw-r--r--. 1 atguigu atguigu  364860 9月   1 2017 libhdfs.a
lrwxrwxrwx. 1 atguigu atguigu      16 2月  27 20:00 libhdfs.so -> libhdfs.so.0.0.0
-rwxr-xr-x. 1 atguigu atguigu  229113 9月   1 2017 libhdfs.so.0.0.0
-rw-r--r--. 1 atguigu atguigu  472950 9月   1 2017 libsnappy.a
-rwxr-xr-x. 1 atguigu atguigu     955 9月   1 2017 libsnappy.la
lrwxrwxrwx. 1 atguigu atguigu      18 2月  27 20:00 libsnappy.so -> libsnappy.so.1.3.0
lrwxrwxrwx. 1 atguigu atguigu      18 2月  27 20:00 libsnappy.so.1 -> libsnappy.so.1.3.0
-rwxr-xr-x. 1 atguigu atguigu  228177 9月   1 2017 libsnappy.so.1.3.0

6、拷贝/opt/software/hadoop-snappy/hadoop-2.7.2/lib/native里面的所有内容到开发集群的/opt/module/hadoop-2.7.2/lib/native路径上

[atguigu@hadoop102 native]$ cp ../native/* /opt/module/hadoop-2.7.2/lib/native/

7、分发集群

[atguigu@hadoop102 lib]$ xsync native/

8、再次查看hadoop支持的压缩类型

[atguigu@hadoop102 lib]$ hadoop checknative
19/02/27 20:07:28 WARN bzip2.Bzip2Factory: Failed to load/initialize native-bzip2 library system-native, will use pure-Java version
19/02/27 20:07:28 INFO zlib.ZlibFactory: Successfully loaded & initialized native-zlib library
Native library checking:
hadoop:  true /opt/module/hadoop-2.7.2/lib/native/libhadoop.so
zlib:    true /lib64/libz.so.1
snappy:  true /opt/module/hadoop-2.7.2/lib/native/libsnappy.so.1
lz4:     true revision:99
bzip2:   false 
openssl: false Cannot load libcrypto.so (libcrypto.so: 无法打开共享对象文件: 没有那个文件或目录)!

9、重新启动hadoop集群、zookeeper集群、hive、历史服务器

[atguigu@hadoop102 hadoop-2.7.2]$ sbin/start-dfs.sh -- 启动dfs集群
[atguigu@hadoop103 hadoop-2.7.2]$ sbin/start-yarn.sh -- 启动yarn集群
[atguigu@hadoop102 hive]$ zkstart.sh -- 启动zookeeper集群
[atguigu@hadoop102 hive]$ bin/hive -- 启动hive
[atguigu@hadoop102 hadoop-2.7.2]$ sbin/mr-jobhistory-daemon.sh start historyserver -- 启动历史服务器
8.6.2 测试存储和压缩

官网:https://cwiki.apache.org/confluence/display/Hive/LanguageManual+ORC ORC存储方式的压缩:

1、创建一个非压缩的的ORC存储方式 (1)建表语句

create table log_orc_none(
track_time string,
url string,
session_id string,
referer string,
ip string,
end_user_id string,
city_id string
)
row format delimited fields terminated by '\t'
stored as orc tblproperties ("orc.compress"="NONE");

(2)插入数据

insert into table log_orc_none select * from log_text;

(3)查看插入后数据

dfs -du -h /user/hive/warehouse/log_orc_none/;
+----------------------------------------------------+--+
|                     DFS Output                     |
+----------------------------------------------------+--+
| 7.7 M  /user/hive/warehouse/log_orc_none/000000_0  |
+----------------------------------------------------+--+

2、创建一个SNAPPY压缩的ORC存储方式 (1)建表语句

create table log_orc_snappy(
track_time string,
url string,
session_id string,
referer string,
ip string,
end_user_id string,
city_id string
)
row format delimited fields terminated by '\t'
stored as orc tblproperties ("orc.compress"="SNAPPY");

(2)插入数据

insert into table log_orc_snappy select * from log_text;

(3)查看插入后数据

dfs -du -h /user/hive/warehouse/log_orc_snappy/;
+------------------------------------------------------+--+
|                      DFS Output                      |
+------------------------------------------------------+--+
| 3.8 M  /user/hive/warehouse/log_orc_snappy/000000_0  |
+------------------------------------------------------+--+

3、上一节中默认创建的ORC存储方式,导入数据后的大小为   2.8 M /user/hive/warehouse/log_orc/000000_0   比Snappy压缩的还小。原因是orc存储文件默认采用ZLIB压缩。ZLIB压缩率比snappy的小,但是ZLIB解压缩速率很低。 4、存储方式和压缩总结   在实际的项目开发当中,hive表的数据存储格式一般选择:orc或parquet。压缩方式一般选择snappy或lzo。

第9章 企业级调优(Hive优化)

9.1 Fetch抓取

  Fetch抓取是指,Hive中对某些情况的查询可以不必使用MapReduce计算。例如:SELECT * FROM employees; 在这种情况下,Hive可以简单地读取employee对应的存储目录下的文件,然后输出查询结果到控制台。   在hive-default.xml.template文件中 hive.fetch.task.conversion 默认是 more,老版本hive默认是minimal,该属性修改为more以后,在全局查找、字段查找、limit查找等都不走MapReduce计算

<property>
    <name>hive.fetch.task.conversion</name>
    <value>more</value>
    <description>
      Expects one of [none, minimal, more].
      Some select queries can be converted to single FETCH task minimizing latency.
      Currently the query should be single sourced not having any subquery and should not have
      any aggregations or distincts (which incurs RS), lateral views and joins.
      0. none : disable hive.fetch.task.conversion
      1. minimal : SELECT STAR, FILTER on partition columns, LIMIT only
      2. more  : SELECT, FILTER, LIMIT only (support TABLESAMPLE and virtual columns)
    </description>
</property>

案例实操: 1)把hive.fetch.task.conversion设置成none,然后执行查询语句,都会执行MapReduce程序。

hive (default)> set hive.fetch.task.conversion=none;
hive (default)> select * from emp;
hive (default)> select ename from emp;
hive (default)> select ename from emp limit 3;

9.2 本地模式

  大多数的 Hadoop Job 是需要 Hadoop 提供的完整的可扩展性来处理大数据集的。不过,有时 Hive 的输入数据量是非常小的。在这种情况下,为查询触发执行任务消耗的时间可能会比实际job的执行时间要多的多。对于大多数这种情况,Hive可以通过本地模式在单台机器上处理所有的任务。对于小数据集,执行时间可以明显被缩短。   用户可以通过设置 hive.exec.mode.local.auto 的值为 true ,来让 Hive 在适当的时候自动启动这个优化。

set hive.exec.mode.local.auto=true;  // 开启本地mr模式

// 设置local mr的最大输入数据量,当输入数据量小于这个值时采用local mr的方式,默认为134217728,即128M
set hive.exec.mode.local.auto.inputbytes.max=50000000;

// 设置local mr的最大输入文件个数,当输入文件个数小于这个值时采用local mr的方式,默认为4
set hive.exec.mode.local.auto.input.files.max=10;

案例实操: 1)开启本地模式,并执行查询语句

set hive.exec.mode.local.auto=true;
select count(*) from log_orc;
+---------+--+
|   _c0   |
+---------+--+
| 100000  |
+---------+--+
1 row selected (1.382 seconds)

2)关闭本地模式,并执行查询语句

set hive.exec.mode.local.auto=false;
select count(*) from log_orc;
+---------+--+
|   _c0   |
+---------+--+
| 100000  |
+---------+--+
1 row selected (16.895 seconds)

9.3 表的优化

9.3.1 小表join大表、大表join小表

  将key相对分散,并且数据量小的表放在join的左边,这样可以有效减少内存溢出错误发生的几率;再进一步,可以使用map join让小的维度表(1000条以下的记录条数)先进内存。在map端完成reduce。 实际测试发现:新版的hive已经对小表JOIN大表和大表JOIN小表进行了优化。小表放在左边和右边已经没有明显区别。 案例实操 1、需求   测试大表JOIN小表和小表JOIN大表的效率。 2、建大表、小表和JOIN后表的语句

// 创建大表
create table bigtable(
id bigint, time bigint, uid string, keyword string, url_rank int, click_num int, click_url string
)
row format delimited fields terminated by '\t';

// 创建小表
create table smalltable(
id bigint, time bigint, uid string, keyword string, url_rank int, click_num int, click_url string
)
row format delimited fields terminated by '\t';

// 创建join后表的语句
create table jointable(
id bigint, time bigint, uid string, keyword string, url_rank int, click_num int, click_url string
)
row format delimited fields terminated by '\t';

3、分别向大表和小表中导入数据

load data local inpath '/opt/module/datas/bigtable' into table bigtable;
load data local inpath '/opt/module/datas/smalltable' into table smalltable;

4、关闭mapjoin功能(默认是打开的)

set hive.auto.convert.join=false;

5、执行小表JOIN大表语句

insert overwrite table jointable
select b.id, b.time, b.uid, b.keyword, b.url_rank, b.click_num, b.click_url
from smalltable s
left join bigtable b
on b.id = s.id;

No rows affected (31.015 seconds)

6、执行大表JOIN小表语句

insert overwrite table jointable
select b.id, b.time, b.uid, b.keyword, b.url_rank, b.click_num, b.click_url
from bigtable b
left join smalltable s
on s.id = b.id;

No rows affected (32.59 seconds)
9.3.2 大表Join大表

1、空KEY过滤   有时join超时是因为某些key对应的数据太多,而相同key对应的数据都会发送到相同的reducer上,从而导致内存不够。此时我们应该仔细分析这些异常的key,很多情况下,这些key对应的数据是异常数据,我们需要在SQL语句中进行过滤。例如:设置key对应的字段为空,操作如下: 案例实操 (1)配置历史服务器 配置mapred-site.xml

<property>
    <name>mapreduce.jobhistory.address</name>
    <value>hadoop102:10020</value>
</property>
<property>
    <name>mapreduce.jobhistory.webapp.address</name>
    <value>hadoop102:19888</value>
</property>

启动历史服务器

[atguigu@hadoop102 hadoop-2.7.2]$ sbin/mr-jobhistory-daemon.sh start historyserver

查看jobhistory http://hadoop102:19888/jobhistory (2)创建原始数据表、空id表、合并后的数据表

// 创建原始表
create table ori(
id bigint, time bigint, uid string, keyword string, url_rank int, click_num int, click_url string
)
row format delimited fields terminated by '\t';

// 创建空id表
create table nullidtable(
id bigint, time bigint, uid string, keyword string, url_rank int, click_num int, click_url string
)
row format delimited fields terminated by '\t';

// 创建join后的表
create table jointable(
id bigint, time bigint, uid string, keyword string, url_rank int, click_num int, click_url string
)
row format delimited fields terminated by '\t';

(3)分别加载原始数据和空id数据到对应表中

load data local inpath '/opt/module/datas/ori' into table ori;
load data local inpath '/opt/module/datas/nullid' into table nullidtable;

(4)测试不过滤空id

insert overwrite table jointable 
select n.* from nullidtable n left join ori o on n.id=o.id;

No rows affected (40.267 seconds) (5)测试过滤空id

insert overwrite table jointable 
select n.* from (select * from nullidtable where id is not null) n left join ori o on n.id=o.id;

No rows affected (25.801 seconds)

2、空key转换   有时虽然某个key为空对应的数据很多,但是相应的数据不是异常数据,必须要包含在join的结果中,此时我们可以表a中key为空的字段赋一个随机的值,使得数据随机均匀地分不到不同的reducer上。 案例实操:


不随机分布空null值的情形: (1)设置5个reduce个数

set mapreduce.job.reduces=5;

(2)JOIN两张表

insert overwrite table jointable
select n.* from nullidtable n left join ori b on n.id=b.id;

结果:如下图所示,可以看出来,出现了数据倾斜,某些reducer的资源消耗远大于其他reducer。

随机分布空null值的情形: (1)设置5个reduce个数

set mapreduce.job.reduces=5;

(2)JOIN两张表

insert overwrite table jointable
select n.* from nullidtable n full join ori o on 
case when n.id is null then concat('hive', rand()) else n.id end=o.id;

结果:如下图所示,可以看出来,消除了数据倾斜,负载均衡reducer的资源消耗。

9.3.3 MapJoin

  如果不指定MapJoin或者不符合MapJoin的条件,那么Hive解析器会将Join操作转换成Common Join,即:在Reduce阶段完成join。容易发生数据倾斜。可以用MapJoin把小表全部加载到内存在map端进行join,避免reducer处理。 1、开启MapJoin参数设置 (1)设置自动选择Mapjoin

set hive.auto.convert.join=true; -- 默认为true

(2)大表小表的阈值设置(默认25M以下认为是小表):

set hive.mapjoin.smalltable.filesize=25000000;

2、MapJoin工作机制,如下图所示

案例实操: (1)开启Mapjoin功能

set hive.auto.convert.join=true; -- 默认为true

(2)执行小表JOIN大表语句

insert overwrite table jointable
select b.id, b.time, b.uid, b.keyword, b.url_rank, b.click_num, b.click_url
from smalltable s
join bigtable b
on s.id=b.id;

No rows affected (24.594 seconds) (3)执行大表JOIN小表语句

insert overwrite table jointable
select b.id, b.time, b.uid, b.keyword, b.url_rank, b.click_num, b.click_url
from bigtable b
join smalltable s
on s.id=b.id;

No rows affected (24.315 seconds)

9.3.4 group by

  默认情况下,Map阶段同一key数据分发给一个Reduce,当一个key数据过大时就倾斜了。   并不是所有的聚合操作都需要在Reduce端完成,很多聚合操作都可以先在Map端进行部分聚合(预处理),最后在Reduce端得出最终结果。(类似于Combine) 1、开启Map端聚合参数设置 (1)是否在Map端进行聚合,默认为true

set hive.map.aggr=true;

(2)设置在Map端进行聚合操作的条目数目

set hive.groupby.mapaggr.checkinterval=100000;

(3)有数据倾斜的时候进行负载均衡(默认是false)

set hive.groupby.skewindata=true;

当选项设定为 true,生成的查询计划会有两个MR Job。第一个MR Job中,Map的输出结果会随机分布到Reduce中,每个Reduce做部分聚合操作,并输出结果,这样处理的结果是相同的group by key有可能被分发到不同的Reduce中,从而达到负载均衡的目的;第二个MR Job再根据预处理的数据结果按照group by key分布到Reduce中(这个过程可以保证相同的group by key被分布到同一个Reduce中),最后完成最终的聚合操作。

9.3.5 Count(Distinct) 去重统计

  数据量小的时候无所谓,数据量大的情况下,由于COUNT DISTINCT操作需要用一个Reduce Task来完成,这一个Reduce需要处理的数据量太大,就会导致整个Job很难完成,一般COUNT DISTINCT使用先GROUP BY再COUNT的方式替换。 案例实操 1、创建一张大表

create table bigtable(
id bigint, time bigint, uid string, keyword string, url_rank int, click_num int, click_url string
) 
row format delimited fields terminated by '\t';

2、加载数据

load data local inpath '/opt/module/datas/bigtable' into table bigtable;

3.设置5个reduce个数

set mapreduce.job.reduces=5;

4、执行去重id查询(只能用一个Reduce)

select count(distinct id) from bigtable;

+--------+--+
|   c0   |
+--------+--+
| 99947  |
+--------+--+
1 row selected (46.446 seconds)

5、采用GROUP BY去重id(可以使用多个Reduce,子查询帮我们做去重工作,把数据分发给了5个Reduce进行去重处理,大数据量的情况下效率高)

select count(id) from (select id from bigtable group by id) a;

+--------+--+
|  _c0   |
+--------+--+
| 99947  |
+--------+--+
1 row selected (78.134 seconds)

虽然会多用一个Job来完成,但在数据量大的情况下,这个绝对是值得的

9.3.6 笛卡尔积

  尽量避免笛卡尔积,join的时候不加on条件,或者无效的on条件,Hive只能使用1个reducer来完成笛卡尔积(笛卡尔积过大会撑爆内存)。

9.3.7 行列过滤

  列处理:在SELECT中,只拿需要的列,如果有,尽量使用分区过滤,少用SELECT *。   行处理:在分区剪裁中,当使用外关联时,如果将副表的过滤条件写在Where后面,那么就会先全表关联,之后再过滤,比如: 案例实操: 1、测试先关联两张表,再用where条件过滤

select o.id from bigtable b
join ori o on o.id=b.id
where o.id<=10;

100 rows selected (23.533 seconds)

2、通过子查询先过滤后,再关联表(推荐使用)(谓词下推:先过滤再关联

select b.id from bigtable b
join (select id from ori where id<=10) o on b.id=o.id;

100 rows selected (22.041 seconds)
9.3.8 动态分区调整

  关系型数据库中,对分区表insert数据时候,数据库自动会根据分区字段的值,将数据插入到相应的分区中,Hive中也提供了类似的机制,即动态分区(Dynamic Partition),只不过,使用Hive的动态分区,需要进行相应的配置。 1、开启动态分区参数设置 (1)开启动态分区功能(默认true,开启)

set hive.exec.dynamic.partition=true;

(2)设置为非严格模式(动态分区的模式,默认strict,表示必须指定至少一个分区为静态分区,nonstrict模式表示允许所有的分区字段都可以使用动态分区。)

set hive.exec.dynamic.partition.mode=nonstrict;

(3)在所有执行MR的节点上,最大一共可以创建多少个动态分区。

set hive.exec.max.dynamic.partitions=1000;

(4)在每个执行MR的节点上,最大可以创建多少个动态分区。该参数需要根据实际的数据来设定。比如:源数据中包含了一年的数据,即day字段有365个值,那么该参数就需要设置成大于365,如果使用默认值100,则会报错。

set hive.exec.max.dynamic.partitions.pernode=100;

(5)整个MR Job中,最大可以创建多少个HDFS文件。

set hive.exec.max.created.files=100000;

(6)当有空分区生成时,是否抛出异常。一般不需要设置,默认值是false,表示不抛出异常。

set hive.error.on.empty.partition=false;

2、案例实操1:将从静态分区中查询到的数据按照分区字段(p_time),动态地放置在动态分区中。   需求:将ori中的数据按照时间(如:20111230000008),插入到目标分区表ori_partitioned_target的相应分区中。 (1)创建分区表

create table ori_partitioned(
id bigint, time bigint, uid string, keyword string, url_rank int, click_num int, click_url string
) 
partitioned by(p_time bigint) 
row format delimited fields terminated by '\t';

(2)加载数据到分区表中(静态分区)

load data local inpath '/opt/module/datas/ds1' into table ori_partitioned partition(p_time='20111230000010');
load data local inpath '/opt/module/datas/ds2' into table ori_partitioned partition(p_time='20111230000011');

(3)创建目标分区表

create table ori_partitioned_target(
id bigint, time bigint, uid string, keyword string, url_rank int, click_num int, click_url string
)
partitioned by(p_time string)
row format delimited fields terminated by '\t';

(4)设置动态分区,并向分区动态地插入数据

set hive.exec.dynamic.partition=true;
set hive.exec.dynamic.partition.mode=nonstrict;
set hive.exec.max.dynamic.partitions=1000;
set hive.exec.max.dynamic.partitions.pernode=100;
set hive.exec.max.created.files=100000;
set hive.error.on.empty.partition=false;

insert overwrite table ori_partitioned_target partition(p_time) 
select id, time, uid, keyword, url_rank, click_num, click_url, p_time from ori_partitioned;

(5)查看目标分区表的分区情况

show partitions ori_partitioned_target;

3、案例实操2:将从普通表中查询到的数据按照分区字段(deptno),动态地放置在动态分区中。 (1)创建原始表(管理表)

create table if not exists default.emp(
empno int,
ename string,
job string,
mgr int,
hiredate string, 
sal double, 
comm double,
deptno int
)
row format delimited fields terminated by '\t';

(2)加载数据到管理表中

load data local inpath '/opt/module/datas/emp.txt' into table default.emp;

(3)创建目标分区表

create table if not exists default.emp_partiton1(
empno int,
ename string,
job string,
mgr int,
hiredate string, 
sal double, 
comm double
)
partitioned by(deptnoooooo int)
row format delimited fields terminated by '\t';

(4)设置动态分区,并向分区动态地插入数据

set hive.exec.dynamic.partition=true;
set hive.exec.dynamic.partition.mode=nonstrict;
set hive.exec.max.dynamic.partitions=1000;
set hive.exec.max.dynamic.partitions.pernode=100;
set hive.exec.max.created.files=100000;
set hive.error.on.empty.partition=false;

insert overwrite table emp_partiton1 partition(deptnoooooo) 
select empno, ename, job, mgr, hiredate, sal, comm, deptno from emp;

(5)查看目标分区表的分区情况

show partitions emp_partiton1;

+-----------------+--+
|    partition    |
+-----------------+--+
| deptnoooooo=10  |
| deptnoooooo=20  |
| deptnoooooo=30  |
+-----------------+--+

注意细节1:原始表字段=分区表字段+分区字段 注意细节2:插入数据的字段顺序要与创建原始表的顺序一致。 注意细节3:分区字段的名称可以任意起。分区字段可以任意选取。注意对应关系即可。

9.3.9 分桶

  详见6.6章。

9.3.10 分区

  详见4.6章。

9.4 数据倾斜

9.4.1 合理设置 Map 数

1)通常情况下,作业会通过 input 的目录产生一个或者多个 map 任务。   主要的决定因素有:input的文件总个数,input的文件大小,集群设置的文件块大小。

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

3)是不是保证每个 map 处理接近128m的文件块,就高枕无忧了?   答案也是不一定。比如有一个127m的文件,正常会用一个map去完成,但这个文件只有一个或者两个小字段,却有几千万的记录,而且如果map处理的逻辑比较复杂,用一个map任务去做(map()方法是按行调用),肯定也比较耗时。   针对上面的问题2和3,我们需要采取两种方式来解决:即减少map数和增加map数。

9.4.2 小文件进行合并

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

set hive.input.format=org.apache.hadoop.hive.ql.io.CombineHiveInputFormat;
9.4.3 复杂文件增加 Map 数

  当input的文件都很大,任务逻辑处理复杂,map 执行非常慢的时候,可以考虑增加 Map 数,来使得每个map处理的数据量减少,从而提高任务的执行效率。   增加map的方法为:根据computeSliteSize(Math.max(minSize,Math.min(maxSize,blocksize)))=blocksize=128M公式,调整maxSize最大值。让maxSize最大值低于blocksize就可以增加map的个数。 案例实操: 1、执行查询

set mapreduce.job.reduces=-1; -- 设置mapreduce的个数

select count(*) from emp;
Hadoop job information for Stage-1: number of mappers: 1; number of reducers: 1

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

set mapreduce.input.fileinputformat.split.maxsize;
+----------------------------------------------------------+--+
|                           set                            |
+----------------------------------------------------------+--+
| mapreduce.input.fileinputformat.split.maxsize=256000000  |
+----------------------------------------------------------+--+

set mapreduce.input.fileinputformat.split.maxsize=100;

select count(*) from emp;
Hadoop job information for Stage-1: number of mappers: 6; number of reducers: 1
9.4.4 合理设置 Reduce 数

1、调整 reduce 个数方法一 (1)每个Reduce处理的数据量默认是256MB

hive.exec.reducers.bytes.per.reducer=256000000

(2)每个任务最大的reduce数,默认为1009

hive.exec.reducers.max=1009

(3)计算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任务处理数据量大小要合适

9.5 并行执行

  Hive会将一个查询转化成一个或者多个阶段。这样的阶段可以是MapReduce阶段、抽样阶段、合并阶段、limit阶段。或者Hive执行过程中可能需要的其他阶段。默认情况下,Hive一次只会执行一个阶段。不过,某个特定的job可能包含众多的阶段,而这些阶段可能并非完全互相依赖的,也就是说有些阶段是可以并行执行的,这样可能使得整个job的执行时间缩短。不过,如果有更多的阶段可以并行执行,那么job可能就越快完成。   通过设置参数 hive.exec.parallel 值为 true,就可以开启并发执行。不过,在共享集群中,需要注意下,如果job中并行阶段增多,那么集群利用率就会增加。

set hive.exec.parallel=true;              // 打开任务并行执行
set hive.exec.parallel.thread.number=16;  // 同一个sql允许最大并行度,默认为8

当然,得是在系统资源比较空闲的时候才有优势,否则,没资源,并行也起不来。

9.6 严格模式

  Hive提供了一个严格模式,可以防止用户执行那些可能意想不到的不好的影响的查询。   通过设置属性hive.mapred.mode值为默认是非严格模式nonstrict。开启严格模式需要修改 hive.mapred.mode 值为 strict,开启严格模式可以禁止3种类型的查询。 hive-default.xml.template

<property>
    <name>hive.mapred.mode</name>
    <value>strict</value>
    <description>
      The mode in which the Hive operations are being performed. 
      In strict mode, some risky queries are not allowed to run. They include:
        Cartesian Product.
        No partition being picked up for a query.
        Comparing bigints and strings.
        Comparing bigints and doubles.
        Orderby without limit.
    </description>
</property>

  1) 对于分区表,除非 where 语句中含有分区字段过滤条件来限制范围,否则不允许执行。换句话说,就是用户不允许扫描所有分区。进行这个限制的原因是,通常分区表都拥有非常大的数据集,而且数据增加迅速。没有进行分区限制的查询可能会消耗令人不可接受的巨大资源来处理这个表。 演示示例:

select * from emp_partiton;

  2) 对于使用了 order by 语句的查询,要求必须使用limit语句。因为 order by 为了执行排序过程会将所有的结果数据分发到同一个Reducer中进行处理,强制要求用户增加这个 limit 语句可以防止Reducer额外执行很长一段时间。 演示示例:

select * from emp order by sal;

  3) 限制笛卡尔积的查询。对关系型数据库非常了解的用户可能期望在执行 join 查询的时候不使用 on 语句而是使用where语句,这样关系数据库的执行优化器就可以高效地将 where 语句转化成那个 on 语句。不幸的是,Hive并不会执行这种优化,因此,如果表足够大,那么这个查询就会出现不可控的情况。 演示示例:

select e.ename, d.dname from emp e, dept d;

9.7 JVM重用

  JVM重用是Hadoop调优参数的内容,其对Hive的性能具有非常大的影响,特别是对于很难避免小文件的场景或task特别多的场景,这类场景大多数执行时间都很短。   Hadoop的默认配置通常是使用派生JVM来执行map和Reduce任务的。这时JVM的启动过程可能会造成相当大的开销,尤其是执行的job包含有成百上千task任务的情况。JVM重用可以使得JVM实例在同一个job中重新使用N次。N的值可以在Hadoop的mapred-site.xml文件中进行配置。通常在10-20之间,具体多少需要根据具体业务场景测试得出。

<property>
  <name>mapreduce.job.jvm.numtasks</name>
  <value>10</value>
  <description>How many tasks to run per jvm. If set to -1, there is
  no limit. 
  </description>
</property>

  这个功能的缺点是,开启JVM重用将一直占用使用到的task插槽,以便进行重用,直到任务完成后才能释放。如果某个“不平衡的”job中有某几个reduce task执行的时间要比其他Reduce task消耗的时间多的多的话,那么保留的插槽就会一直空闲着却无法被其他的job使用,直到所有的task都结束了才会释放。

9.8 推测执行

  在分布式集群环境下,因为程序Bug(包括Hadoop本身的bug),负载不均衡或者资源分布不均等原因,会造成同一个作业的多个任务之间运行速度不一致,有些任务的运行速度可能明显慢于其他任务(比如一个作业的某个任务进度只有50%,而其他所有任务已经运行完毕),则这些任务会拖慢作业的整体执行进度。为了避免这种情况发生,Hadoop采用了推测执行(Speculative Execution)机制,它根据一定的法则推测出“拖后腿”的任务,并为这样的任务启动一个备份任务,让该任务与原始任务同时处理同一份数据,并最终选用最先成功运行完成任务的计算结果作为最终结果。   推测执行算法原理:

  设置开启推测执行参数:Hadoop的mapred-site.xml文件中进行配置:

<property>
    <name>mapreduce.map.speculative</name>
    <value>true</value>
    <description>If true, then multiple instances of some map tasks may be executed in parallel.</description>
</property>

<property>
    <name>mapreduce.reduce.speculative</name>
    <value>true</value>
    <description>If true, then multiple instances of some reduce tasks may be executed in parallel.</description>
</property>

不过hive本身也提供了配置项来控制reduce-side的推测执行:

<property>
    <name>hive.mapred.reduce.tasks.speculative.execution</name>
    <value>true</value>
    <description>Whether speculative execution for reducers should be turned on. </description>
</property>

  关于调优这些推测执行变量,还很难给一个具体的建议。如果用户对于运行时的偏差非常敏感的话,那么可以将这些功能关闭掉。如果用户因为输入数据量很大而需要执行长时间的map或者Reduce task的话,那么启动推测执行造成的浪费是非常巨大大。

9.9 压缩

  详见第8章。

9.10 执行计划(Explain)

1、基本语法

EXPLAIN [EXTENDED | DEPENDENCY | AUTHORIZATION] query

2、案例实操 (1)查看下面这条语句的执行计划

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

(2)查看详细执行计划

hive (default)> explain extended select * from emp;
hive (default)> explain extended select deptno, avg(sal) avg_sal from emp group by deptno;
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-02-28 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 第8章 压缩和存储(Hive高级)
    • 8.1 Hadoop源码编译支持Snappy压缩
      • 8.1.1 资源准备
      • 8.1.2 jar包安装
      • 8.1.3 编译源码
    • 8.2 Hadoop压缩配置
      • 8.2.1 MR支持的压缩编码
      • 8.2.2 压缩参数配置
    • 8.3 开启Map输出阶段压缩
      • 8.4 开启Reduce输出阶段压缩
        • 8.5 文件存储格式
          • 8.5.1 列式存储和行式存储
          • 8.5.2 TextFile格式
          • 8.5.3 Orc格式
          • 8.5.4 Parquet格式
          • 8.5.5 主流文件存储格式对比实验
        • 8.6 存储和压缩结合
          • 8.6.1 修改Hadoop集群具有Snappy压缩方式
          • 8.6.2 测试存储和压缩
      • 第9章 企业级调优(Hive优化)
        • 9.1 Fetch抓取
          • 9.2 本地模式
            • 9.3 表的优化
              • 9.3.1 小表join大表、大表join小表
              • 9.3.2 大表Join大表
              • 9.3.3 MapJoin
              • 9.3.4 group by
              • 9.3.5 Count(Distinct) 去重统计
              • 9.3.6 笛卡尔积
              • 9.3.7 行列过滤
              • 9.3.8 动态分区调整
              • 9.3.9 分桶
              • 9.3.10 分区
            • 9.4 数据倾斜
              • 9.4.1 合理设置 Map 数
              • 9.4.2 小文件进行合并
              • 9.4.3 复杂文件增加 Map 数
              • 9.4.4 合理设置 Reduce 数
            • 9.5 并行执行
              • 9.6 严格模式
                • 9.7 JVM重用
                  • 9.8 推测执行
                    • 9.9 压缩
                      • 9.10 执行计划(Explain)
                      相关产品与服务
                      负载均衡
                      负载均衡(Cloud Load Balancer,CLB)提供安全快捷的流量分发服务,访问流量经由 CLB 可以自动分配到云中的多台后端服务器上,扩展系统的服务能力并消除单点故障。负载均衡支持亿级连接和千万级并发,可轻松应对大流量访问,满足业务需求。
                      领券
                      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档