Hive第四天:Hive函数、Hive压缩配置、Hive文件存储格式、Orc与Parquet、Hive企业级调优、Hive大小表Join、MapJoin、GroupBy、行列过滤去重统计、动态分区调整

接上篇第6章的6.7.4 Hive第三天:Hive的Join语句、Hive数据排序、分区排序、OrderBy全局排序、MR内部排序SortBy、ClusterBy、Hive分桶及抽样查询、行转列与列转行、窗口函数,赋空值

本文目录

6.7.5Rank


第7章函数
7.1系统内置函数
7.2自定义函数
7.3自定义UDF函数


第8章压缩和存储
8.1Hadoop源码编译支持Snappy压缩
8.1.1资源准备
8.1.2jar包安装
8.1.3编译源码
8.2Hadoop压缩配置
8.2.1MR支持的压缩编码
8.2.2压缩参数配置
8.3开启Map输出阶段压缩
8.4开启Reduce输出阶段压缩
8.5文件存储格式
8.5.1列式存储和行式存储
8.5.2 TextFile格式
8.5.3Orc格式
8.5.4Parquet格式
8.5.5主流文件存储格式对比实验
8.6存储和压缩结合
8.6.1修改Hadoop集群具有Snappy压缩方式
8.6.2测试存储和压缩


第9章企业级调优
9.1Fetch抓取
9.2本地模式
9.3表的优化
9.3.1小表、大表Join
9.3.2大表Join大表
9.3.3MapJoin
9.3.4Group By
9.3.5 Count(Distinct)去重统计

9.3.6笛卡尔积
9.3.7行列过滤
9.3.8动态分区调整
9.3.9分桶
9.3.10分区

 

6.7.5 Rank

1.函数说明

RANK() 排序相同时会重复,总数不会变(名次会跳)

DENSE_RANK()排序相同时会重复,总数会减少(名次不跳)

ROW_NUMBER() 会根据顺序计算 (不会重复)

2.数据准备

表6-7 数据准备

name

subject

score

孙悟空

语文

87

孙悟空

数学

95

孙悟空

英语

68

大海

语文

94

大海

数学

56

大海

英语

84

宋宋

语文

64

宋宋

数学

86

宋宋

英语

84

婷婷

语文

65

婷婷

数学

85

婷婷

英语

78

3.需求

计算每门学科成绩排名。

计算每门学科前3名

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

[atguigu@hadoop102 datas]$ vi score.txt

孙悟空    语文 87

孙悟空    数学 95

孙悟空    英语 68

大海 语文 94

大海 数学 56

大海 英语 84

宋宋 语文 64

宋宋 数学 86

宋宋 英语 84

婷婷 语文 65

婷婷 数学 85

婷婷 英语 78

5.创建hive表并导入数据

create table score(

name string,

subject string,

score int)

row format delimited fields terminated by "\t";

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

6.按需求查询数据

没有排序规则测试

hive (default)> select *,rank() over() from score;

row_number排序(按照读姓名的顺序倒序)

 

hive (default)> select *,row_number() over() from score;

 

select name,

subject,

score,

rank() over(partition by subject order by score desc) rp,

dense_rank() over(partition by subject order by score desc) drp,

row_number() over(partition by subject order by score desc) rmp

from score;

 

name    subject score   rp      drp     rmp

孙悟空  数学    95      1       1       1

宋宋    数学    86      2       2       2

婷婷    数学    85      3       3       3

大海    数学    56      4       4       4

宋宋    英语    84      1       1       1

大海    英语    84      1       1       2

婷婷    英语    78      3       2       3

孙悟空  英语    68      4       3       4

大海    语文    94      1       1       1

孙悟空  语文    87      2       2       2

婷婷    语文    65      3       3       3

宋宋    语文    64      4       4       4

第7章 函数

7.1 系统内置函数

1.查看系统自带的函数

hive> show functions;

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

hive> desc function upper;

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

hive> desc function extended upper;

7.2 自定义函数

1)Hive 自带了一些函数,比如:max/min等,但是数量有限,自己可以通过自定义UDF来方便的扩展。

