【无标题】

第1章 Hive基本概念

1.1 什么是Hive

1.2 Hive的优缺点

1.2.1 优点

1.2.2 缺点

1.3 Hive架构原理

1.4 Hive和数据库比较

1.4.1 查询语言

1.4.2 数据更新

1.4.3 执行延迟

1.4.4 数据规模

第2章 Hive安装

2.1 Hive安装地址

2.2 MySql安装

2.2.1 安装包准备

2.2.2 安装MySql

2.2.3 配置MySql

2.3 Hive安装部署

2.4 Hive元数据配置到MySql

2.3.1 拷贝驱动

2.3.2 配置Metastore到MySql

2.5 启动Hive

2.5.1 初始化元数据库

2.5.2 启动metastore和hiveserver 2

2.5.3 HiveJDBC访问

2.6 Hive常用交互命令

2.7 Hive其他命令操作

2.8 Hive常见属性配置

2.8.1 Hive运行日志信息配置

2.8.2 参数配置方式

第3章 Hive数据类型

3.1 基本数据类型

3.2 集合数据类型

3.3 类型转化

第4章 DDL数据定义

4.1 创建数据库

4.2 查询数据库

4.2.1 显示数据库

4.2.2 查看数据库详情

4. 2.3 切换当前数据库

4.3 修改数据库

4.4 删除数据库

4.5 创建表

4.5.1 管理表

4.5.2 外部表

4.5.3 管理表与外部表的互相转换

4.6 修改表

4.6.1 重命名表

4.6.2 增加、修改和删除表分区

4.6.3 增加/修改/替换列信息

4.7 删除表

第5章 DML数据操作

5.1 数据导入

5.1.1 向表中装载数据(Load)

5.1.2 通过查询语句向表中插入数据(Insert)

5.1.3 查询语句中创建表并加载数据(As Select)

5.1.4 创建表时通过Location指定加载数据路径

5.1.5 Import数据到指定Hive表中

5.2 数据导出

5.2.1 Insert导出

5.2.2 Hadoop命令导出到本地

5.2.3 Hive Shell 命令导出

5.2.4 Export导出到HDFS上

5.2.5 Sqoop导出

5.2.6 清除表中数据(Truncate)

第6章 查询

6.1 基本查询(Select…From)

6.1.1 全表和特定列查询

6.1.2 列别名

6.1.3 算术运算符

6.1.4 常用函数

6.1.5 Limit语句

6.1.6 Where语句

6.1.7 比较运算符(Between/In/ Is Null)

6.1.8 Like和RLike

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

6.2 分组

6.2.1 Group By语句

6.2.2 Having语句

6.3 Join语句

6.3.1 等值Join

6.3.2 表的别名

6.3.3 内连接

6.3.4 左外连接

6.3.5 右外连接

6.3.6 满外连接

6.3.7 多表连接

6.3.8 笛卡尔积

6.4 排序

6.4.1 全局排序(Order By)

6.4.2 按照别名排序

6.4.3 多个列排序

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

6.4.5 分区排序(Distribute By)

6.4.6 Cluster By

6.5 抽样查询

第7章

函数

7.1 系统 内置 函数

7.2 常用内置函数

7.2.1 空字段赋值

7.2.2 CASE WHEN

7.2.3 行转列

7.2.5 窗口函数(开窗函数)

7.2.6 Rank

7.2.7 日期相关函数

7.3 自定义函数

7.4 自定义UDF函数

第8章 压缩和存储

8.1 Hadoop压缩配置

8.1.1 MR支持的压缩编码

8.1.2 压缩参数配置

8.2 开启Map输出阶段压缩 (MR引擎)

8.3 开启Reduce输出阶段压缩

8.4 文件存储格式

8.4.1 列式存储和行式存储

8.4.2 TextFile格式

8.4.3 Orc格式

8.4.4 Parquet格式

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

8.5 存储和压缩结合

8.5.1 测试 存储和压缩

第9章 Hive实战

9.1 需求描述

9.2 数据结构

9.3 准备工作

9.4 业务分析

9.4.1 统计视频观看数Top10

9.4.2 统计视频类别热度Top10

9.4.3 统计出视频观看数最高的20个视频的所属类别以及类别包含Top20视频的个数

9.4.4 统计视频观看数Top50所关联视频的所属类别排序

9.4.5 统计每个类别中的视频热度Top10,以Music为例

9.4.6 统计每个类别视频观看数Top10

第10 章 分区表和分桶表

10.1 分区表

10.1.1 分区表基本操作

10.1.2 分区表注意事项

10.1.3 动态分区调整

10.2 分桶表

第11 章 企业级调优

11.1 Fetch抓取

11.2 表的优化

11.2.1 小表、大表Join

11.2.2 大表Join大表

11.2.3 MapJoin (MR引擎)

11.2.4 Group By

11.2.5 笛卡尔积

11.2.6 行列过滤

11.2.7 分桶

11.2.8 分区

11.3 合理设置Map 及Reduce 数 (MR引擎)

11.3.1 复杂文件增加Map数

11.3.2 小文件进行合并

11.3.3 合理设置Reduce数

11.4 并行执行

11.5 严格模式

11.6 JVM重用

11.7 压缩

11.8 执行计划(Explain)

附录: 常见错误 及解决 方案

第1章 Hive基本概念

1.1 什么是Hive

Hive:由Facebook开源用于解决海量结构化日志的数据统计工具。

Hive是基于Hadoop的一个数据仓库工具,可以将结构化的数据文件映射为一张表,并提供类SQL查询功能。

本质是:将HQL转化成MapReduce程序

(1)Hive处理的数据存储在HDFS

(2)Hive分析数据底层的实现是MapReduce

(3)执行程序运行在Yarn上

1.2 Hive的优缺点

1.2.1 优点

(1)操作接口采用类SQL语法,提供快速开发的能力(简单、容易上手)。

(2)避免了去写MapReduce,减少开发人员的学习成本。

(3)Hive的执行延迟比较高,因此Hive常用于数据分析,对实时性要求不高的场合。

(4)Hive优势在于处理大数据,对于处理小数据没有优势,因为Hive的执行延迟比较高。

(5)Hive支持用户自定义函数,用户可以根据自己的需求来实现自己的函数。

1.2.2 缺点

1)Hive的HQL表达能力有限

(1)迭代式算法无法表达

(2)数据挖掘方面不擅长,由于MapReduce数据处理流程的限制,效率更高的算法却无法实现。

2)Hive的效率比较低

(1)Hive自动生成的MapReduce作业,通常情况下不够智能化

(2)Hive调优比较困难,粒度较粗

1.3 Hive架构原理

1)用户接口:Client

CLI(command-line interface)、JDBC/ODBC(jdbc访问hive)、WEBUI(浏览器访问hive)

2)元数据:Metastore

元数据包括:表名、表所属的数据库(默认是default)、表的拥有者、列/分区字段、表的类型(是否是外部表)、表的数据所在目录等;

默认存储在自带的derby数据库中,推荐使用MySQL存储Metastore

3)Hadoop

使用HDFS进行存储,使用MapReduce进行计算。

4)驱动器:Driver

(1)解析器(SQL Parser):将SQL字符串转换成抽象语法树AST,这一步一般都用第三方工具库完成,比如antlr;对AST进行语法分析,比如表是否存在、字段是否存在、SQL语义是否有误。

(2)编译器(Physical Plan):将AST编译生成逻辑执行计划。

(3)优化器(Query Optimizer):对逻辑执行计划进行优化。

(4)执行器(Execution):把逻辑执行计划转换成可以运行的物理计划。对于Hive来说,就是MR/Spark。

Hive通过给用户提供的一系列交互接口,接收到用户的指令(SQL),使用自己的Driver,结合元数据(MetaStore),将这些指令翻译成MapReduce,提交到Hadoop中执行,最后,将执行返回的结果输出到用户交互接口。

1.4 Hive和数据库比较

由于 Hive 采用了类似SQL 的查询语言 HQL(Hive Query Language),因此很容易将 Hive 理解为数据库。其实从结构上来看,Hive 和数据库除了拥有类似的查询语言,再无类似之处。本文将从多个方面来阐述 Hive 和数据库的差异。数据库可以用在 Online 的应用中,但是Hive 是为数据仓库而设计的,清楚这一点,有助于从应用角度理解 Hive 的特性。

1.4.1 查询语言

由于SQL被广泛的应用在数据仓库中,因此,专门针对Hive的特性设计了类SQL的查询语言HQL。熟悉SQL开发的开发者可以很方便的使用Hive进行开发。

1.4.2 数据更新

由于Hive是针对数据仓库应用设计的,而数据仓库的内容是读多写少的。因此,Hive中不建议对数据的改写,所有的数据都是在加载的时候确定好的。而数据库中的数据通常是需要经常进行修改的,因此可以使用 INSERT INTO … VALUES 添加数据,使用 UPDATE … SET修改数据。

1.4.3 执行延迟

Hive 在查询数据的时候,由于没有索引,需要扫描整个表,因此延迟较高。另外一个导致 Hive 执行延迟高的因素是 MapReduce框架。由于MapReduce 本身具有较高的延迟,因此在利用MapReduce 执行Hive查询时,也会有较高的延迟。相对的,数据库的执行延迟较低。当然,这个低是有条件的,即数据规模较小,当数据规模大到超过数据库的处理能力的时候,Hive的并行计算显然能体现出优势。

1.4.4 数据规模

由于Hive建立在集群上并可以利用MapReduce进行并行计算,因此可以支持很大规模的数据;对应的,数据库可以支持的数据规模较小。

第2章 Hive安装

2.1 Hive安装地址

1)Hive 官网地址

http://hive.apache.org/

2)文档查看地址

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

3)下载地址

http://archive.apache.org/dist/hive/

4)github 地址

https://github.com/apache/hive

2.2 MySql安装

2.2.1 安装包准备

1 )卸载自带的Mysql-libs(如果之前安装过mysql,要全都卸载掉)

[atguigu@hadoop102 software]$ rpm -qa | grep mariadb

[atguigu@hadoop102 software]$ sudo rpm -e --nodeps mariadb-libs

1

2

2 )将安装包和JDBC驱动上传到/opt/software,共计6个

01_mysql-community-common-5.7.29-1.el7.x86_64.rpm

02_mysql-community-libs-5.7.29-1.el7.x86_64.rpm

03_mysql-community-libs-compat-5.7.29-1.el7.x86_64.rpm

04_mysql-community-client-5.7.29-1.el7.x86_64.rpm

05_mysql-community-server-5.7.29-1.el7.x86_64.rpm

mysql-connector-java-5.1.48.jar

1

2

3

4

5

6

7

8

9

10

11

2.2.2 安装MySql

1) 安装 mysql 依赖

[atguigu@hadoop102 software]$ sudo rpm -ivh 01_mysql-community-common-5.7.29-1.el7.x86_64.rpm

[atguigu@hadoop102 software]$ sudo rpm -ivh 02_mysql-community-libs-5.7.29-1.el7.x86_64.rpm

[atguigu@hadoop102 software]$ sudo rpm -ivh 03_mysql-community-libs-compat-5.7.29-1.el7.x86_64.rpm

1

2

3

4

5

2) 安装 mysql-client

[atguigu@hadoop102 software]$ sudo rpm -ivh 04_mysql-community-client-5.7.29-1.el7.x86_64.rpm

1

3) 安装 mysql-server

[atguigu@hadoop102 software]$ sudo rpm -ivh 05_mysql-community-server-5.7.29-1.el7.x86_64.rpm

1

4) 初始化 mysql

[atguigu@hadoop102 software]$ sudo mysqld --initialize --user=mysql

1

5) 查看 mysql 密码

[atguigu@hadoop102 software]$ sudo cat /var/log/mysqld.log

1

6)启动 mysql

[atguigu@hadoop102 software]$ sudo systemctl start mysqld

1

2.2.3 配置MySql

配置只要是root用户+密码,在任何主机上都能登录MySQL数据库。

1)用刚刚查到的密码进入mysql(如果报错,给密码加单引号)

[atguigu@hadoop102 software]$ mysql -uroot -p’password’

1

2)设置复杂密码(由于mysql密码策略,此密码必须足够复杂)

mysql> set password=password('你的密码');

1

3)更改mysql密码策略(选做)

mysql> set global validate_password_length=4;

mysql> set global validate_password_policy=0;

1

2

3

4) 设置简单好记的密码

mysql> set password=password("000000");

1

5) 进入 msyql 库

mysql> use mysql

1

6) 查询 user 表

mysql> select user, host from user;

1

7) 修改 user 表 , 把 Host 表内容修改为 %,目的是为了远程登录MySQL

mysql> update user set host="%" where user="root";

1

8)刷新

mysql> flush privileges;

1

9)退出

mysql> quit;

1

2.3 Hive安装部署

1) 把apache-hive-3.1.2-bin.tar.gz上传到linux的/opt/software目录下

2) 解压apache-hive-3.1.2-bin.tar.gz到/opt/module/目录下面

[atguigu@hadoop102 software]$ tar -zxvf /opt/software/apache-hive-3.1.2-bin.tar.gz -C /opt/module/

1

3) 修改 apache-hive-3.1.2-bin.tar.gz 的名称为 hive

[atguigu@hadoop102 software]$ mv /opt/module/apache-hive-3.1.2-bin/ /opt/module/hive

1

4) 修改 / etc/profile.d/my_env.sh , 添加环境变量

[atguigu@hadoop102 software]$ sudo vim /etc/profile.d/my_env.sh

1

5) 添加内容

#HIVE_HOME

export HIVE_HOME=/opt/module/hive

export PATH=$PATH:$HIVE_HOME/bin

1

2

3

4

5

重启Xshell对话框使环境变量生效

6)解决日志Jar包冲突

[atguigu@hadoop102 software]$ mv $HIVE_HOME/lib/log4j-slf4j-impl-2.10.0.jar $HIVE_HOME/lib/log4j-slf4j-impl-2.10.0.bak

1

2.4 Hive元数据配置到MySql

2.3.1 拷贝驱动

将MySQL的JDBC驱动拷贝到Hive的lib目录下

[atguigu@hadoop102 software]$ cp /opt/software/mysql-connector-java-5.1.48.jar $HIVE_HOME/lib

1

2.3.2 配置Metastore到MySql

在$HIVE_HOME/conf目录下新建hive-site.xml文件

[atguigu@hadoop102 software]$ vim $HIVE_HOME/conf/hive-site.xml

1

添加如下内容

<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>

<configuration>

<!-- jdbc连接的URL -->

<property>

<name>javax.jdo.option.ConnectionURL</name>

<value>jdbc:mysql://hadoop102:3306/metastore?useSSL=false</value>

</property>

<!-- jdbc连接的Driver-->

<property>

<name>javax.jdo.option.ConnectionDriverName</name>

<value>com.mysql.jdbc.Driver</value>

</property>

<!-- jdbc连接的用户名-->

<property>

<name>javax.jdo.option.ConnectionUserName</name>

<value>root</value>

</property>

<!-- jdbc连接的密码-->

<property>

<name>javax.jdo.option.ConnectionPassword</name>

<value>root</value>

</property>

<!-- Hive默认在HDFS的工作目录 -->

<property>

<name>hive.metastore.warehouse.dir</name>

<value>/user/hive/warehouse</value>

</property>

<!-- Hive元数据存储版本的验证 -->

<property>

<name>hive.metastore.schema.verification</name>

<value>false</value>

</property>

<!-- 指定存储元数据要连接的地址 -->

<property>

<name>hive.metastore.uris</name>

<value>thrift://hadoop102:9083</value>

</property>

<!-- 指定hiveserver2连接的端口号 -->

<property>

<name>hive.server2.thrift.port</name>

<value>10000</value>

</property>

<!-- 指定hiveserver2连接的host -->

<property>

<name>hive.server2.thrift.bind.host</name>

<value>hadoop102</value>

</property>

<!-- 元数据存储授权 -->

<property>

<name>hive.metastore.event.db.notification.api.auth</name>

<value>false</value>

</property>

<!-- 打印表头 -->

<property>

<name>hive.cli.print.header</name>

<value>true</value>

</property>

<!-- 打印当前所在的库 -->

<property>

<name>hive.cli.print.current.db</name>

<value>true</value>

</property>

</configuration>

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

2.5 启动Hive

2.5.1 初始化元数据库

1)登录MySQL

[atguigu@hadoop102 software]$ mysql -uroot -proot

1

2)新建Hive元数据库

mysql> create database metastore;

mysql> quit;

1

2

3

3)初始化Hive元数据库

[atguigu@hadoop102 software]$ schematool -initSchema -dbType mysql -verbose

1

如果出现以下异常:

查看hadoop安装目录下share/hadoop/common/lib内guava.jar版本查看hive安装目录下lib内guava.jar的版本

删除版本低的,并拷贝高版本的

2.5.2 启动metastore和hiveserver 2

1)Hive 2.x 以上版本 , 要先启动这两个服务 , 否则会报错 :

FAILED: HiveException java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient

1

①启动metastore

[atguigu@hadoop202 hive]$ hive --service metastore

2020-04-24 16:58:08: Starting Hive Metastore Server

1

2

3

注意: 启动后窗口不能再操作,需打开一个新的shell窗口做别的操作

②启动 hiveserver2

[atguigu@hadoop202 hive]$ hive --service hiveserver2

which: no hbase in (/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/opt/module/jdk1.8.0_212/bin:/opt/module/hadoop-3.1.3/bin:/opt/module/hadoop-3.1.3/sbin:/opt/module/hive/bin:/home/atguigu/.local/bin:/home/atguigu/bin)

2020-04-24 17:00:19: Starting HiveServer2

1

2

3

4

5

注意: 启动后窗口不能再操作,需打开一个新的shell窗口做别的操作

2) 编写hive服务启动脚本

①前台启动的方式导致需要打开多个shell窗口,可以使用如下方式后台方式启动

nohup: 放在命令开头,表示不挂起,也就是关闭终端进程也继续保持运行状态

2>&1 : 表示将错误重定向到标准输出上

&: 放在命令结尾,表示后台运行

一般会组合使用: nohup [xxx命令操作]> file 2>&1 & , 表示将xxx命令运行的

结果输出到file中,并保持命令启动的进程在后台运行。

如上命令不要求掌握

[atguigu@hadoop202 hive]$ nohup hive --service metastore 2>&1 &

[atguigu@hadoop202 hive]$ nohup hive --service hiveserver2 2>&1 &

1

2

3

②为了方便使用,可以直接编写脚本来管理服务的启动和关闭

[atguigu@hadoop102 software]$ vim $HIVE_HOME/bin/hiveservices.sh

1

内容如下:(此脚本的编写不要求掌握,直接拿来使用即可)

#!/bin/bash

HIVE_LOG_DIR=$HIVE_HOME/logs

mkdir -p $HIVE_LOG_DIR

#检查进程是否运行正常,参数1为进程名,参数2为进程端口

function check_process()

{

pid=$(ps -ef 2>/dev/null | grep -v grep | grep -i $1 | awk '{print $2}')

ppid=$(netstat -nltp 2>/dev/null | grep $2 | awk '{print $7}' | cut -d '/' -f 1)

echo $pid

[[ "$pid" =~ "$ppid" ]] && [ "$ppid" ] && return 0 || return 1

}

function hive_start()

{

metapid=$(check_process HiveMetastore 9083)

cmd="nohup hive --service metastore >$HIVE_LOG_DIR/metastore.log 2>&1 &"

cmd=$cmd" sleep 4; hdfs dfsadmin -safemode wait >/dev/null 2>&1"

[ -z "$metapid" ] && eval $cmd || echo "Metastroe服务已启动"

server2pid=$(check_process HiveServer2 10000)

cmd="nohup hive --service hiveserver2 >$HIVE_LOG_DIR/hiveServer2.log 2>&1 &"

[ -z "$server2pid" ] && eval $cmd || echo "HiveServer2服务已启动"

}

function hive_stop()

{

metapid=$(check_process HiveMetastore 9083)

[ "$metapid" ] && kill $metapid || echo "Metastore服务未启动"

server2pid=$(check_process HiveServer2 10000)

[ "$server2pid" ] && kill $server2pid || echo "HiveServer2服务未启动"

}

case $1 in

"start")

hive_start

;;

"stop")

hive_stop

;;

"restart")

hive_stop

sleep 2

hive_start

;;

"status")

check_process HiveMetastore 9083 >/dev/null && echo "Metastore服务运行正常" || echo "Metastore服务运行异常"

check_process HiveServer2 10000 >/dev/null && echo "HiveServer2服务运行正常" || echo "HiveServer2服务运行异常"

;;

*)

echo Invalid Args!

echo 'Usage: '$(basename $0)' start|stop|restart|status'

;;

esac

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

3)添加执行权限

[atguigu@hadoop102 software]$ chmod +x $HIVE_HOME/bin/hiveservices.sh

1

4)启动Hive后台服务(hiveserver 2 能正常启动的前提是先启动hadoop集群)

[atguigu@hadoop102 software]$ hiveservices.sh start

1

2.5.3 HiveJDBC访问

1)启动beeline客户端(如果提示拒绝连接等一会儿再连即可)

[atguigu@hadoop102 software]$ beeline -u jdbc:hive2://hadoop102:10000 -n atguigu

1

2)看到如下界面

Connecting to jdbc:hive2://hadoop102:10000