2)当Hive提供的内置函数无法满足你的业务处理需要时,此时就可以考虑使用用户自定义函数(UDF:user-defined function)。

3)根据用户自定义函数类别分为以下三种:

   1UDFUser-Defined-Function

          一进一出

   (2)UDAF(User-Defined Aggregation Function)

          聚集函数,多进一出

          类似于:count/max/min

   (3)UDTF(User-Defined Table-Generating Functions)

          一进多出

          如lateral view explore()

4)官方文档地址

https://cwiki.apache.org/confluence/display/Hive/HivePlugins

5)编程步骤:

   1)继承org.apache.hadoop.hive.ql.UDF

   2)需要实现evaluate函数;evaluate函数支持重载;

   3)在hive的命令行窗口创建函数

          a)添加jar

add jar linux_jar_path

          b)创建function

create [temporary] function [dbname.]function_name AS class_name;

   (4)在hive的命令行窗口删除函数

Drop [temporary] function [if exists] [dbname.]function_name;

 

6)注意事项

   (1)UDF必须要有返回类型,可以返回null,但是返回类型不能为void;

7.3 自定义UDF函数

1.创建一个Maven工程Hive

2.导入依赖

<dependencies>

       <!-- https://mvnrepository.com/artifact/org.apache.hive/hive-exec -->

       <dependency>

           <groupId>org.apache.hive</groupId>

           <artifactId>hive-exec</artifactId>

           <version>1.2.1</version>

       </dependency>

</dependencies>

3.创建一个类

package com.atguigu.hive;

import org.apache.hadoop.hive.ql.exec.UDF;

 

public class Lower extends UDF {

 

   public String evaluate (final String s) {

       

        if (s == null) {

            return null;

        }

       

        return s.toLowerCase();

   }

}

4.打成jar包上传到服务器/opt/module/jars/udf.jar

5.将jar包添加到hive的classpath

hive (default)> add jar /opt/module/datas/udf.jar;

 

6.创建临时函数与开发好的java class关联

hive (default)> hive (default)> create temporary function MyHive as "UDF.myhive.MyHive";

 

7.即可在hql中使用自定义的函数strip 

hive (default)> elect ename,MyHive(ename) lowername from emp;

 

第8章 压缩和存储

8.1 Hadoop源码编译支持Snappy压缩

8.1.1 资源准备

1.CentOS联网

配置CentOS能连接外网。Linux虚拟机ping www.baidu.com 是畅通的

注意:采用root角色编译,减少文件夹权限出现问题

 

2.jar包准备(hadoop源码、JDK8 、maven、protobuf)

1hadoop-2.7.2-src.tar.gz

2jdk-8u144-linux-x64.tar.gz

3snappy-1.1.3.tar.gz

4apache-maven-3.0.5-bin.tar.gz

5protobuf-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]# vi /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 apache-maven-3.0.5]# vi /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支持的压缩编码

表6-8

压缩格式

工具

算法

文件扩展名

是否可切分

DEFAULT

DEFAULT

.deflate

Gzip

gzip

DEFAULT

.gz

bzip2

bzip2

bzip2

.bz2

LZO

lzop

LZO

.lzo

Snappy

Snappy

.snappy

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

表6-9

压缩格式

对应的编码/解码器

DEFLATE

org.apache.hadoop.io.compress.DefaultCodec

gzip

org.apache.hadoop.io.compress.GzipCodec

bzip2

org.apache.hadoop.io.compress.BZip2Codec

LZO

com.hadoop.compression.lzo.LzopCodec

Snappy

org.apache.hadoop.io.compress.SnappyCodec

压缩性能的比较:

表6-10

压缩算法

原始文件大小

压缩文件大小

压缩速度

解压速度

gzip

8.3GB

1.8GB

17.5MB/s

58MB/s

bzip2

8.3GB

1.1GB

2.4MB/s

9.5MB/s

LZO

8.3GB

2.9GB

49.3MB/s

74.6MB/s

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文件中):

表6-11

参数

默认值

阶段

建议

io.compression.codecs  

core-site.xml中配置