Connected to: Apache Hive (version 3.1.2)

Driver: Hive JDBC (version 3.1.2)

Transaction isolation: TRANSACTION_REPEATABLE_READ

Beeline version 3.1.2 by Apache Hive

0: jdbc:hive2://hadoop102:10000>

退出使用!quit

1

2

3

4

5

6

7

8

9

10

11

12

13

2.6 Hive常用交互命令

[atguigu@hadoop102 hive]$ bin/hive -help

usage: hive

-d,--define <key=value> Variable subsitution to apply to hive

commands. e.g. -d A=B or --define A=B

--database <databasename> Specify the database to use

-e <quoted-query-string> SQL from command line

-f <filename> SQL from files

-H,--help Print help information

--hiveconf <property=value> Use value for given property

--hivevar <key=value> Variable subsitution to apply to hive

commands. e.g. --hivevar A=B

-i <filename> Initialization SQL file

-S,--silent Silent mode in interactive shell

-v,--verbose Verbose mode (echo executed SQL to the console)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

1)“-e”不进入hive的交互窗口执行sql语句

[atguigu@hadoop102 hive]$ bin/hive -e "select id from student;"

1

2)“-f”执行脚本中sql语句

(1)在/opt/module/data目录下创建hivef.sql文件

[atguigu@hadoop102 datas]$ touch hivef.sql

1

(2)文件中写入正确的sql语句

select *from student;

1

(3)执行文件中的sql语句

[atguigu@hadoop102 hive]$ bin/hive -f /opt/module/data/hivef.sql

1

(4)执行文件中的sql语句并将结果写入文件中

[atguigu@hadoop102 hive]$ bin/hive -f /opt/module/data/hivef.sql > /opt/module/data/hive_result.txt

1

2.7 Hive其他命令操作

1)退出hive窗口:

hive(default)>exit;

hive(default)>quit;

1

2

3

在新版的hive中没区别了,在以前的版本是有的:

exit:先隐性提交数据,再退出;

quit:不提交数据,退出;

2)在hive cli命令窗口中如何查看hdfs文件系统

hive(default)>dfs -ls /;

1

3)查看在hive中输入的所有历史命令

(1)进入到当前用户的根目录/root或/home/atguigu

(2)查看. hivehistory文件

[atguigu@hadoop102 ~]$ cat .hivehistory

1

2.8 Hive常见属性配置

2.8.1 Hive运行日志信息配置

1)Hive的log默认存放在/tmp/atguigu/hive.log目录下(当前用户名下)

2)修改hive的log存放日志到/opt/module/hive/logs

(1)修改/opt/module/hive/conf/hive-log4j2.properties.template文件名称为

hive-log4j2.properties

[atguigu@hadoop102 conf]$ pwd

/opt/module/hive/conf

[atguigu@hadoop102 conf]$ mv hive-log4j2.properties.template hive-log4j2.properties

1

2

3

(2)在hive-log4j2.properties文件中修改log存放位置

hive.log.dir=/opt/module/hive/logs

1

2.8.2 参数配置方式

1)查看当前所有的配置信息

hive>set;

1

2)参数的配置三种方式

(1)配置文件方式

默认配置文件:hive-default.xml

用户自定义配置文件:hive-site.xml

注意:用户自定义配置会覆盖默认配置。另外,Hive也会读入Hadoop的配置,因为Hive是作为Hadoop的客户端启动的,Hive的配置会覆盖Hadoop的配置。配置文件的设定对本机启动的所有Hive进程都有效。

(2)命令行参数方式

启动Hive时,可以在命令行添加-hiveconf param=value来设定参数。

例如:

[atguigu@hadoop103 hive]$ bin/hive -hiveconf mapred.reduce.tasks=10;

1

注意:仅对本次hive启动有效

查看参数设置:

hive (default)> set mapred.reduce.tasks;

1

(3)参数声明方式

可以在HQL中使用SET关键字设定参数

例如:

hive (default)> set mapred.reduce.tasks=100;

1

注意:仅对本次hive启动有效。

查看参数设置

hive (default)> set mapred.reduce.tasks;

1

上述三种设定方式的优先级依次递增。即配置文件<命令行参数<参数声明。注意某些系统级的参数,例如log4j相关的设定,必须用前两种方式设定,因为那些参数的读取在会话建立以前已经完成了。

第3章 Hive数据类型

3.1 基本数据类型

Hive数据类型Java数据类型长度例子

TINYINTbyte1byte有符号整数20

SMALINTshort2byte有符号整数20

INTint4byte有符号整数20

BIGINTlong8byte有符号整数20

BOOLEANboolean布尔类型,true或者falseTRUE FALSE

FLOATfloat单精度浮点数3.14159

DOUBLEdouble双精度浮点数3.14159

STRINGstring字符系列。可以指定字符集。可以使用单引号或者双引号。‘now is the time’ “for all good men”

TIMESTAMP时间类型

BINARY字节数组

对于Hive的String类型相当于数据库的varchar类型,该类型是一个可变的字符串,不过它不能声明其中最多能存储多少个字符,理论上它可以存储2GB的字符数。

3.2 集合数据类型

数据类型描述语法示例

STRUCT和c语言中的struct类似,都可以通过“点”符号访问元素内容。例如,如果某个列的数据类型是STRUCT{first STRING, last STRING},那么第1个元素可以通过字段.first来引用。struct()例如struct<street:string, city:string>

MAPMAP是一组键-值对元组集合,使用数组表示法可以访问数据。例如,如果某个列的数据类型是MAP,其中键->值对是’first’->’John’和’last’->’Doe’,那么可以通过字段名[‘last’]获取最后一个元素map()例如map<string, int>

ARRAY数组是一组具有相同类型和名称的变量的集合。这些变量称为数组的元素,每个数组元素都有一个编号,编号从零开始。例如,数组值为[‘John’, ‘Doe’],那么第2个元素可以通过数组名[1]进行引用。Array()例如array

Hive有三种复杂数据类型ARRAY、MAP 和 STRUCT。ARRAY和MAP与Java中的Array和Map类似,而STRUCT与C语言中的Struct类似,它封装了一个命名字段集合,复杂数据类型允许任意层次的嵌套。

1) 案例实操

(1)假设某表有如下一行,我们用JSON格式来表示其数据结构。在Hive下访问的格式为

{

"name": "songsong",

"friends": ["bingbing" , "lili"] , //列表Array,

"children": { //键值Map,

"xiao song": 18 ,

"xiaoxiao song": 19

}

"address": { //结构Struct,

"street": "hui long guan" ,

"city": "beijing"

}

}

1

2

3

4

5

6

7

8

9

10

11

12

(2)基于上述数据结构,我们在Hive里创建对应的表,并导入数据。

创建本地测试文件test.txt

songsong,bingbing_lili,xiao song:18_xiaoxiao song:19,hui long guan_beijing

yangyang,caicai_susu,xiao yang:18_xiaoxiao yang:19,chao yang_beijing

1

2

3

注意:MAP,STRUCT和ARRAY里的元素间关系都可以用同一个字符表示,这里用“_”。

(3)Hive上创建测试表test

字段解释:

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

1

2

3

4

5

6

7

8

9

10

row format delimited fields terminated by ‘,’ – 列分隔符

collection items terminated by ‘_’ --MAP STRUCT 和 ARRAY 的分隔符(数据分割符号)

map keys terminated by ‘:’ – MAP中的key与value的分隔符

lines terminated by ‘\n’; – 行分隔符

(4)导入文本数据到测试表

load data local inpath ‘/opt/module/data/test.txt’ into table test;

(5)访问三种集合列里的数据,以下分别是ARRAY,MAP,STRUCT的访问方式

hive (default)> select friends[1],children['xiao song'],address.city from test

where name="songsong";

OK

_c0 _c1 city

lili 18 beijing

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

1

2

3

4

5

6

3.3 类型转化

Hive的原子数据类型是可以进行隐式转换的,类似于Java的类型转换,例如某表达式使用INT类型,TINYINT会自动转换为INT类型,但是Hive不会进行反向转化,例如,某表达式使用TINYINT类型,INT不会自动转换为TINYINT类型,它会返回错误,除非使用CAST操作。

1)隐式类型转换规则如下

(1)任何整数类型都可以隐式地转换为一个范围更广的类型,如TINYINT可以转换成INT,INT可以转换成BIGINT。

(2)所有整数类型、FLOAT和STRING类型都可以隐式地转换成DOUBLE。

(3)TINYINT、SMALLINT、INT都可以转换为FLOAT。

(4)BOOLEAN类型不可以转换为任何其它的类型。

2)可以使用CAST操作显示进行数据类型转换

例如CAST(‘1’ AS INT)将把字符串’1’ 转换成整数1;如果强制类型转换失败,如执行CAST(‘X’ AS INT),表达式返回空值 NULL。

0: jdbc:hive2://hadoop102:10000> select '1'+2, cast('1'as int) + 2;

+------+------+--+

| _c0 | _c1 |

+------+------+--+

| 3.0 | 3 |

+------+------+--+

1

2

3

4

5

6

第4章 DDL数据定义

4.1 创建数据库

CREATE DATABASE [IF NOT EXISTS] database_name

[COMMENT database_comment]

[LOCATION hdfs_path]

[WITH DBPROPERTIES (property_name=property_value, ...)];

1

2

3

4

5

6

7