org.apache.hadoop.io.compress.DefaultCodec, org.apache.hadoop.io.compress.GzipCodec, org.apache.hadoop.io.compress.BZip2Codec,

org.apache.hadoop.io.compress.Lz4Codec

输入压缩

Hadoop使用文件扩展名判断是否支持某种编解码器

mapreduce.map.output.compress

false

mapper输出

这个参数设为true启用压缩

mapreduce.map.output.compress.codec

org.apache.hadoop.io.compress.DefaultCodec

mapper输出

使用LZOLZ4snappy编解码器在此阶段压缩数据

mapreduce.output.fileoutputformat.compress

false

reducer输出

这个参数设为true启用压缩

mapreduce.output.fileoutputformat.compress.codec

org.apache.hadoop.io.compress. DefaultCodec

reducer输出

使用标准工具或者编解码器,如gzipbzip2

mapreduce.output.fileoutputformat.compress.type

RECORD

reducer输出

SequenceFile输出使用的压缩类型:NONEBLOCK

通过jdbc连接hive

[root@hadoop102 native]# /opt/module/hive/bin/beeline

Beeline version 1.2.1 by Apache Hive

beeline> !connect jdbc:hive2://hadoop102:10000

Connecting to jdbc:hive2://hadoop102:10000

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;

 

jobHistory上查看configuration可以看到所有的配置信息

 

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 mapreduce.output.fileoutputformat.compress=true;

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

hive (default)> set mapreduce.output.fileoutputformat.compress.codec =

 org.apache.hadoop.io.compress.SnappyCodec;

4.设置mapreduce最终数据输出压缩为块压缩

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

5.测试一下输出结果是否是压缩文件

hive (default)> insert overwrite local directory

 '/opt/module/datas/distribute-result' select * from emp distribute by deptno sort by empno desc;

 

8.5 文件存储格式

Hive支持的存储数的格式主要有:TEXTFILE SEQUENCEFILEORCPARQUET

8.5.1 列式存储和行式存储

图6-10 列式存储和行式存储

如图6-10所示左边为逻辑表,右边第一个为行式存储,第二个为列式存储。

1.行存储的特点

查询满足条件的一整行数据的时候,列存储则需要去每个聚集的字段找到对应的每个列的值,行存储只需要找到其中一个值,其余的值都在相邻地方,所以此时行存储查询的速度更快。

2.列存储的特点

因为每个字段的数据聚集存储,在查询只需要少数几个字段的时候,能大大减少读取的数据量;每个字段的数据类型一定是相同的,列式存储可以针对性的设计更好的设计压缩算法。

TEXTFILESEQUENCEFILE的存储格式都是基于行存储的;

ORCPARQUET是基于列式存储的。

8.5.2 TextFile格式

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

8.5.3 Orc格式

Orc (Optimized Row Columnar)Hive 0.11版里引入的新的存储格式。

如图6-11所示可以看到每个Orc文件由1个或多个stripe组成,每个stripe250MB大小,这个Stripe实际相当于RowGroup概念,不过大小由4MB->250MB,这样应该能提升顺序读的吞吐率。每个Stripe里有三部分组成,分别是Index DataRow DataStripe Footer

 

6-11 Orc格式

      1Index Data:一个轻量级的index,默认是每隔1W行做一个索引。这里做的索引应该只是记录某行的各字段在Row Data中的offset

      2Row Data:存的是具体的数据,先取部分行,然后对这些行按列进行存储。对每个列进行了编码,分成多个Stream来存储。

      3Stripe Footer:存的是各个Stream的类型,长度等信息。

每个文件有一个File Footer,这里面存的是每个Stripe的行数,每个Column的数据类型信息等;每个文件的尾部是一个PostScript,这里面记录了整个文件的压缩类型以及FileFooter的长度信息等。在读取文件时,会seek到文件尾部读PostScript,从里面解析到File Footer长度,再读FileFooter,从里面解析到各个Stripe信息,再读各个Stripe,即从后往前读。

8.5.4 Parquet格式

Parquet是面向分析型业务的列式存储格式,由TwitterCloudera合作开发,20155月从Apache的孵化器里毕业成为Apache顶级项目。