1)创建一个数据库,数据库在HDFS上的默认存储路径是/user/hive/warehouse/*.db。

hive (default)> create database db_hive;

1

2)避免要创建的数据库已经存在错误,增加if not exists判断。(标准写法)

hive (default)> create database db_hive;

FAILED: Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.DDLTask. Database db_hive already exists

hive (default)> create database if not exists db_hive;

1

2

3

4

5

3)创建一个数据库,指定数据库在HDFS上存放的位置

hive (default)> create database db_hive2 location '/db_hive2.db';

1

4.2 查询数据库

4.2.1 显示数据库

1 )显示数据库

hive> show databases;

1

2)过滤显示查询的数据库

hive> show databases like 'db_hive*';

OK

db_hive

db_hive_1

1

2

3

4

5

6

7

4.2.2 查看数据库详情

1)显示数据库信息

hive> desc database db_hive;

OK

db_hivehdfs://hadoop102:9000/user/hive/warehouse/db_hive.dbatguiguUSER

1

2

3

4

5

2)显示数据库详细信息,extended

hive> desc database extended db_hive;

OK

db_hivehdfs://hadoop102:9000/user/hive/warehouse/db_hive.dbatguiguUSER

1

2

3

4

5

4. 2.3 切换当前数据库

hive (default)> use db_hive;

1

4.3 修改数据库

用户可以使用ALTER DATABASE命令为某个数据库的DBPROPERTIES设置键-值对属性值,来描述这个数据库的属性信息。数据库的其他元数据信息都是不可更改的,包括数据库名和数据库所在的目录位置。

hive (default)> alter database db_hive set dbproperties('createtime'='20170830');

1

在hive中查看修改结果

hive> desc database extended db_hive;

db_name comment location owner_name owner_type parameters

db_hive hdfs://hadoop102:8020/user/hive/warehouse/db_hive.db atguigu USER {createtime=20170830}

1

2

3

4

5

4.4 删除数据库

1 )删除空数据库

hive>drop database db_hive2;

1

2) 如果删除的数据库不存在 , 最好采用 if exists 判断数据库是否存在

hive> drop database db_hive;

FAILED: SemanticException [Error 10072]: Database does not exist: db_hive

hive> drop database if exists db_hive2;

1

2

3

4

5

3)如果数据库不为空,可以采用cascade命令,强制删除

hive> drop database db_hive;

FAILED: Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.DDLTask. InvalidOperationException(message:Database db_hive is not empty. One or more tables exist.)

hive> drop database db_hive cascade;

1

2

3

4

5

4.5 创建表

1)建表语法

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]

[TBLPROPERTIES (property_name=property_value, ...)]

[AS select_statement]

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

2)字段解释说明

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

(2)EXTERNAL关键字可以让用户创建一个外部表,在建表的同时可以指定一个指向实际数据的路径(LOCATION),在删除表的时候,内部表的元数据和数据会被一起删除,而外部表只删除元数据,不删除数据。

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

(4)PARTITIONED BY创建分区表

(5)CLUSTERED BY创建分桶表

(6)SORTED BY不常用,对桶中的一个或多个列另外排序

(7)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的简称, hive使用Serde进行行对象的序列与反序列化。

(8)STORED AS指定存储文件类型

常用的存储文件类型:SEQUENCEFILE(二进制序列文件)、TEXTFILE(文本)、RCFILE(列式存储格式文件)

如果文件数据是纯文本,可以使用STORED AS TEXTFILE。如果数据需要压缩,使用 STORED AS SEQUENCEFILE。

(9)LOCATION :指定表在HDFS上的存储位置。

(10)AS:后跟查询语句,根据查询结果创建表。

(11)LIKE允许用户复制现有的表结构,但是不复制数据。

4.5.1 管理表

1)理论

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

2)案例实操

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

1

2

3

4

5

6

(2)根据查询结果创建表(查询的结果会添加到新创建的表中)

create table if not exists student3 as select id, name from student;

1

(3)根据已经存在的表结构创建表

create table if not exists student4 like student;

1

(4)查询表的类型

hive (default)> desc formatted student2;

Table Type: MANAGED_TABLE

1

2

3

4.5.2 外部表

1)理论

因为表是外部表,所以Hive并非认为其完全拥有这份数据。删除该表并不会删除掉这份数据,不过描述表的元数据信息会被删除掉。

2)管理表和外部表的使用场景

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

3)案例实操

分别创建部门和员工外部表,并向表中导入数据。

(1)上传数据到HDFS

hive (default)> dfs -mkdir /student;

hive (default)> dfs -put /opt/module/data/student.txt /student;

1

2

3

(2)建表语句,创建外部表

hive (default)> create external table stu_external(

id int,

name string)

row format delimited fields terminated by '\t'

location '/student';

1

2

3

4

5

6

7

8

9

(3)查看创建的表

hive (default)> select * from stu_external;

OK

stu_external.id stu_external.name

1001 lisi

1002 wangwu

1003 zhaoliu

1

2

3

4

5

6

(4)查看表格式化数据

h

ive (default)> desc formatted dept;

Table Type: EXTERNAL_TABLE

1

2

3

(5)删除外部表

hive (default)> drop table stu_external;

1

2

3

外部表删除后,hdfs中的数据还在,但是metadata中stu_external的元数据已被删除

4.5.3 管理表与外部表的互相转换

(1)查询表的类型

hive (default)> desc formatted student2;

Table Type: MANAGED_TABLE

1

2

3

(2)修改内部表student2为外部表

alter table student2 set tblproperties('EXTERNAL'='TRUE');

1

2

3

(3)查询表的类型

hive (default)> desc formatted student2;

Table Type: EXTERNAL_TABLE

1

2

3

(4)修改外部表student2为内部表

alter table student2 set tblproperties('EXTERNAL'='FALSE');

1

2

3

(5)查询表的类型

hive (default)> desc formatted student2;

Table Type: MANAGED_TABLE

1

2

3

注意:(‘EXTERNAL’=‘TRUE’)和(‘EXTERNAL’=‘FALSE’)为固定写法,区分大小写!

4.6 修改表

4.6.1 重命名表

1 )语法

ALTER TABLE table_name RENAME TO new_table_name

1

2

3

2)实操案例

hive (default)> alter table dept_partition2 rename to dept_partition3;

###

1

2

3

4.6.2 增加、修改和删除表分区

详见4.6.1分区表基本操作。

4.6.3 增加/修改/替换列信息

1)语法

(1)更新列

ALTER TABLE table_name CHANGE [COLUMN] col_old_name col_new_name column_type [COMMENT col_comment] [FIRST|AFTER column_name]

1

(2)增加和替换列

ALTER TABLE table_name ADD|REPLACE COLUMNS (col_name data_type [COMMENT col_comment], ...)

1

2

3

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

2)实操案例

(1)查询表结构

hive> desc dept_partition;

1

2

3

(2)添加列

hive (default)> alter table dept_partition add columns(deptdesc string);

1

2

3

(3)查询表结构

hive> desc dept_partition;

1

2

3

(4)更新列

hive (default)> alter table dept_partition change column deptdesc desc int;

1

2

3

(5)查询表结构

hive> desc dept_partition;

1

2

3

(6)替换列

hive (default)> alter table dept_partition replace columns(deptno string, dname

string, loc string);

1

2

3

(7)查询表结构

hive> desc dept_partition;

##

1

2

3

4.7 删除表

hive (default)> drop table dept_partition;

#

1

2

3

第5章 DML数据操作

5.1 数据导入

5.1.1 向表中装载数据(Load)

1)语法

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

1

2

3

(1)load data:表示加载数据

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

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

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

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

(6)student:表示具体的表

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

2)实操案例

(0)创建一张表

hive (default)> create table student(id string, name string) row format delimited fields terminated by '\t';

1

2

3

(1)加载本地文件到hive

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

1

2

3

(2)加载HDFS文件到hive中

上传文件到HDFS

hive (default)> dfs -put /opt/module/data/student.txt /user/atguigu/hive;

1

2

3

加载HDFS上数据

hive (default)> load data inpath '/user/atguigu/hive/student.txt' into table default.student;

1

2

3

(3)加载数据覆盖表中已有的数据

上传文件到HDFS

hive (default)> dfs -put /opt/module/data/student.txt /user/atguigu/hive;

1

2

3

加载数据覆盖表中已有的数据

hive (default)> load data inpath '/user/atguigu/hive/student.txt' overwrite into table default.student;

###

1

2

3

5.1.2 通过查询语句向表中插入数据(Insert)

1)创建一张分区表

hive (default)> create table student_par(id int, name string) partitioned by (month string) row format delimited fields terminated by '\t';

1

2

3

2)基本插入数据

hive (default)> insert into table student_par partition(month='201709') values(1,'wangwu'),(2,'zhaoliu');

1

2

3

3)基本模式插入(根据单张表查询结果)

hive (default)> insert overwrite table student partition(month='201708')

select id, name from student where month='201709';

1

2

insert into:以追加数据的方式插入到表或分区,原有数据不会删除

insert overwrite:会覆盖表或分区中已存在的数据

注意:insert不支持插入部分字段

4)多表(多分区)插入模式(根据多张表查询结果)

hive (default)> from student

insert overwrite table student partition(month='201707')

select id, name where month='201709'

insert overwrite table student partition(month='201706')

select id, name where month='201709';

1

2

3

4

5

5.1.3 查询语句中创建表并加载数据(As Select)

详见4.5.1章创建表。

根据查询结果创建表(查询的结果会添加到新创建的表中)

create table if not exists student3

as select id, name from student;

1

2

5.1.4 创建表时通过Location指定加载数据路径

1 )上传数据到hdfs上

hive (default)> dfs -mkdir /student;

hive (default)> dfs -put /opt/module/data/student.txt /student;

1

2

2)创建表,并指定在hdfs上的位置

hive (default)> create external table if not exists student5(

id int, name string

)

row format delimited fields terminated by '\t'

location '/student;

1

2

3

4

5

3) 查询数据

hive (default)> select * from student5;

1

5.1.5 Import数据到指定Hive表中

注意:先用export导出后,再将数据导入。

hive (default)> import table student2 partition(month='201709') from

'/user/hive/warehouse/export/student';

1

2

5.2 数据导出

5.2.1 Insert导出

1)将查询的结果导出到本地

hive (default)> insert overwrite local directory '/opt/module/data/export/student'

select * from student;

1

2

2) 将查询的结果格式化导出到本地

hive(default)>insert overwrite local directory '/opt/module/data/export/student1'

ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t' select * from student;

1

2

3)将查询的结果导出到HDFS上(没有local)

hive (default)> insert overwrite directory '/user/atguigu/student2'

ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t'

select * from student;

1

2

3

5.2.2 Hadoop命令导出到本地

hive (default)> dfs -get /user/hive/warehouse/student/month=201709/000000_0

/opt/module/data/export/student3.txt;

1

2

5.2.3 Hive Shell 命令导出

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

[atguigu@hadoop102 hive]$ bin/hive -e 'select * from default.student;' >

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

1

2

5.2.4 Export导出到HDFS上

(defahiveult)> export table default.student to

'/user/hive/warehouse/export/student';

1

2

export和import主要用于两个Hadoop平台集群之间Hive表迁移。

5.2.5 Sqoop导出

后续课程专门讲。

5.2.6 清除表中数据(Truncate)

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

hive (default)> truncate table student;

#

1

2

3

第6章 查询

https://cwiki.apache.org/confluence/display/Hive/LanguageManual+Select

查询语句语法:

SELECT [ALL | DISTINCT] select_expr, select_expr, ...

FROM table_reference

[WHERE where_condition]

[GROUP BY col_list]

[ORDER BY col_list]

[CLUSTER BY col_list

| [DISTRIBUTE BY col_list] [SORT BY col_list]

]

[LIMIT number]

1

2

3

4

5

6

7

8

9

6.1 基本查询(Select…From)

6.1.1 全表和特定列查询

0)数据准备

(1)创建部门表

create table if not exists dept(

deptno int,

dname string,

loc int

)

row format delimited fields terminated by '\t';

1

2

3

4

5

6

(2)创建员工表

create table if not exists emp(

empno int,

ename string,

job string,

mgr int,

hiredate string,

sal double,

comm double,

deptno int)

row format delimited fields terminated by '\t';

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

(3)导入数据

load data local inpath '/opt/module/data/dept.txt' into table

dept;

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

1

2

3

4

5

1)全表查询

hive (default)> select * from emp;

1

2) 选择特定列查询

hive (default)> select empno, ename from emp;

1

注意:

(1)SQL 语言大小写不敏感。

(2)SQL 可以写在一行或者多行

(3)关键字不能被缩写也不能分行

(4)各子句一般要分行写。

(5)使用缩进提高语句的可读性。

6.1.2 列别名

1)重命名一个列

2)便于计算

3)紧跟列名,也可以在列名和别名之间加入关键字‘AS’

4)案例实操

查询名称和部门

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

1

6.1.3 算术运算符

运算符描述

A+BA和B 相加

A-BA减去B

A*BA和B 相乘

A/BA除以B

A%BA对B取余

A&BA和B按位取与

A|BA和B按位取或

A^BA和B按位取异或

~AA按位取反

案例实操:查询出所有员工的薪水后加1显示。

hive (default)> select sal +1 from emp;

1

6.1.4 常用函数

1 )求总行数(count)

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

1

2)求工资的最大值(max)

hive (default)> select max(sal) max_sal from emp;

1

3)求工资的最小值(min)

hive (default)> select min(sal) min_sal from emp;

1

4)求工资的总和(sum)

hive (default)> select sum(sal) sum_sal from emp;

1

5)求工资的平均值(avg)

hive (default)> select avg(sal) avg_sal from emp;

1

6.1.5 Limit语句

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

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

1

6.1.6 Where语句

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

2)WHERE子句紧随FROM子句

3)案例实操

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

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

1

注意:where子句中不能使用字段别名。

6.1.7 比较运算符(Between/In/ Is Null)

1) 下面表中描述了谓词操作符 , 这些操作符同样可以用于 JOIN…ON 和 HAVING 语句中。

操作符支持的数据类型描述

A=B基本数据类型如果A等于B则返回TRUE,反之返回FALSE

A<=>B基本数据类型如果A和B都为NULL,则返回TRUE,如果一边为NULL,返回False

A<>B, A!=B基本数据类型A或者B为NULL则返回NULL;如果A不等于B,则返回TRUE,反之返回FALSE

A<B基本数据类型A或者B为NULL,则返回NULL;如果A小于B,则返回TRUE,反之返回FALSE

A<=B基本数据类型A或者B为NULL,则返回NULL;如果A小于等于B,则返回TRUE,反之返回FALSE

A>B基本数据类型A或者B为NULL,则返回NULL;如果A大于B,则返回TRUE,反之返回FALSE

A>=B基本数据类型A或者B为NULL,则返回NULL;如果A大于等于B,则返回TRUE,反之返回FALSE

A [NOT] BETWEEN B AND C基本数据类型如果A,B或者C任一为NULL,则结果为NULL。如果A的值大于等于B而且小于或等于C,则结果为TRUE,反之为FALSE。如果使用NOT关键字则可达到相反的效果。

A IS NULL所有数据类型如果A等于NULL,则返回TRUE,反之返回FALSE

A IS NOT NULL所有数据类型如果A不等于NULL,则返回TRUE,反之返回FALSE

IN(数值1, 数值2)所有数据类型使用 IN运算显示列表中的值

A [NOT] LIKE BSTRING 类型B是一个SQL下的简单正则表达式,也叫通配符模式,如果A与其匹配的话,则返回TRUE;反之返回FALSE。B的表达式说明如下:‘x%’表示A必须以字母‘x’开头,‘%x’表示A必须以字母’x’结尾,而‘%x%’表示A包含有字母’x’,可以位于开头,结尾或者字符串中间。如果使用NOT关键字则可达到相反的效果。

A RLIKE B, A REGEXP BSTRING 类型B是基于java的正则表达式,如果A与其匹配,则返回TRUE;反之返回FALSE。匹配使用的是JDK中的正则表达式接口实现的,因为正则也依据其中的规则。例如,正则表达式必须和整个字符串A相匹配,而不是只需与其字符串匹配。

2)案例实操

(1)查询出薪水等于5000的所有员工

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

1

(2)查询工资在500到1000的员工信息

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

1

(3)查询comm为空的所有员工信息

hive (default)> select * from emp where comm is null;

1

(4)查询工资是1500或5000的员工信息

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

1

6.1.8 Like和RLike

1)使用LIKE运算选择类似的值

2)选择条件可以包含字符或数字:

% 代表零个或多个字符(任意个字符)。

_ 代表一个字符。

3)RLIKE子句

RLIKE子句是Hive中这个功能的一个扩展,其可以通过Java的正则表达式这个更强大的语言来指定匹配条件。

4)案例实操

(1)查找以2开头薪水的员工信息

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

1

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

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

1

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

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

1

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

操作符含义

AND逻辑并

OR逻辑或

NOT逻辑否

1) 案例实操

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

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

1

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

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

1

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

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

1

6.2 分组

6.2.1 Group By语句

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

1) 案例实操:

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

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

1

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

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

t.deptno, t.job;

1

2

6.2.2 Having语句

1)having 与 where 不同点

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

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

2 )案例实操

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

求每个部门的平均工资

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

1

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

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

avg_sal > 2000;

1

2

3

6.3 Join语句

6.3.1 等值Join

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

1) 案例实操

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

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

1

6.3.2 表的别名

1)好处

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

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

2)案例实操

合并员工表和部门表

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

= d.deptno;

1

2

3

6.3.3 内连接

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

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

= d.deptno;

1

2

3

6.3.4 左外连接

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

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

1

6.3.5 右外连接

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

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

1

6.3.6 满外连接

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

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

= d.deptno;

1

2

6.3.7 多表连接

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

数据准备

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-gWJuZzN3-1633767577098)(file:///C:\Users\wanka\AppData\Local\Temp\ksohtml\wps80A7.tmp.png)]

1 )创建位置表

create table if not exists location(

loc int,

loc_name string

)

row format delimited fields terminated by '\t';

1

2

3

4

5

2)导入数据

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

1

3)多表连接查询

hive (default)>SELECT e.ename, d.dname, l.loc_name

FROM emp e

JOIN dept d

ON d.deptno = e.deptno

JOIN location l

ON d.loc = l.loc;

1

2

3

4

5

6

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

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

优化:当对3个或者更多表进行join连接时,如果每个on子句都使用相同的连接键的话,那么只会产生一个MapReduce job。

6.3.8 笛卡尔积

1)笛卡尔集会在下面条件下产生

(1)省略连接条件

(2)连接条件无效

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

2 )案例实操

hive (default)> select empno, dname from emp, dept;

1

6.4 排序

6.4.1 全局排序(Order By)

Order By:全局排序,只有一个Reducer

1)使用 ORDER BY 子句排序

ASC(ascend): 升序(默认)

DESC(descend): 降序

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

3)案例实操

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

hive (default)> select * from emp order by sal;

1

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

hive (default)> select * from emp order by sal desc;

1

6.4.2 按照别名排序

按照员工薪水的2倍排序

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

1

6.4.3 多个列排序

按照部门和工资升序排序

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

1

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

Sort By:对于大规模的数据集order by的效率非常低。在很多情况下,并不需要全局排序,此时可以使用 sort by 。

Sort by为每个reducer产生一个排序文件。每个Reducer内部进行排序,对全局结果集来说不是排序。

1 )设置 reduce 个数

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

1

2 )查看设置 reduce 个数

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

1

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

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

1

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

hive (default)> insert overwrite local directory '/opt/module/data/sortby-result'

select * from emp sort by deptno desc;

1

2

3

6.4.5 分区排序(Distribute By)

Distribute By: 在有些情况下,我们需要控制某个特定行应该到哪个reducer,通常是为了进行后续的聚集操作。 distribute by 子句可以做这件事。 distribute by 类似MR中partition(自定义分区),进行分区,结合sort by使用。

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

1) 案例实操:

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

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

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

1

2

3

注意:

Ø distribute by的分区规则是根据分区字段的hash码与reduce的个数进行模除后,余数相同的分到一个区。

Ø Hive要求DISTRIBUTE BY语句要写在SORT BY语句之前。

6.4.6 Cluster By

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

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

(1)以下两种写法等价

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

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

1

2

3

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

6.5 抽样查询

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

查询表stu_buck中的数据。

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

1

注: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

第7章

函数

7.1 系统 内置 函数

1 )查看系统自带的函数

hive> show functions;

1

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

hive> desc function upper;

1

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

hive> desc function extended upper;

1

7.2 常用内置函数

7.2.1 空字段赋值

1)函数说明

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

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

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

hive (default)> select comm,nvl(comm, -1) from emp;

OK

comm _c1

NULL -1.0

300.0 300.0

500.0 500.0

NULL -1.0

1400.0 1400.0

NULL -1.0

NULL -1.0

NULL -1.0

NULL -1.0

0.0 0.0

NULL -1.0

NULL -1.0

NULL -1.0

NULL -1.0

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

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

hive (default)> select comm, nvl(comm,mgr) from emp;

OK

comm _c1

NULL 7902.0

300.0 300.0

500.0 500.0

NULL 7839.0

1400.0 1400.0

NULL 7839.0

NULL 7839.0

NULL 7566.0

NULL NULL

0.0 0.0

NULL 7788.0

NULL 7698.0

NULL 7566.0

NULL 7782.0

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

7.2.2 CASE WHEN

1)数据准备

namedept_idsex

悟空A男

大海A男

宋宋B男

凤姐A女

婷姐B女

婷婷B女

2)需求

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

A 2 1

B 1 2

1

2

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

[atguigu@hadoop102 datas]$ vi emp_sex.txt

悟空A男

大海A男

宋宋B男

凤姐A女

婷姐B女

婷婷B女

1

2

3

4

5

6

7

4)创建hive表并导入数据

create table emp_sex(

name string,

dept_id string,

sex string)

row format delimited fields terminated by "\t";

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

1

2

3

4

5

6

5)按需求查询数据

select

dept_id,

sum(case sex when '男' then 1 else 0 end) male_count,

sum(case sex when '女' then 1 else 0 end) female_count

from

emp_sex

group by

dept_id;

1

2

3

4

5

6

7

8

7.2.3 行转列

1 )相关函数说明

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

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

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

2 )数据准备

nameconstellationblood_type

孙悟空白羊座A

大海射手座A

宋宋白羊座B

猪八戒白羊座A

凤姐射手座A

苍老师白羊座B

3 )需求

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

射手座,A 大海|凤姐

白羊座,A 孙悟空|猪八戒

白羊座,B 宋宋|苍老师

1

2

3

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

[atguigu@hadoop102 datas]$ vi constellation.txt

孙悟空白羊座A

大海 射手座A

宋宋 白羊座B

猪八戒 白羊座A

凤姐 射手座A

1

2

3

4

5

6

5 )创建hive表并导入数据

create table person_info(

name string,

constellation string,

blood_type string)

row format delimited fields terminated by "\t";

load data local inpath "/opt/module/data/constellation.txt" into table person_info;

1

2

3

4

5

6

6 )按需求查询数据

select

t1.base,

concat_ws('|', collect_set(t1.name)) name

from

(select

name,

concat(constellation, ",", blood_type) base

from

person_info) t1

group by

t1.base;

1

2

3

4

5

6

7

8

9

10

11

7.2.5 窗口函数(开窗函数)

1 )相关函数说明

OVER():指定分析函数工作的数据窗口大小,这个数据窗口大小可能会随着行的变而变化。

CURRENT ROW:当前行

n PRECEDING:往前n行数据

n FOLLOWING:往后n行数据

UNBOUNDED:起点,UNBOUNDED PRECEDING 表示从前面的起点, UNBOUNDED FOLLOWING表示到后面的终点

LAG(col,n,default_val):往前第n行数据

LEAD(col,n, default_val):往后第n行数据

NTILE(n):把有序窗口的行分发到指定数据的组中,各个组有编号,编号从1开始,对于每一行,NTILE返回此行所属的组的编号。注意:n必须为int类型。

2 )数据准备: name , orderdate , cost

jack,2017-01-01,10

tony,2017-01-02,15

jack,2017-02-03,23

tony,2017-01-04,29

jack,2017-01-05,46

jack,2017-04-06,42

tony,2017-01-07,50

jack,2017-01-08,55

mart,2017-04-08,62

mart,2017-04-09,68

neil,2017-05-10,12

mart,2017-04-11,75

neil,2017-06-12,80

mart,2017-04-13,94

1

2

3

4

5

6

7

8

9

10

11

12

13

14

3 )需求

(1)查询在2017年4月份购买过的顾客及总人数

(2)查询顾客的购买明细及月购买总额

(3)上述的场景, 将每个顾客的cost按照日期进行累加

(4)查询每个顾客上次的购买时间

(5)查询前20%时间的订单信息

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

[atguigu@hadoop102 datas]$ vi business.txt

1

5 )创建hive表并导入数据

create table business(

name string,

orderdate string,

cost int

) ROW FORMAT DELIMITED FIELDS TERMINATED BY ',';

load data local inpath "/opt/module/data/business.txt" into table business;

1

2

3

4

5

6

6 )按需求查询数据

(1)查询在2017年4月份购买过的顾客及总人数

select name,count(*) over ()

from business

where substring(orderdate,1,7) = '2017-04'

group by name;

1

2

3

4

(2)查询顾客的购买明细及月购买总额

select name,orderdate,cost,sum(cost) over(partition by month(orderdate)) from

business;

1

2

(3)上述的场景, 将每个顾客的cost按照日期进行累加

select name,orderdate,cost,

sum(cost) over() as sample1,--所有行相加

sum(cost) over(partition by name) as sample2,--按name分组,组内数据相加

sum(cost) over(partition by name order by orderdate) as sample3,--按name分组,组内数据累加

sum(cost) over(partition by name order by orderdate rows between UNBOUNDED PRECEDING and current row ) as sample4 ,--和sample3一样,由起点到当前行的聚合

sum(cost) over(partition by name order by orderdate rows between 1 PRECEDING and current row) as sample5, --当前行和前面一行做聚合

sum(cost) over(partition by name order by orderdate rows between 1 PRECEDING AND 1 FOLLOWING ) as sample6,--当前行和前边一行及后面一行

sum(cost) over(partition by name order by orderdate rows between current row and UNBOUNDED FOLLOWING ) as sample7 --当前行及后面所有行

from business;

1

2

3

4

5

6

7

8

9

rows必须跟在Order by 子句之后,对排序的结果进行限制,使用固定的行数来限制分区中的数据行数量

(4)查看顾客上次的购买时间

select name,orderdate,cost,

lag(orderdate,1,'1900-01-01') over(partition by name order by orderdate ) as time1, lag(orderdate,2) over (partition by name order by orderdate) as time2

from business;

1

2

3

(5)查询前20%时间的订单信息

select * from (

select name,orderdate,cost, ntile(5) over(order by orderdate) sorted

from business

) t

where sorted = 1;

1

2

3

4

5

7.2.6 Rank

1 )函数说明

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

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

ROW_NUMBER() 会根据顺序计算

2 )数据准备

namesubjectscore

孙悟空语文87

孙悟空数学95

孙悟空英语68

大海语文94

大海数学56

大海英语84

宋宋语文64

宋宋数学86

宋宋英语84

婷婷语文65

婷婷数学85

婷婷英语78

3 )需求

计算每门学科成绩排名。

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

[atguigu@hadoop102 datas]$ vi score.txt

1

5 )创建hive表并导入数据

create table score(

name string,

subject string,

score int)

row format delimited fields terminated by "\t";

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

1

2

3

4

5

6

6 )按需求查询数据

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

扩展:求出每门学科前三名的学生?

7.2.7 日期相关函数

(1)current_date返回当前日期

select current_date();

1

(2)date_add, date_sub 日期的加减

--今天开始90天以后的日期

select date_add(current_date(), 90);

--今天开始90天以前的日期

select date_sub(current_date(), 90);

1

2

3

4

(3)两个日期之间的日期差

--今天和1990年6月4日的天数差

SELECT datediff(CURRENT_DATE(), "1990-06-04");

1

2

3

7.3 自定义函数

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

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

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

(1)UDF(User-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.exec.UDF

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

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

添加jar

add jar linux_jar_path

1

创建function

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

1

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

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

1

6)注意事项:UDF必须要有返回类型,可以返回null,但是返回类型不能为void;

7.4 自定义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>3.1.2</version>

</dependency>

</dependencies>

1

2

3

4

5

6

7

8

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

}

}

1

2

3

4

5

6

7

8

9

10

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

5)将 jar 包添加到 hive 的 classpath

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

1

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

hive (default)> create temporary function mylower as "com.atguigu.hive.Lower";

1

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

hive (default)> select ename, mylower(ename) lowername from emp;

1

第8章 压缩和存储

8.1 Hadoop压缩配置

8.1.1 MR支持的压缩编码

压缩格式工具算法文件扩展名是否可切分

DEFLATE无DEFLATE.deflate否

GzipgzipDEFLATE.gz否

bzip2bzip2bzip2.bz2是

LZOlzopLZO.lzo是

Snappy无Snappy.snappy否

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

压缩格式对应的编码/解码器

DEFLATEorg.apache.hadoop.io.compress.DefaultCodec

gziporg.apache.hadoop.io.compress.GzipCodec

bzip2org.apache.hadoop.io.compress.BZip2Codec

LZOcom.hadoop.compression.lzo.LzopCodec

Snappyorg.apache.hadoop.io.compress.SnappyCodec

压缩性能的比较:

压缩算法原始文件大小压缩文件大小压缩速度解压速度

gzip8.3GB1.8GB17.5MB/s58MB/s

bzip28.3GB1.1GB2.4MB/s9.5MB/s

LZO8.3GB2.9GB49.3MB/s74.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.1.2 压缩参数配置

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

参数默认值阶段建议

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.compressfalsemapper输出这个参数设为true启用压缩

mapreduce.map.output.compress.codecorg.apache.hadoop.io.compress.DefaultCodecmapper输出使用LZO、LZ4或snappy编解码器在此阶段压缩数据

mapreduce.output.fileoutputformat.compressfalsereducer输出这个参数设为true启用压缩

mapreduce.output.fileoutputformat.compress.codecorg.apache.hadoop.io.compress. DefaultCodecreducer输出使用标准工具或者编解码器,如gzip和bzip2

mapreduce.output.fileoutputformat.compress.typeRECORDreducer输出SequenceFile输出使用的压缩类型:NONE和BLOCK

8.2 开启Map输出阶段压缩 (MR引擎)

开启map输出阶段压缩可以减少job中map和Reduce task间数据传输量。具体配置如下:

1) 案例实操:

(1)开启hive中间传输数据压缩功能

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

1

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

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

1

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

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

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

1

2

(4)执行查询语句

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

1

8.3 开启Reduce输出阶段压缩

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

1) 案例实操:

(1)开启hive最终输出数据压缩功能

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

1

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

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

1

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

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

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

1

2

3

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

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

1

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

hive (default)> insert overwrite local directory

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

1

2

3

8.4 文件存储格式

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

8.4.1 列式存储和行式存储

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

1) 行存储的特点

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

2) 列存储的特点

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

TEXTFILE和SEQUENCEFILE的存储格式都是基于行存储的;

ORC和PARQUET是基于列式存储的。

8.4.2 TextFile格式

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

8.4.3 Orc格式

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

如下图所示可以看到每个Orc文件由1个或多个stripe组成,每个stripe一般为HDFS的块大小,每一个stripe包含多条记录,这些记录按照列进行独立存储,对应到Parquet中的row group的概念。每个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.4.4 Parquet格式

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

(1)行组(Row Group):每一个行组包含一定的行数,在一个HDFS文件中至少存储一个行组,类似于orc的stripe的概念。

(2)列块(Column Chunk):在一个行组中每一列保存在一个列块中,行组中的所有列连续的存储在这个行组文件中。一个列块中的值都是相同类型的,不同的列块可能使用不同的算法进行压缩。

(3)页(Page):每一个列块划分为多个页,一个页是最小的编码的单位,在同一个列块的不同页可能使用不同的编码方式。

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

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

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

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

存储文件的压缩比测试:

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;

1

2

3

4

5

6

7

8

9

10

11

(2)向表中加载数据

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

1

(3)查看表中数据大小

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

18.1 M /user/hive/warehouse/log_text/log.data

1

2

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

tblproperties("orc.compress"="NONE");

1

2

3

4

5

6

7

8

9

10

11

12

(2)向表中加载数据

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

1

(3)查看表中数据大小

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

1

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 ;

1

2

3

4

5

6

7

8

9

10

11

(2)向表中加载数据

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

1

(3)查看表中数据大小

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

1

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)

1

2

3

4

5

6

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

1

2

3

4

5

6

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

1

2

3

4

5

6

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

8.5 存储和压缩结合

8.5.1 测试 存储和压缩

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

ORC存储方式的压缩:

KeyDefaultNotes

orc.compressZLIBhigh level compression (one of NONE, ZLIB, SNAPPY)

orc.compress.size262,144number of bytes in each compression chunk

orc.stripe.size268,435,456number of bytes in each stripe

orc.row.index.stride10,000number of rows between index entries (must be >= 1000)

orc.create.indextruewhether to create row indexes

orc.bloom.filter.columns“”comma separated list of column names for which bloom filter should be created

orc.bloom.filter.fpp0.05false positive probability for bloom filter (must >0.0 and <1.0)

注意:所有关于ORCFile的参数都是在HQL语句的TBLPROPERTIES字段里面出现

1)创建一个非压缩的的 ORC 存储方式

(1)建表语句

create table log_orc_zlib(

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"="ZLIB");

1

2

3

4

5

6

7

8

9

10

11

12

(2)插入数据

insert into log_orc_zlib select * from log_text;

1

(3)查看插入后数据

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

1

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");

1

2

3

4

5

6

7

8

9

10

11

12

(2)插入数据

insert into log_orc_snappy select * from log_text;

1

(3)查看插入后数据

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

1

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采用的是deflate压缩算法。比snappy压缩的小。

4 )存储方式和压缩总结

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

第9章 Hive实战

9.1 需求描述

统计硅谷影音视频网站的常规指标,各种TopN指标:

–统计视频观看数Top10

–统计视频类别热度Top10

–统计视频观看数Top20所属类别

–统计视频观看数Top50所关联视频的所属类别Rank

–统计每个类别中的视频热度Top10

–统计每个类别视频观看数Top10

9.2 数据结构

表 视频表

字段备注详细描述

video id视频唯一id(String)11位字符串

uploader视频上传者(String)上传视频的用户名String

age视频年龄(int)视频在平台上的整数天

category视频类别(Array)上传视频指定的视频分类

length视频长度(Int)整形数字标识的视频长度

views观看次数(Int)视频被浏览的次数

rate视频评分(Double)满分5分

Ratings流量(Int)视频的流量,整型数字

conments评论数(Int)一个视频的整数评论数

related ids相关视频id(Array)相关视频的id,最多20个

9.3 准备工作

(1)创建外部表:gulivideo_ori,

create external table video_ori(

videoId string,

uploader string,

age int,

category array<string>,

length int,

views int,

rate float,

ratings int,

comments int,

relatedId array<string>)

row format delimited fields terminated by "\t"

collection items terminated by "

1

2

3

4

5

6

7

8

9

10

11

12

13

(2)然后建立内部表:

create table video_orc(

videoId string,

uploader string,

age int,

category array<string>,

length int,

views int,

rate float,

ratings int,

comments int,

relatedId array<string>)

stored as orc

tblproperties("orc.compress"="SNAPPY");

1

2

3

4

5

6

7

8

9

10

11

12

13

(3)向ORC表插入数据

insert into table video_orc select * from video_ori;

1

9.4 业务分析

9.4.1 统计视频观看数Top10

思路:使用order by按照views字段做一个全局排序即可,同时我们设置只显示前10条。

最终代码:

SELECT

videoid,

views

FROM

video_orc

ORDER BY

views DESC

LIMIT 10;

1

2

3

4

5

6

7

8

9.4.2 统计视频类别热度Top10

思路:

(1)即统计每个类别有多少个视频,显示出包含视频最多的前10个类别。

(2)我们需要按照类别group by聚合,然后count组内的videoId个数即可。

(3)因为当前表结构为:一个视频对应一个或多个类别。所以如果要group by类别,需要先将类别进行列转行(展开),然后再进行count即可。

(4)最后按照热度排序,显示前10条。

最终代码:

SELECT

cate,

COUNT(videoid) n

FROM

(

SELECT

videoid,

cate

FROM

video_orc LATERAL VIEW explode(category) tbl as cate) t1

GROUP BY

cate

ORDER BY

n desc

limit 10;

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

9.4.3 统计出视频观看数最高的20个视频的所属类别以及类别包含Top20视频的个数

思路:

(1)先找到观看数最高的20个视频所属条目的所有信息,降序排列

(2)把这20条信息中的category分裂出来(列转行)

(3)最后查询视频分类名称和该分类下有多少个Top20的视频

最终代码:

SELECT

cate,

COUNT(videoid) n

FROM

(

SELECT

videoid,

cate

FROM

(

SELECT

videoid,

views,

category

FROM

video_orc

ORDER BY

views DESC

LIMIT 20 ) t1 LATERAL VIEW explode(category) tbl as cate ) t2

GROUP BY

cate

ORDER BY

n DESC;

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

9.4.4 统计视频观看数Top50所关联视频的所属类别排序

代码:

SELECT

DISTINCT t4.cate,

t5.n

FROM

(

SELECT

explode(category) cate

FROM

(

SELECT

DISTINCT t2.videoid,

v.category

FROM

(

SELECT

explode(relatedid) videoid

FROM

(

SELECT

videoid,

views,

relatedid

FROM

video_orc

ORDER BY

views DESC

LIMIT 50 ) t1 ) t2

JOIN video_orc v on

t2.videoid = v.videoid ) t3 ) t4

JOIN (

SELECT

cate,

COUNT(videoid) n

FROM

(

SELECT

videoid,

cate

FROM

video_orc LATERAL VIEW explode(category) tbl as cate) g1

GROUP BY

cate ) t5 ON

t4.cate = t5.cate

ORDER BY

t5.n DESC;

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

9.4.5 统计每个类别中的视频热度Top10,以Music为例

思路:

(1)要想统计Music类别中的视频热度Top10,需要先找到Music类别,那么就需要将category展开,所以可以创建一张表用于存放categoryId展开的数据。

(2)向category展开的表中插入数据。

(3)统计对应类别(Music)中的视频热度。

最终代码:

创建表类别表:

create table gulivideo_category(

videoId string,

uploader string,

age int,

categoryId string,

length int,

views int,

rate float,

ratings int,

comments int,

relatedId array<string>)

row format delimited

fields terminated by "\t"

collection items terminated by "&"

stored as orc;

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

向类别表中插入数据:

insert into table gulivideo_category

select

videoId,

uploader,

age,

categoryId,

length,

views,

rate,

ratings,

comments,

relatedId

from

gulivideo_orc lateral view explode(category) catetory as categoryId;

1

2

3

4

5

6

7

8

9

10

11

12

13

14

统计Music类别的Top10(也可以统计其他)

select

videoId,

views

from

gulivideo_category

where

categoryId = "Music"

order by

views

desc limit

10;

1

2

3

4

5

6

7

8

9

10

11

9.4.6 统计每个类别视频观看数Top10

最终代码:

CT

cate,

videoid,

views

FROM

(

SELECT

cate,

videoid,

views,

RANK() OVER(PARTITION BY cate

ORDER BY

views DESC) hot

FROM

video_category ) t1

WHERE

hot <= 10;

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

第10 章 分区表和分桶表

10.1 分区表

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

10.1.1 分区表基本操作

1 )引入分区表(需要根据日期对日志进行管理)

/user/hive/warehouse/log_partition/20170702/20170702.log

/user/hive/warehouse/log_partition/20170703/20170703.log

/user/hive/warehouse/log_partition/20170704/20170704.log

1

2

3

2) 创建分区表语法

hive (default)> create table dept_partition(

deptno int, dname string, loc string

)

partitioned by (month string)

row format delimited fields terminated by '\t';

1

2

3

4

5

注意:分区字段不能是表中已经存在的数据,可以将分区字段看作表的伪列。

3)加载数据到分区表中

hive (default)> load data local inpath '/opt/module/data/dept.txt' into table default.dept_partition partition(month='201709');

hive (default)> load data local inpath '/opt/module/data/dept.txt' into table default.dept_partition partition(month='201708');

hive (default)> load data local inpath '/opt/module/data/dept.txt' into table default.dept_partition partition(month='201707');

1

2

3

注意:分区表加载数据时,必须指定分区

图 加载数据到分区表

图 分区表

4)查询分区表中数据

单分区查询

hive (default)> select * from dept_partition where month='201709';

1

多分区联合查询

hive (default)> select * from dept_partition where month='201709'

union

select * from dept_partition where month='201708'

union

select * from dept_partition where month='201707';

_u3.deptno _u3.dname _u3.loc _u3.month

10 ACCOUNTING NEW YORK 201707

10 ACCOUNTING NEW YORK 201708

10 ACCOUNTING NEW YORK 201709

20 RESEARCH DALLAS 201707

20 RESEARCH DALLAS 201708

20 RESEARCH DALLAS 201709

30 SALES CHICAGO 201707

30 SALES CHICAGO 201708

30 SALES CHICAGO 201709

40 OPERATIONS BOSTON 201707

40 OPERATIONS BOSTON 201708

40 OPERATIONS BOSTON 201709

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

5) 增加分区

创建单个分区

hive (default)> alter table dept_partition add partition(month='201706') ;

1

同时创建多个分区

hive (default)> alter table dept_partition add partition(month='201705') partition(month='201704');

1

6) 删除分区

删除单个分区

hive (default)> alter table dept_partition drop partition (month='201704');

1

同时删除多个分区

hive (default)> alter table dept_partition drop partition (month='201705'), partition (month='201706');

1

7)查看分区表有多少分区

hive> show partitions dept_partition;

1

8) 查看分区表结构

hive> desc formatted dept_partition;

\# Partition Information

\# col_name data_type comment

month string

1

2

3

4

10.1.2 分区表注意事项

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

1

2)正常的加载数据

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

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

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

1

2

(2)查询分区数据

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

1

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

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

上传数据

hive (default)> dfs -mkdir -p

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

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

1

2

3

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

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

1

执行修复命令

hive> msck repair table dept_partition2;

1

再次查询数据

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

1

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

上传数据

hive (default)> dfs -mkdir -p

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

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

1

2

3

执行添加分区

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

day='11');

1

2

查询数据

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

1

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

创建目录

hive (default)> dfs -mkdir -p

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

1

2

上传数据

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

dept_partition2 partition(month='201709',day='10');

1

2

3

查询数据

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

1

10.1.3 动态分区调整

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

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

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

hive.exec.dynamic.partition=true

1

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

hive.exec.dynamic.partition.mode=nonstrict

1

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

hive.exec.max.dynamic.partitions=1000

1

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

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

1

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

hive.exec.max.created.files=100000

1

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

hive.error.on.empty.partition=false

1

2 )案例实操

需求:将dept表中的数据按照地区(loc字段),插入到目标表dept_partition的相应分区中。

(1)创建目标分区表

hive (default)> create table dept_partition(id int, name string) partitioned

by (location int) row format delimited fields terminated by '\t';

1

2

3

(2)设置动态分区

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

hive (default)> insert into table dept_partition partition(location) select deptno, dname, loc from dept;

1

2

3

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

hive (default)> show partitions dept_partition;

1

思考:目标分区表是如何匹配到分区字段的?

10.2 分桶表

分区提供一个隔离数据和优化查询的便利方式。不过,并非所有的数据集都可形成合理的分区。对于一张表或者分区,Hive 可以进一步组织成桶,也就是更为细粒度的数据范围划分。

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

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

1)先创建分桶表,通过直接导入数据文件的方式

(1)数据准备

(2)创建分桶表

create table stu_buck(id int, name string)

clustered by(id)

into 4 buckets

row format delimited fields terminated by '\t';

1

2

3

4

(3)查看表结构

hive (default)> desc formatted stu_buck;

Num Buckets: 4

1

2

(4)导入数据到分桶表中

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

stu_buck;

1

2

(5)查看创建的分桶表中是否分成4个桶

(6)查询分桶的数据

select * from stu_buck;

OK

stu_buck.id stu_buck.name

1004 ss4

1008 ss8

1012 ss12

1016 ss16

1001 ss1

1005 ss5

1009 ss9

1013 ss13

1002 ss2

1006 ss6

1010 ss10

1014 ss14

1003 ss3

1007 ss7

1011 ss11

1015 ss15

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

分桶规则:

根据结果可知:Hive的分桶采用对分桶字段的值进行哈希,然后除以桶的个数求余的方式决定该条记录存放在哪个桶当中

第11 章 企业级调优

11.1 Fetch抓取

Fetch抓取是指,Hive中对某些情况的查询可以不必使用MapReduce计算。例如:SELECT * FROM employees;在这种情况下,Hive可以简单地读取employee对应的存储目录下的文件,然后输出查询结果到控制台。

在hive-default.xml.template文件中hive.fetch.task.conversion默认是more,老版本hive默认是minimal,该属性修改为more以后,在全局查找、字段查找、limit查找等都不走mapreduce。

<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

2

3

4

5

6

7

8

9

10

11

1)案例实操:

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

1

2

3

4

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

1

2

3

4

11.2 表的优化

11.2.1 小表、大表Join

将key相对分散,并且数据量小的表放在join的左边,这样可以有效减少内存溢出错误发生的几率;再进一步,可以使用map join让小的维度表(1000条以下的记录条数)先进内存。在map端完成reduce。

实际测试发现:新版的hive已经对小表JOIN大表和大表JOIN小表进行了优化。小表放在左边和右边已经没有明显区别。

案例实操

1)需求

测试大表JOIN小表和小表JOIN大表的效率

2)建大表、小表和 JOIN 后表的语句

// 创建大表

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

1

// 创建小表

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

1

// 创建join后表的语句

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

1

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

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

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

1

2

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

set hive.auto.convert.join = false;

1

5)执行小表 JOIN 大表语句

insert overwrite table jointable

select b.id, b.t, b.uid, b.keyword, b.url_rank, b.click_num, b.click_url

from smalltable s

join bigtable b

on b.id = s.id;

Time taken: 35.921 seconds

No rows affected (44.456 seconds)

1

2

3

4

5

6

7

8

6) 执行大表 JOIN 小表语句

insert overwrite table jointable

select b.id, b.t, 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: 34.196 seconds

No rows affected (26.287 seconds)

1

2

3

4

5

6

7

8

11.2.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>

1

2

3

4

5

6

7

8

启动历史服务器

sbin/mr-jobhistory-daemon.sh start historyserver

1

查看jobhistory

http://hadoop102:19888/jobhistory

(2)创建原始数据表、空id表、合并后数据表

// 创建原始表

create table ori(id bigint, t 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, t 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, t bigint, uid string, keyword string, url_rank int, click_num int, click_url string) row format delimited fields terminated by '\t';

1

2

3

4

5

6

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

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

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

1

2

(4)测试不过滤空id

hive (default)> insert overwrite table jointable select n.* from nullidtable n

left join ori o on n.id = o.id;

1

2

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

1

Time taken: 31.725 seconds

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

1

2

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

随机分布空null值

(1)设置5个reduce个数

set mapreduce.job.reduces = 5;

1

(2)JOIN两张表

insert overwrite table jointable

select n.* from nullidtable n full join ori o on

nvl(n.id,rand()) = o.id;

1

2

3

4

5

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

11.2.3 MapJoin (MR引擎)

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

1 )开启 MapJoin 参数设置

(1)设置自动选择Mapjoin

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

1

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

set hive.mapjoin.smalltable.filesize=25000000;

1

2)MapJoin 工作机制

3) 案例实操:

(1)开启Mapjoin功能

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

1

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

insert overwrite table jointable

select b.id, b.t, b.uid, b.keyword, b.url_rank, b.click_num, b.click_url

from smalltable s

left join bigtable b

on s.id = b.id;

1

2

3

4

5

Time taken: 24.594 seconds

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

insert overwrite table jointable

select b.id, b.t, 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;

1

2

3

4

5

Time taken: 24.315 seconds

11.2.4 Group By

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

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-M1480gUW-1633767577116)(file:///C:\Users\wanka\AppData\Local\Temp\ksohtml\wps80E2.tmp.jpg)]

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

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

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

set hive.map.aggr = true

1

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

set hive.groupby.mapaggr.checkinterval = 100000

1

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

set hive.groupby.skewindata = true

1

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

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

Stage-Stage-1: Map: 1 Reduce: 5 Cumulative CPU: 23.68 sec HDFS Read: 19987 HDFS Write: 9 SUCCESS

Total MapReduce CPU Time Spent: 23 seconds 680 msec

OK

deptno

10

20

30

1

2

3

4

5

6

7

8

优化以后

hive (default)> set hive.groupby.skewindata = true;

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

Stage-Stage-1: Map: 1 Reduce: 5 Cumulative CPU: 28.53 sec HDFS Read: 18209 HDFS Write: 534 SUCCESS

Stage-Stage-2: Map: 1 Reduce: 5 Cumulative CPU: 38.32 sec HDFS Read: 15014 HDFS Write: 9 SUCCESS

Total MapReduce CPU Time Spent: 1 minutes 6 seconds 850 msec

OK

deptno

10

20

30

1

2

3

4

5

6

7

8

9

10

11.2.5 笛卡尔积

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

11.2.6 行列过滤

列处理:在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;

1

2

3

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

1

2

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

11.2.7 分桶

详见6.6章。

11.2.8 分区

详见4.6章。

11.3 合理设置Map 及Reduce 数 (MR引擎)

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

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

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

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

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

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

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

11.3.1 复杂文件增加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

1

2

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

1

2

3

11.3.2 小文件进行合并

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

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

1

(2)在Map-Reduce的任务结束时合并小文件的设置:

在map-only任务结束时合并小文件,默认true

SET hive.merge.mapfiles = true;

1

在map-reduce任务结束时合并小文件,默认false

SET hive.merge.mapredfiles = true;

1

合并文件的大小,默认256M

SET hive.merge.size.per.task = 268435456;

1

当输出文件的平均大小小于该值时,启动一个独立的map-reduce任务进行文件merge

SET hive.merge.smallfiles.avgsize = 16777216;

1

11.3.3 合理设置Reduce数

1)调整 reduce 个数方法一

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

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

1

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

hive.exec.reducers.max=1009

1

(3)计算reducer数的公式

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

1

2 )调整 reduce 个数方法二

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

设置每个job的Reduce个数

set mapreduce.job.reduces = 15;

1

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

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

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

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

11.4 并行执行

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。

1

2

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

11.5 严格模式

Hive可以通过设置防止一些危险操作:

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

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

(3)将hive.strict.checks.cartesian.product设置为true时,会限制笛卡尔积的查询。对关系型数据库非常了解的用户可能期望在执行JOIN查询的时候不使用ON语句而是使用where语句,这样关系数据库的执行优化器就可以高效地将WHERE语句转化成那个ON语句。不幸的是,Hive并不会执行这种优化,因此,如果表足够大,那么这个查询就会出现不可控的情况。

11.6 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>

1

2

3

4

5

6

7

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

11.7 压缩

详见第8章。

11.8 执行计划(Explain)

1)基本语法

EXPLAIN [EXTENDED | DEPENDENCY | AUTHORIZATION] query

1

2)案例实操

(1)查看下面这条语句的执行计划

hive (default)> explain select * from emp;

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

1

2

3

(2)查看详细执行计划

hive (default)> explain extended select * from emp;

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

1

2

附录: 常见错误 及解决 方案

0)如果更换Tez引擎后,执行任务卡住,可以尝试调节容量调度器的资源调度策略

<property>

<name>yarn.scheduler.capacity.maximum-am-resource-percent</name>

<value>0.1</value>

<description>

Maximum percent of resources in the cluster which can be used to run

application masters i.e. controls number of concurrent running

applications.

</description>

</property>

1

2

3

4

5

6

7

8

9

改成

<property>

<name>yarn.scheduler.capacity.maximum-am-resource-percent</name>

<value>1</value>

<description>

Maximum percent of resources in the cluster which can be used to run

application masters i.e. controls number of concurrent running

applications.

</description>

</property>

1

2

3

4

5

6

7

8

9

1)SecureCRT 7.3 出现乱码或者删除不掉数据 , 免安装版的 SecureCRT 卸载或者用虚拟机直接操作或者换安装版的 SecureCRT

2)连接不上mysql数据库

(1)导错驱动包,应该把mysql-connector-java-5.1.27-bin.jar导入/opt/module/hive/lib的不是这个包。错把mysql-connector-java-5.1.27.tar.gz导入hive/lib包下。

(2)修改user表中的主机名称没有都修改为%,而是修改为localhost

3)hive默认的输入格式处理是CombineHiveInputFormat,会对小文件进行合并。

hive (default)> set hive.input.format;

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

1

2

可以采用HiveInputFormat就会根据分区数输出相应的文件。

hive (default)> set hive.input.format=org.apache.hadoop.hive.ql.io.HiveInputFormat;

1

4) 不能执行 mapreduce 程序

可能是hadoop的yarn没开启。

5) 启动 mysql 服务时 , 报 MySQL server PID file could not be found! 异常 。

在/var/lock/subsys/mysql路径下创建hadoop102.pid,并在文件中添加内容:4396

6)报 service mysql status MySQL is not running, but lock file (/var/lock/subsys/mysql[ 失败 ] ) 异常 。

解决方案:在/var/lib/mysql 目录下创建: -rw-rw----. 1 mysql mysql 5 12月 22 16:41 hadoop102.pid 文件,并修改权限为 777。

7 )JVM 堆内存溢出

描述:java.lang.OutOfMemoryError: Java heap space

解决:在yarn-site.xml中加入如下代码

<property>

<name>yarn.scheduler.maximum-allocation-mb</name>

<value>2048</value>

</property>

<property>

<name>yarn.scheduler.minimum-allocation-mb</name>

<value>2048</value>

</property>

<property>

<name>yarn.nodemanager.vmem-pmem-ratio</name>

<value>2.1</value>

</property>

<property>

<name>mapred.child.java.opts</name>

<value>-Xmx1024m</value>

</property>

————————————————

版权声明:本文为CSDN博主「工藤-新二」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。

原文链接:https://blog.csdn.net/qq_39346903/article/details/120328630

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值