Parquet文件是以二进制方式存储的,所以是不可以直接读取的,文件中包括该文件的数据和元数据,因此Parquet格式文件是自解析的。

通常情况下,在存储Parquet数据的时候会按照Block大小设置行组的大小,由于一般情况下每一个Mapper任务处理数据的最小单位是一个Block,这样可以把每一个行组由一个Mapper任务处理,增大任务执行并行度Parquet文件的格式如图6-12所示。

 

6-12  Parquet格式

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

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

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

存储文件的压缩比测试:

  1. 测试数据

1万多条数据

 

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)向表中加载数据

hive (default)> load data local inpath '/opt/module/datas/log.data' into table log_text ;

3)查看表中数据大小

hive (default)> dfs -du -h /user/hive/warehouse/log_text;

 

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

hive (default)> insert into table log_orc select * from log_text ;

3)查看表中数据大小

hive (default)> dfs -du -h /user/hive/warehouse/log_orc/ ;

2.8 M  /user/hive/warehouse/log_orc/000000_0

 

4.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)向表中加载数据

hive (default)> insert into table log_parquet select * from log_text ;

3)查看表中数据大小

hive (default)> dfs -du -h /user/hive/warehouse/log_parquet/ ;

13.1 M  /user/hive/warehouse/log_parquet/000000_0

 

存储文件的压缩比总结:

ORC >  Parquet >  textFile

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

1.TextFile

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

_c0

100000

Time taken: 21.54 seconds, Fetched: 1 row(s)

Time taken: 21.08 seconds, Fetched: 1 row(s)

Time taken: 19.298 seconds, Fetched: 1 row(s)

 

2.ORC

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

_c0

100000

Time taken: 20.867 seconds, Fetched: 1 row(s)

Time taken: 22.667 seconds, Fetched: 1 row(s)

Time taken: 18.36 seconds, Fetched: 1 row(s)

3.Parquet

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

_c0

100000

Time taken: 22.922 seconds, Fetched: 1 row(s)

Time taken: 21.074 seconds, Fetched: 1 row(s)

Time taken: 18.384 seconds, Fetched: 1 row(s)

存储文件的查询速度总结:查询速度相近。

8.6 存储和压缩结合

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

1.查看hadoop checknative命令使用

[atguigu@hadoop104 hadoop-2.7.2]$ hadoop  checknative [-a|-h]  check native hadoop and compression libraries availability

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

  [atguigu@hadoop104 hadoop-2.7.2]$ hadoop checknative

17/12/24 20:32:52 WARN bzip2.Bzip2Factory: Failed to load/initialize native-bzip2 library system-native, will use pure-Java version

17/12/24 20:32:52 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

3.将编译好的支持Snappy压缩的hadoop-2.7.2.tar.gz包导入到hadoop102的/opt/software中

4.解压hadoop-2.7.2.tar.gz到当前路径

[atguigu@hadoop102 software]$ tar -zxvf hadoop-2.7.2.tar.gz

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

[atguigu@hadoop102 native]$ pwd

/opt/software/hadoop-2.7.2/lib/native

[atguigu@hadoop102 native]$ ll

-rw-r--r--. 1 atguigu atguigu  472950 9月   1 10:19 libsnappy.a

-rwxr-xr-x. 1 atguigu atguigu     955 9月   1 10:19 libsnappy.la

lrwxrwxrwx. 1 atguigu atguigu      18 12月 24 20:39 libsnappy.so -> libsnappy.so.1.3.0

lrwxrwxrwx. 1 atguigu atguigu      18 12月 24 20:39 libsnappy.so.1 -> libsnappy.so.1.3.0

-rwxr-xr-x. 1 atguigu atguigu  228177 9月   1 10:19 libsnappy.so.1.3.0

6.拷贝/opt/software/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 hadoop-2.7.2]$ hadoop checknative

17/12/24 20:45:02 WARN bzip2.Bzip2Factory: Failed to load/initialize native-bzip2 library system-native, will use pure-Java version

17/12/24 20:45:02 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

9.重新启动hadoop集群和hive

8.6.2 测试存储和压缩

官网:https://cwiki.apache.org/confluence/display/Hive/LanguageManual+ORC

ORC存储方式的压缩:

6-12

Key

Default

Notes

orc.compress

ZLIB

high level compression (one of NONE, ZLIB, SNAPPY)

orc.compress.size

262,144

number of bytes in each compression chunk

orc.stripe.size

67,108,864

number of bytes in each stripe

orc.row.index.stride

10,000

number of rows between index entries (must be >= 1000)

orc.create.index

true

whether to create row indexes

orc.bloom.filter.columns

""

comma separated list of column names for which bloom filter should be created

orc.bloom.filter.fpp

0.05

false positive probability for bloom filter (must >0.0 and <1.0)

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)插入数据

hive (default)> insert into table log_orc_none select * from log_text ;

       3)查看插入后数据

hive (default)> dfs -du -h /user/hive/warehouse/log_orc_none/ ;

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)插入数据

hive (default)> insert into table log_orc_snappy select * from log_text ;

       3)查看插入后数据

hive (default)> dfs -du -h /user/hive/warehouse/log_orc_snappy/ ;

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压缩。比snappy压缩的小。

4.存储方式和压缩总结

在实际的项目开发当中,hive表的数据存储格式一般选择:orcparquet。压缩方式一般选择snappylzo

9 企业级调优

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;

       2)把hive.fetch.task.conversion设置成more,然后执行查询语句,如下查询方式都不会执行mapreduce程序。

hive (default)> set hive.fetch.task.conversion=more;

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)开启本地模式,并执行查询语句

hive (default)> set hive.exec.mode.local.auto=true; 

hive (default)> select * from emp cluster by deptno;

Time taken: 1.328 seconds, Fetched: 14 row(s)

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

hive (default)> set hive.exec.mode.local.auto=false; 

hive (default)> select * from emp cluster by deptno;

Time taken: 20.09 seconds, Fetched: 14 row(s)

9.3 表的优化

9.3.1 小表、大表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.分别向大表和小表中导入数据

hive (default)> load data local inpath '/opt/module/datas/bigtable' into table bigtable;

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

 

Time taken: 39.229 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;

 

Time taken: 44.966 seconds

经过反复测试发现大表Join小表效率略低于小表Join大表,实际上二者效率相差不大,因为hive底层做了优化。

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>

启动历史服务器

sbin/mr-jobhistory-daemon.sh start historyserver

查看jobhistory

http://192.168.1.102: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';

  1. 分别加载原始数据和空id数据到对应表中

 

hive (default)> load data local inpath '/opt/module/datas/ori' into table ori;

hive (default)> load data local inpath '/opt/module/datas/nullid' into table nullidtable;

4)测试不过滤空id

hive (default)> insert overwrite table jointable

select n.* from nullidtable n left join ori o on n.id = o.id;

 

Time taken: 33.895 seconds

Time taken: 37.284 seconds

5)测试过滤空id

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

 

Time taken: 29.792 seconds

Time taken: 28.876 seconds

2.空key转换

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

案例实操:

不随机分布空null值:

1)设置5reduce个数

set mapreduce.job.reduces = 5;

2JOIN两张表

insert overwrite table jointable

select n.* from nullidtable n left join ori b on n.id = b.id;

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

 

6-13 key转换

随机分布空null

1)设置5reduce个数

set mapreduce.job.reduces = 5;

2JOIN两张表

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;

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

6-14 随机分布空值

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工作机制,如图6-15所示

1)TaskA,它是一个Local Task(在客户端本地执行的Task),负责扫描小表b的数据,将其转换成一个HashTable的数据结构,并写入本地的文件中,之后将该文件加载到DistributeCache中。
2)Task B,该任务是一个没有Reduce的MR,启动MapTasks扫描大表a,在Map阶段,根据a的每一条记录去和DistributeCache中b表对应的HashTable关联,并直接输出结果。
3)由于MapJoin没有Reduce,所以由Map直接输出结果文件,有多少个Map Task,就有多少个结果文件。

图6-15  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;

Time taken: 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;

Time taken: 24.315 seconds

9.3.4 Group By

默认情况下,Map阶段同一Key数据分发给一个reduce,当一个key数据过大时就倾斜了。

    并不是所有的聚合操作都需要在Reduce端完成,很多聚合操作都可以先在Map端进行部分聚合,最后在Reduce端得出最终结果。

1.开启Map端聚合参数设置

       (1)是否在Map端进行聚合,默认为True

hive.map.aggr=true

(2)在Map端进行聚合操作的条目数目(默认100000)

hive.groupby.mapaggr.checkinterval = 100000

 

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

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. 创建一张大表

hive (default)> 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.加载数据

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

 bigtable;

3.设置5个reduce个数

set mapreduce.job.reduces = 5;

4.执行去重id查询

先不去重查看执行时间及查询行数(999998 rows)

 

hive (default)> select count(distinct id) from bigtable;

Stage-Stage-1: Map: 1  Reduce: 1   Cumulative CPU: 7.12 sec   HDFS Read: 120741990 HDFS Write: 7 SUCCESS

Total MapReduce CPU Time Spent: 7 seconds 120 msec

OK

c0

100001

Time taken: 23.607 seconds, Fetched: 1 row(s)

 

5.采用GROUP by去重id

hive (default)> select count(id) from (select id from bigtable group by id) a;

 

Stage-Stage-1: Map: 1  Reduce: 5   Cumulative CPU: 17.53 sec   HDFS Read: 120752703 HDFS Write: 580 SUCCESS

Stage-Stage-2: Map: 1  Reduce: 1   Cumulative CPU: 4.29 sec   HDFS Read: 9409 HDFS Write: 7 SUCCESS

Total MapReduce CPU Time Spent: 21 seconds 820 msec

OK

_c0

100001

Time taken: 50.795 seconds, Fetched: 1 row(s)

 

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

9.3.6 笛卡尔积

尽量避免笛卡尔积,join的时候不加on条件,或者无效的on条件,Hive只能使用1个reducer来完成笛卡尔积。

9.3.7 行列过滤

谓词下推:先执行where语句

列处理:在SELECT中,只拿需要的列,如果有,尽量使用分区过滤,少用SELECT *。

行处理:在分区剪裁中,当使用外关联时,如果将副表的过滤条件写在Where后面,那么就会先全表关联,之后再过滤,比如:

案例实操:

1.测试先关联两张表,再用where条件过滤

hive (default)> select o.id from bigtable b join ori o on o.id = b.id

where o.id <= 10;

 

Time taken: 24.55 seconds, Fetched: 100 row(s)

2.通过子查询后,再关联表

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

 

Time taken: 19.163 seconds, Fetched: 100 row(s)

9.3.8 动态分区调整

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

1.开启动态分区参数设置

(1)开启动态分区功能(默认true,开启)

hive.exec.dynamic.partition=true

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

hive.exec.dynamic.partition.mode=nonstrict

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

hive.exec.max.dynamic.partitions=1000

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

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

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

hive.exec.max.created.files=100000

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

hive.error.on.empty.partition=false

2.案例实操

需求:将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)加载数据到分区表中

hive (default)> load data local inpath '/opt/module/datas/ds1' into table ori_partitioned partition(p_time='20190828');

 

hive (default)> load data local inpath '/opt/module/datas/ds2' into table ori_partitioned partition(p_time='20190829');

 

(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;

 

hive (default)> 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)查看目标分区表的分区情况

hive (default)> show partitions ori_partitioned_target;

 

9.3.9 分桶

详见6.6章。

Hive第三天:Hive的Join语句、Hive数据排序、分区排序、OrderBy全局排序、MR内部排序SortBy、ClusterBy、Hive分桶及抽样查询、行转列与列转行、窗口函数,赋空值

9.3.10 分区

详见4.6章。

Hive第二天:Hive的创建表、管理表与外部表、分区表、修改表、删除表、Hive的DML数据操作、Hive数据导入导出、inport与export、Hive查询、基本查询、where过滤、分组查询

Hive第五天做谷粒影音项目

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值