【大数据】Hive学习笔记

 

1 Hive基本概念

1.1 什么是Hive

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

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

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

1Hive处理的数据存储在HDFSlinux

2Hive分析数据底层的实现是MapReducegit

3)执行程序运行在Yarngithub

1.2 Hive的优缺点

1.2.1 优势

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

2) 避免了去写MapReduce,减小开发人员的学习成本正则表达式

3) Hive的执行延迟比较高,所以Hive经常使用于数据分析,对实时性要求不高的场合算法

4) Hive优点在于处理大数据,对于处理小数据没有优点,由于Hive的执行延迟比较高sql

5) Hive支持用户自定义函数,用户能够根据本身的需求来实现本身的函数

1.2.2 缺点

1.HiveHQL表达能力有限

1)迭代式算法没法表达

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

2.Hive的效率比较低

1Hive自动生成的MapReduce做业,一般状况下不够智能化

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

1.3 Hive架构原理

 

6-1 Hive架构原理

1.用户接口:Client

CLIcommand-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 是创建在 Hadoop 之上的,全部 Hive 的数据都是存储在 HDFS 中的。而数据库则能够将数据保存在块设备或者本地文件系统中。

1.4.3 数据更新

因为Hive是针对数据仓库应用设计的,而数据仓库的内容是读多写少的。所以,Hive中不建议对数据的改写,全部的数据都是在加载的时候肯定好的。而数据库中的数据一般是须要常常进行修改的,所以可使用 INSERT INTO …  VALUES 添加数据,使用 UPDATE … SET修改数据。

1.4.4 执行

Hive中大多数查询的执行是经过 Hadoop 提供的 MapReduce 来实现的。而数据库一般有本身的执行引擎。

1.4.5 执行延迟

Hive 在查询数据的时候,因为没有索引,须要扫描整个表,所以延迟较高。另一个致使 Hive 执行延迟高的因素是 MapReduce框架。因为MapReduce 自己具备较高的延迟,所以在利用MapReduce 执行Hive查询时,也会有较高的延迟。相对的,数据库的执行延迟较低。固然,这个低是有条件的,即数据规模较0小,当数据规模大到超过数据库的处理能力的时候,Hive的并行计算显然能体现出优点。

1.4.6 可扩展性

因为Hive是创建在Hadoop之上的,所以Hive的可扩展性是和Hadoop的可扩展性是一致的(世界上最大的Hadoop 集群在 Yahoo!2009年的规模在4000 台节点左右)。而数据库因为 ACID 语义的严格限制,扩展行很是有限。目前最早进的并行数据库 Oracle 在理论上的扩展能力也只有100台左右。

1.4.7 数据规模

因为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 Hive安装部署

1.Hive安装及配置

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

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

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

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

[atguigu@hadoop102 module]$ mv apache-hive-1.2.1-bin/ hive

4)修改/opt/module/hive/conf目录下的hive-env.sh.template名称为hive-env.sh

[atguigu@hadoop102 conf]$ mv hive-env.sh.template hive-env.sh

5)配置hive-env.sh文件

a)配置HADOOP_HOME路径

export HADOOP_HOME=/opt/module/hadoop-2.7.2

b)配置HIVE_CONF_DIR路径

export HIVE_CONF_DIR=/opt/module/hive/conf

2.Hadoop集群配置

1)必须启动hdfsyarn

[atguigu@hadoop102 hadoop-2.7.2]$ sbin/start-dfs.sh

[atguigu@hadoop103 hadoop-2.7.2]$ sbin/start-yarn.sh

2HDFS上建立/tmp/user/hive/warehouse两个目录并修改他们的同组权限可写

[atguigu@hadoop102 hadoop-2.7.2]$ bin/hadoop fs -mkdir /tmp

[atguigu@hadoop102 hadoop-2.7.2]$ bin/hadoop fs -mkdir -p /user/hive/warehouse

 

[atguigu@hadoop102 hadoop-2.7.2]$ bin/hadoop fs -chmod g+w /tmp

[atguigu@hadoop102 hadoop-2.7.2]$ bin/hadoop fs -chmod g+w /user/hive/warehouse

3.Hive基本操做

1)启动hive

[atguigu@hadoop102 hive]$ bin/hive

2)查看数据库

hive> show databases;

3)打开默认数据库

hive> use default;

4)显示default数据库中的表

hive> show tables;

5)建立一张表

hive> create table student(id int, name string);

6)显示数据库中有几张表

hive> show tables;

7)查看表的结构

hive> desc student;

8)向表中插入数据

hive> insert into student values(1000,"ss");

9)查询表中数据

hive> select * from student;

10)退出hive

hive> quit;

说明:(查看hivehdfs中的结构)

数据库:在hdfs中表现为${hive.metastore.warehouse.dir}目录下一个文件夹

表:在hdfs中表现所属db目录下一个文件夹,文件夹中存放该表中的具体数据

2.3 将本地文件导入Hive案例

需求

将本地/opt/module/datas/student.txt这个目录下的数据导入到hivestudent(id int, name string)表中。

1数据准备

/opt/module/datas这个目录下准备数据

1)在/opt/module/目录下建立datas

[atguigu@hadoop102 module]$ mkdir datas

2)在/opt/module/datas/目录下建立student.txt文件并添加数据

[atguigu@hadoop102 datas]$ touch student.txt

[atguigu@hadoop102 datas]$ vi student.txt

1001 zhangshan

1002 lishi

1003 zhaoliu

注意以tab键间隔。

2.Hive实际操做

1)启动hive

[atguigu@hadoop102 hive]$ bin/hive

2)显示数据库

hive> show databases;

3)使用default数据库

hive> use default;

4)显示default数据库中的表

hive> show tables;

5)删除已建立的student

hive> drop table student;

6)建立student, 并声明文件分隔符’\t’

hive> create table student(id int, name string) ROW FORMAT DELIMITED FIELDS TERMINATED

 BY '\t';

7)加载/opt/module/datas/student.txt 文件到student数据库表中。

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

8Hive查询结果

hive> select * from student;

OK

1001 zhangshan

1002 lishi

1003 zhaoliu

Time taken: 0.266 seconds, Fetched: 3 row(s)

3.遇到的问题

再打开一个客户端窗口启动hive,会产生java.sql.SQLException异常。

Exception in thread "main" java.lang.RuntimeException: java.lang.RuntimeException:

 Unable to instantiate

 org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient

        at org.apache.hadoop.hive.ql.session.SessionState.start(SessionState.java:522)

        at org.apache.hadoop.hive.cli.CliDriver.run(CliDriver.java:677)

        at org.apache.hadoop.hive.cli.CliDriver.main(CliDriver.java:621)

        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)

        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

        at java.lang.reflect.Method.invoke(Method.java:606)

        at org.apache.hadoop.util.RunJar.run(RunJar.java:221)

        at org.apache.hadoop.util.RunJar.main(RunJar.java:136)

Caused by: java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient

        at org.apache.hadoop.hive.metastore.MetaStoreUtils.newInstance(MetaStoreUtils.java:1523)

        at org.apache.hadoop.hive.metastore.RetryingMetaStoreClient.<init>(RetryingMetaStoreClient.java:86)

        at org.apache.hadoop.hive.metastore.RetryingMetaStoreClient.getProxy(RetryingMetaStoreClient.java:132)

        at org.apache.hadoop.hive.metastore.RetryingMetaStoreClient.getProxy(RetryingMetaStoreClient.java:104)

        at org.apache.hadoop.hive.ql.metadata.Hive.createMetaStoreClient(Hive.java:3005)

        at org.apache.hadoop.hive.ql.metadata.Hive.getMSC(Hive.java:3024)

        at org.apache.hadoop.hive.ql.session.SessionState.start(SessionState.java:503)

... 8 more

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

2.4 MySql安装

2.4.1 安装包准备

1.查看mysql是否安装,若是安装了,卸载mysql

1)查看

[root@hadoop102 桌面]# rpm -qa|grep mysql

mysql-libs-5.1.73-7.el6.x86_64

2)卸载

[root@hadoop102 桌面]# rpm -e --nodeps mysql-libs-5.1.73-7.el6.x86_64

2.解压mysql-libs.zip文件到当前目录

[root@hadoop102 software]# unzip mysql-libs.zip

[root@hadoop102 software]# ls

mysql-libs.zip

mysql-libs

3.进入到mysql-libs文件夹下

[root@hadoop102 mysql-libs]# ll

总用量 76048

-rw-r--r--. 1 root root 18509960 3月  26 2015 MySQL-client-5.6.24-1.el6.x86_64.rpm

-rw-r--r--. 1 root root  3575135 12月  1 2013 mysql-connector-java-5.1.27.tar.gz

-rw-r--r--. 1 root root 55782196 3月  26 2015 MySQL-server-5.6.24-1.el6.x86_64.rpm

2.4.2 安装MySql服务器

1.安装mysql服务端

[root@hadoop102 mysql-libs]# rpm -ivh MySQL-server-5.6.24-1.el6.x86_64.rpm

2.查看产生的随机密码

[root@hadoop102 mysql-libs]# cat /root/.mysql_secret

OEXaQuS8IWkG19Xs

3.查看mysql状态

[root@hadoop102 mysql-libs]# service mysql status

4.启动mysql

[root@hadoop102 mysql-libs]# service mysql start

2.4.3 安装MySql客户端

1.安装mysql客户端

[root@hadoop102 mysql-libs]# rpm -ivh MySQL-client-5.6.24-1.el6.x86_64.rpm

2.连接mysql

[root@hadoop102 mysql-libs]# mysql -uroot -p OEXaQuS8IWkG19Xs

3.修改密码

mysql>SET PASSWORD=PASSWORD('000000');

4.退出mysql

mysql>exit

2.4.4 MySqluser表中主机配置

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

1.进入mysql

[root@hadoop102 mysql-libs]# mysql -uroot -p000000

2.显示数据库

mysql>show databases;

3.使用mysql数据库

mysql>use mysql;

4.展现mysql数据库中的全部表

mysql>show tables;

5.展现user表的结构

mysql>desc user;

6.查询user

mysql>select User, Host, Password from user;

7.修改user表,把Host表内容修改成%

mysql>update user set host='%' where host='localhost';

8.删除root用户的其余host

mysql>delete from user where Host='hadoop102';

mysql>delete from user where Host='127.0.0.1';

mysql>delete from user where Host='::1';

9.刷新

mysql>flush privileges;

10.退出

mysql>quit;

2.5 Hive元数据配置到MySql

2.5.1 驱动拷贝

1.在/opt/software/mysql-libs目录下解压mysql-connector-java-5.1.27.tar.gz驱动包

[root@hadoop102 mysql-libs]# tar -zxvf mysql-connector-java-5.1.27.tar.gz

2.拷贝/opt/software/mysql-libs/mysql-connector-java-5.1.27目录下的mysql-connector-java-5.1.27-bin.jar/opt/module/hive/lib/

[root@hadoop102 mysql-connector-java-5.1.27]# cp mysql-connector-java-5.1.27-bin.jar

 /opt/module/hive/lib/

2.5.2 配置MetastoreMySql

1./opt/module/hive/conf目录下建立一个hive-site.xml

[atguigu@hadoop102 conf]$ touch hive-site.xml

[atguigu@hadoop102 conf]$ vi hive-site.xml

2.根据官方文档配置参数,拷贝数据到hive-site.xml文件中

https://cwiki.apache.org/confluence/display/Hive/AdminManual+MetastoreAdmin

<?xml version="1.0"?>

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

<configuration>

<property>

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

  <value>jdbc:mysql://hadoop102:3306/metastore?createDatabaseIfNotExist=true</value>

  <description>JDBC connect string for a JDBC metastore</description>

</property>

 

<property>

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

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

  <description>Driver class name for a JDBC metastore</description>

</property>

 

<property>

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

  <value>root</value>

  <description>username to use against metastore database</description>

</property>

 

<property>

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

  <value>000000</value>

  <description>password to use against metastore database</description>

</property>

</configuration>

3.配置完毕后,若是启动hive异常,能够从新启动虚拟机。(重启后,别忘了启动hadoop集群)

2.5.3 多窗口启动Hive测试

1.先启动MySQL

[atguigu@hadoop102 mysql-libs]$ mysql -uroot -p000000

查看有几个数据库

mysql> show databases;

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

| Database           |

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

| information_schema |

| mysql             |

| performance_schema |

| test               |

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

2.再次打开多个窗口,分别启动hive

[atguigu@hadoop102 hive]$ bin/hive

3.启动hive后,回到MySQL窗口查看数据库,显示增长了metastore数据库

mysql> show databases;

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

| Database           |

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

| information_schema |

| metastore          |

| mysql             |

| performance_schema |

| test               |

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

2.6 HiveJDBC访问

2.6.1 启动hiveserver2服务

[atguigu@hadoop102 hive]$ bin/hiveserver2

2.6.2 启动beeline

[atguigu@hadoop102 hive]$ bin/beeline

Beeline version 1.2.1 by Apache Hive

beeline>

2.6.3 链接hiveserver2

beeline> !connect jdbc:hive2://hadoop102:10000(回车)

Connecting to jdbc:hive2://hadoop102:10000

Enter username for jdbc:hive2://hadoop102:10000: atguigu(回车)

Enter password for jdbc:hive2://hadoop102:10000: (直接回车)

Connected to: Apache Hive (version 1.2.1)

Driver: Hive JDBC (version 1.2.1)

Transaction isolation: TRANSACTION_REPEATABLE_READ

0: jdbc:hive2://hadoop102:10000> show databases;

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

| database_name  |

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

| default        |

| hive_db2       |

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

2.7 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.“-e”不进入hive的交互窗口执行sql语句

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

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

1)在/opt/module/datas目录下建立hivef.sql文件

[atguigu@hadoop102 datas]$ touch hivef.sql

文件中写入正确的sql语句

select *from student;

2)执行文件中的sql语句

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

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

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

2.8 Hive其余命令操做

1.退出hive窗口:

hive(default)>exit;

hive(default)>quit;

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

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

quit:不提交数据,退出;

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

hive(default)>dfs -ls /;

3.在hive cli命令窗口中如何查看本地文件系统

hive(default)>! ls /opt/module/datas;

4.查看在hive中输入的全部历史命令

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

2)查看. hivehistory文件

[atguigu@hadoop102 ~]$ cat .hivehistory

2.9 Hive常见属性配置

2.9.1 Hive数据仓库位置配置

1Default数据仓库的最原始位置是在hdfs上的:/user/hive/warehouse路径下

2在仓库目录下,没有对默认的数据库default建立文件夹。若是某张表属于default数据库,直接在数据仓库目录下建立一个文件夹。

3)修改default数据仓库原始位置(将hive-default.xml.template以下配置信息拷贝到hive-site.xml文件中)

<property>

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

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

<description>location of default database for the warehouse</description>

</property>

配置同组用户有执行权限

bin/hdfs dfs -chmod g+w /user/hive/warehouse

2.9.2 查询后信息显示配置

1)在hive-site.xml文件中添加以下配置信息,就能够实现显示当前数据库,以及查询表的头信息配置。

<property>

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

<value>true</value>

</property>

 

<property>

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

<value>true</value>

</property>

2)从新启动hive,对比配置先后差别

1)配置前,如图6-2所示

 

6-2 配置前

2)配置后,如图6-3所示

 

6-3 配置后

2.9.3 Hive运行日志信息配置

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

2.修改hivelog存放日志到/opt/module/hive/logs

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

hive-log4j.properties

[atguigu@hadoop102 conf]$ pwd

/opt/module/hive/conf

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

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

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

2.9.4 参数配置方式

1.查看当前全部的配置信息

hive>set;

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;

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

查看参数设置:

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

3)参数声明方式

能够在HQL中使用SET关键字设定参数

例如:

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

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

查看参数设置

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

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

3 Hive数据类型

3.1 基本数据类型

6-1

Hive数据类型

Java数据类型

长度

例子

TINYINT

byte

1byte有符号整数

20

SMALINT

short

2byte有符号整数

20

INT

int

4byte有符号整数

20

BIGINT

long

8byte有符号整数

20

BOOLEAN

boolean

布尔类型,true或者false

TRUE  FALSE

FLOAT

float

单精度浮点数

3.14159

DOUBLE

double

双精度浮点数

3.14159

STRING

string

字符系列。能够指定字符集。可使用单引号或者双引号。

now is the time’ “for all good men

TIMESTAMP

 

时间类型

 

BINARY

 

字节数组

 

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

3.2 集合数据类型

6-2

数据类型

描述

语法示例

STRUCT

c语言中的struct相似,均可以经过“点”符号访问元素内容。例如,若是某个列的数据类型是STRUCT{first STRING, last STRING},那么1个元素能够经过字段.first来引用

struct()

例如struct<street:string, city:string>

MAP

MAP是一组键-值对元组集合,使用数组表示法能够访问数据。例如,若是某个列的数据类型是MAP,其中键->值对是’first->John’和’last->Doe’,那么能够经过字段名[last]获取最后一个元素

map()

例如map<string, int>

ARRAY

数组是一组具备相同类型和名称的变量的集合。这些变量称为数组的元素,每一个数组元素都有一个编号,编号从零开始。例如,数组值为[John, Doe],那么2个元素能够经过数组名[1]进行引用

Array()

例如array<string>

Hive有三种复杂数据类型ARRAYMAP STRUCTARRAYMAPJava中的ArrayMap相似,而STRUCTC语言中的Struct相似,它封装了一个命名字段集合,复杂数据类型容许任意层次的嵌套。

案例实操

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"

    }

}

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

注意:MAPSTRUCTARRAY里的元素间关系均可以用同一个字符表示,这里用“_”

3Hive上建立测试表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';

字段解释:

row format delimited fields terminated by ','  -- 列分隔符

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

map keys terminated by ':' -- MAP中的keyvalue的分隔符

lines terminated by '\n'; -- 行分隔符

4导入文本数据到测试表

hive (default)> load data local inpath ‘/opt/module/datas/test.txt’into table test

5)访问三种集合列里的数据,如下分别是ARRAYMAPSTRUCT的访问方式

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)

3.3 类型转化

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

1.隐式类型转换规则以下

1)任何整数类型均可以隐式地转换为一个范围更广的类型,如TINYINT能够转换成INTINT能够转换成BIGINT

2)全部整数类型、FLOATSTRING类型均可以隐式地转换成DOUBLE

3TINYINTSMALLINTINT均可以转换为FLOAT

4BOOLEAN类型不能够转换为任何其它的类型。

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    |

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

4 DDL数据定义

4.1 建立数据库

CREATE DATABASE [IF NOT EXISTS] database_name

[COMMENT database_comment]

[LOCATION hdfs_path]

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

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

hive (default)> create database db_hive;

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;

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

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

 

6-4 数据库存放位置

4.2 查询数据库

4.2.1 显示数据库

1.显示数据库

hive> show databases;

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

hive> show databases like 'db_hive*';

OK

db_hive

db_hive_1

4.2.2 查看数据库详情

1.显示数据库信息

hive> desc database db_hive;

OK

db_hive hdfs://hadoop102:9000/user/hive/warehouse/db_hive.db atguiguUSER

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

hive> desc database extended db_hive;

OK

db_hive hdfs://hadoop102:9000/user/hive/warehouse/db_hive.db atguiguUSER

4.2.3 切换当前数据库

hive (default)> use db_hive;

4.3 修改数据库

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

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

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}

4.4 删除数据库

1.删除空数据库

hive>drop database db_hive2;

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;

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;

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]

2.字段解释说明 

1CREATE TABLE 建立一个指定名字的表。若是相同名字的表已经存在,则抛出异常;用户能够用 IF NOT EXISTS 选项来忽略这个异常。

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

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

4PARTITIONED BY建立分区表

5CLUSTERED BY建立分桶表

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

7ROW 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。在建表的时候,用户还须要为表指定列,用户在指定表的列的同时也会指定自定义的SerDeHive经过SerDe肯定表的具体的列的数据。

SerDeSerialize/Deserilize的简称, hive使用Serde进行行对象的序列与反序列化。

8STORED AS指定存储文件类型

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

若是文件数据是纯文本,可使用STORED AS TEXTFILE。若是数据须要压缩,使用 STORED AS SEQUENCEFILE

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

10AS:后跟查询语句,根据查询结果建立表

11LIKE容许用户复制现有的表结构,可是不复制数据。

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

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

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

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

create table if not exists student4 like student;

4)查询表的类型

hive (default)> desc formatted student2;

Table Type:             MANAGED_TABLE  

4.5.2 外部表

1.理论

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

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

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

3.案例实操

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

(1) 上传数据到HDFS

hive (default)> dfs -mkdir /student;

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

2)建表语句

建立外部

hive (default)> create external table stu_external(

id int,

name string)

row format delimited fields terminated by '\t'

location '/student';

3)查看建立的表

hive (default)> select * from stu_external;

OK

stu_external.id stu_external.name

1001    lisi

1002    wangwu

1003    zhaoliu

4)查看表格式化数据

hive (default)> desc formatted dept;

Table Type:             EXTERNAL_TABLE

5)删除外部表

hive (default)> drop table stu_external;

外部表删除后,hdfs中的数据还在,可是metadatastu_external的元数据已被删除

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

1)查询表的类型

hive (default)> desc formatted student2;

Table Type:             MANAGED_TABLE

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

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

3)查询表的类型

hive (default)> desc formatted student2;

Table Type:             EXTERNAL_TABLE

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

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

5查询表的类型

hive (default)> desc formatted student2;

Table Type:             MANAGED_TABLE

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

4.6 分区表

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

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

2.建立分区表语法

hive (default)> create table dept_partition(

deptno int, dname string, loc string

)

partitioned by (month string)

row format delimited fields terminated by '\t';

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

3.加载数据到分区表中

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

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

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

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

 

6-5 加载数据到分区表

 

6-6 分区表

4.查询分区表中数据

单分区查询

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

多分区联合查询

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

5.增长分区

建立单个分区

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

同时建立多个分区

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

6.删除分区

删除单个分区

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

同时删除多个分区

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

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

hive> show partitions dept_partition;

8.查看分区表结构

hive> desc formatted dept_partition;

 

# Partition Information          

# col_name              data_type               comment             

month                   string    

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

2.正常的加载数据

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

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

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

2)查询分区数据

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

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

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

上传数据

hive (default)> dfs -mkdir -p

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

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

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

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

执行修复命令

hive> msck repair table dept_partition2;

再次查询数据

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

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

上传数据

hive (default)> dfs -mkdir -p

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

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

执行添加分区

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

 day='11');

查询数据

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

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

建立目录

hive (default)> dfs -mkdir -p

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

上传数据

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

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

查询数据

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

4.7 修改表

4.7.1 重命名表

1.语法

ALTER TABLE table_name RENAME TO new_table_name

2.实操案例

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

4.7.2 增长、修改和删除表分区

详见4.6.1分区表基本操做。

4.7.3 增长/修改/替换列信息

1.语法

更新列

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

增长和替换列

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

注:ADD是表明新增一字段,字段位置在全部列后面(partition列前)REPLACE则是表示替换表中全部字段

2.实操案例

1)查询表结构

hive> desc dept_partition;

2)添加列

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

3)查询表结构

hive> desc dept_partition;

4)更新列

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

5)查询表结构

hive> desc dept_partition;

6)替换列

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

 string, loc string);

7)查询表结构

hive> desc dept_partition;

4.8 删除表

hive (default)> drop table dept_partition;

5 DML数据操做

5.1 数据导入

5.1.1 向表中装载数据(Load

1.语法

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

1load data:表示加载数据

2local:表示从本地加载数据到hive表;不然从HDFS加载数据到hive

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

4overwrite:表示覆盖表中已有数据,不然表示追加

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

6student:表示具体的表

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

2.实操案例

0)建立一张表

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

1)加载本地文件到hive

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

2)加载HDFS文件到hive

上传文件到HDFS

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

加载HDFS上数据

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

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

上传文件到HDFS

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

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

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

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

1.建立一张分区表

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

2.基本插入数据

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

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

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

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

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

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

详见4.5.1章建立表。

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

create table if not exists student3

as select id, name from student;

5.1.4 建立表时经过Location指定加载数据路径

1.上传数据到hdfs

hive (default)> dfs -mkdir /student;

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

2. 建立表,并指定在hdfs上的位置

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

              id int, name string

              )

              row format delimited fields terminated by '\t'

              location '/student;

3.查询数据

hive (default)> select * from student5;

5.1.5 Import数据到指定Hive表中

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

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

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

5.2 数据导出

5.2.1 Insert导出

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

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

            select * from student;

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

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

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

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

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

             ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t'

             select * from student;

5.2.2 Hadoop命令导出到本地

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

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

5.2.3 Hive Shell 命令导出

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

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

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

5.2.4 Export导出到HDFS

(defahiveult)> export table default.student to

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

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

5.2.5 Sqoop导出

后续课程专门讲。

5.3 清除表中数据(Truncate

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

hive (default)> truncate table student;

6 查询

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

查询语句语法:

[WITH CommonTableExpression (, CommonTableExpression)*]    (Note: Only available

 starting with Hive 0.13.0)

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]

6.1 基本查询(Select…From

6.1.1 全表和特定列查询

建立部门表

create table if not exists dept(

deptno int,

dname string,

loc int

)

row format delimited fields terminated by '\t';

建立员工表

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

导入数据

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

dept;

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

1.全表查询

hive (default)> select * from emp;

2.选择特定列查询

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

注意:

1SQL 语言大小写不敏感。 

2SQL 能够写在一行或者多行

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

4)各子句通常要分行写。

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

6.1.2 列别名

1.重命名一个列

2.便于计算

3.紧跟列名,也能够在列名和别名之间加入关键字AS 

4.案例实操

查询名称和部门

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

6.1.3 算术运算符

6-3

运算符

描述

A+B

AB 相加

A-B

A减去B

A*B

AB 相乘

A/B

A除以B

A%B

AB取余

A&B

AB按位取与

A|B

AB按位取或

A^B

AB按位取异或

~A

A按位取反

案例实操

  查询出全部员工的薪水后加1显示。

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

6.1.4 经常使用函数

1.求总行数(count

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

2.求工资的最大值(max

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

3.求工资的最小值(min

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

4.求工资的总和(sum

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

5.求工资的平均值(avg

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

6.1.5 Limit语句

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

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

6.2 Where语句

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

2WHERE子句紧随FROM子句

3.案例实操

查询出薪水大于1000的全部员工

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

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

6.2.1 比较运算符(Between/In/ Is Null

1)下面表中描述了谓词操做符,这些操做符一样能够用于JOIN…ONHAVING语句中。

6-4

操做符

支持的数据类型

描述

A=B

基本数据类型

若是A等于B则返回TRUE,反之返回FALSE

A<=>B

基本数据类型

若是AB都为NULL,则返回TRUE,其余的和等号(=)操做符的结果一致,若是任一为NULL则结果为NULL

A<>B, A!=B

基本数据类型

A或者BNULL则返回NULL;若是A不等于B,则返回TRUE,反之返回FALSE

A<B

基本数据类型

A或者BNULL,则返回NULL;若是A小于B,则返回TRUE,反之返回FALSE

A<=B

基本数据类型

A或者BNULL,则返回NULL;若是A小于等于B,则返回TRUE,反之返回FALSE

A>B

基本数据类型

A或者BNULL,则返回NULL;若是A大于B,则返回TRUE,反之返回FALSE

A>=B

基本数据类型

A或者BNULL,则返回NULL;若是A大于等于B,则返回TRUE,反之返回FALSE

A [NOT] BETWEEN B AND C

基本数据类型

若是AB或者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 B

STRING 类型

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

A RLIKE B, A REGEXP B

STRING 类型

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

2)案例实操

1)查询出薪水等于5000的全部员工

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

2)查询工资在5001000的员工信息

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

3)查询comm为空的全部员工信息

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

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

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

6.2.2 LikeRLike

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

2)选择条件能够包含字符或数字:

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

_ 表明一个字符。

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

4)案例实操

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

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

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

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

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

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

6.2.3 逻辑运算符(And/Or/Not

6-5

操做符

含义

AND

逻辑并

OR

逻辑或

NOT

逻辑否

案例实操

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

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

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

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

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

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

6.3 分组

6.3.1 Group By语句

GROUP BY语句一般会和聚合函数一块儿使用,按照一个或者多个列队结果进行分组,而后对每一个组执行聚合操做。

案例实操:

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

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

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

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

 t.deptno, t.job;

6.3.2 Having语句

1.havingwhere不一样点

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

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

2.案例实操

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

求每一个部门的平均工资

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

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

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

 avg_sal > 2000;

6.4 Join语句

6.4.1 等值Join

Hive支持一般的SQL JOIN语句,可是只支持等值链接,不支持非等值链接。

案例实操

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

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

6.4.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;

6.4.3 内链接

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

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

 = d.deptno;

6.4.4 左外链接

左外链接:JOIN操做符左边表中符合WHERE子句的全部记录将会被返回。

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

6.4.5 右外链接

右外链接:JOIN操做符右边表中符合WHERE子句的全部记录将会被返回。

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

6.4.6 满外链接

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

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

 = d.deptno;

6.4.7 多表链接

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

数据准备

 

1.建立位置表

create table if not exists location(

loc int,

loc_name string

)

row format delimited fields terminated by '\t';

2.导入数据

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

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;

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

注意:为何不是表d和表l先进行链接操做呢?这是由于Hive老是按照从左到右的顺序执行的。

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

6.4.8 笛卡尔积

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

1)省略链接条件

2)链接条件无效

3)全部表中的全部行互相链接

2.案例实操

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

6.4.9 链接谓词中不支持or

hive join目前不支持在on子句中使用谓词or

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

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

6.5 排序

6.5.1 全局排序(Order By

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

1.使用 ORDER BY 子句排序

ASCascend: 升序(默认)

DESCdescend: 降序

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

3.案例实操 

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

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

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

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

6.5.2 按照别名排序

按照员工薪水的2倍排序

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

6.5.3 多个列排序

按照部门和工资升序排序

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

6.5.4 每一个MapReduce内部排序(Sort By

Sort By:对于大规模的数据集order by的效率很是低。在不少状况下,并不须要全局排序,此时能够使用sort by

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

1.设置reduce个数

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

2.查看设置reduce个数

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

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

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

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

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

 select * from emp sort by deptno desc;

6.5.5 分区排序(Distribute By

Distribute By: 在有些状况下,咱们须要控制某个特定行应该到哪一个reducer,一般是为了进行后续的汇集操做。distribute by 句能够作这件事distribute by相似MRpartition(自定义分区),进行分区,结合sort by使用。 

对于distribute by进行测试,必定要分配多reduce进行处理,不然没法看到distribute by的效果。

案例实操:

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

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

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

注意:

1. distribute by的分区规则是根据分区字段hashreduce的个数进行模除后,余数相同的分到一个

2. Hive要求DISTRIBUTE BY语句要写在SORT BY语句以前。

6.5.6 Cluster By

distribute bysorts 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;

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

6.6 分桶及抽样查询

6.6.1 分桶表数据存储

分区提供一个隔离数据和优化查询的便利方式。不过,并不是全部的数据集均可造成合理的分区。对于一张表或者分区,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';

3)查看表结构

hive (default)> desc formatted stu_buck;

Num Buckets:            4     

4)导入数据到分桶表中

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

 stu_buck;

5)查看建立的分桶表中是否分红4个桶,如图6-7所示

 

6-7 未分桶

发现并无分红4个桶。是什么缘由呢?

2.建立分桶表时,数据经过子查询的方式导入

(1)先建一个普通的stu表

create table stu(id int, name string)

row format delimited fields terminated by '\t';

(2)向普通的stu表中导入数据

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

(3)清空stu_buck表中数据

truncate table stu_buck;

select * from stu_buck;

(4)导入数据到分桶表,经过子查询的方式

insert into table stu_buck

select id, name from stu;

5)发现仍是只有一个分桶,如图6-8所示

 

6-8 未分桶

6)须要设置一个属性

hive (default)> set hive.enforce.bucketing=true;

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

hive (default)> insert into table stu_buck

select id, name from stu;

 

6-9 分桶

7)查询分桶的数据

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

分桶规则:

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

6.6.2 分桶抽样查询

对于很是大的数据集,有时用户须要使用的是一个具备表明性的查询结果而不是所有结果。Hive能够经过对表进行抽样来知足这个需求。

查询表stu_buck中的数据。

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

注:tablesample是抽样语句,语法:TABLESAMPLE(BUCKET x OUT OF y) 

y必须是tablebucket数的倍数或者因子。hive根据y的大小,决定抽样的比例。例如,table总共分了4份,当y=2时,抽取(4/2=)2bucket的数据,当y=8时,抽取(4/8=)1/2bucket的数据。

x表示从哪一个bucket开始抽取,若是须要取多个分区,之后的分区号为当前分区号加上y。例如,tablebucket数为4tablesample(bucket 1 out of 2),表示总共抽取(4/2=2bucket的数据,抽取第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

6.7 其余经常使用查询函数

6.7.1 空字段赋值

  1. 函数说明

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

  1. 数据准备:采用员工表
  2. 查询:若是员工的commNULL,则用-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. 查询:若是员工的commNULL,则用领导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

6.7.2 CASE WHEN

1. 数据准备

name

dept_id

sex

悟空

A

大海

A

宋宋

B

 

 

凤姐

A

婷姐

B

婷婷

B

2.需求

求出不一样部门男女各多少人。结果以下:

A     2       1

B     1       2

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

[atguigu@hadoop102 datas]$ vi emp_sex.txt

悟空 A 男

大海 A 男

宋宋 B 男

凤姐 A 女

婷姐 B 女

婷婷 B 女

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/datas/emp_sex.txt' into table emp_sex;

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;

6.7.2 行转列

1.相关函数说明

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

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

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

2.数据准备

6-6 数据准备

name

constellation

blood_type

孙悟空

白羊座

A

大海

射手座

A

宋宋

白羊座

B

猪八戒

白羊座

A

凤姐

射手座

A

3.需求

把星座和血型同样的人归类到一块儿。结果以下:

射手座,A            大海|凤姐

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

白羊座,B            宋宋

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

[atguigu@hadoop102 datas]$ vi constellation.txt

孙悟空 白羊座 A

大海      射手座 A

宋宋      白羊座 B

猪八戒    白羊座 A

凤姐      射手座 A

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/datas/constellation.txt" into table person_info;

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;

6.7.3 列转行

1.函数说明

EXPLODE(col)hive中复杂的array或者map结构拆分红多行。

LATERAL VIEW

用法:LATERAL VIEW udtf(expression) tableAlias AS columnAlias

解释:用于和split, explodeUDTF一块儿使用,它可以将一列数据拆成多行数据,在此基础上能够对拆分后的数据进行聚合。

2.数据准备

6-7 数据准备

movie

category

《疑犯追踪》

悬疑,动做,科幻,剧情

Lie to me

悬疑,警匪,动做,心理,剧情

《战狼2

战争,动做,灾难

3.需求

将电影分类中的数组数据展开。结果以下:

《疑犯追踪》      悬疑

《疑犯追踪》      动做

《疑犯追踪》      科幻

《疑犯追踪》      剧情

Lie to me》   悬疑

Lie to me》   警匪

Lie to me》   动做

Lie to me》   心理

Lie to me》   剧情

《战狼2》        战争

《战狼2》        动做

《战狼2》        灾难

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

[atguigu@hadoop102 datas]$ vi movie.txt

《疑犯追踪》 悬疑,动做,科幻,剧情

Lie to me 悬疑,警匪,动做,心理,剧情

《战狼2 战争,动做,灾难

5.建立hive表并导入数据

create table movie_info(

    movie string,

    category array<string>)

row format delimited fields terminated by "\t"

collection items terminated by ",";

load data local inpath "/opt/module/datas/movie.txt" into table movie_info;

6.按需求查询数据

select

    movie,

    category_name

from

    movie_info lateral view explode(category) table_tmp as category_name;

6.7.4 窗口函数(开窗函数)

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

3.需求

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

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

(3)上述的场景,要将cost按照日期进行累加

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

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

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

[atguigu@hadoop102 datas]$ vi business.txt

5.建立hive表并导入数据

create table business(

name string,

orderdate string,

cost int

) ROW FORMAT DELIMITED FIELDS TERMINATED BY ',';

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

6.按需求查询数据

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

select name,count(*) over ()

from business 

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

group by name;

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

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

 business;

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

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;

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

select * from (

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

    from business

) t

where sorted = 1;

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.需求

计算每门学科成绩排名。

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

[atguigu@hadoop102 datas]$ vi score.txt

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.按需求查询数据

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 自定义函数

1Hive 自带了一些函数,好比:max/min等,可是数量有限,本身能够经过自定义UDF来方便的扩展。

2)当Hive提供的内置函数没法知足你的业务处理须要时,此时就能够考虑使用用户自定义函数(UDFuser-defined function)。

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

1UDFUser-Defined-Function

一进一出

2UDAFUser-Defined Aggregation Function

汇集函数,多进一出

相似于:count/max/min

3UDTFUser-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)注意事项

1UDF必需要有返回类型,能够返回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)> create temporary function mylower as "com.atguigu.hive.Lower";

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

hive (default)> select ename, mylower(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 mavenprotobuf)

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

压缩格式

工具

算法

文件扩展名

是否可切分

DEFLATE

DEFLATE

.deflate

Gzip

gzip

DEFLATE

.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

 

8.3 开启Map输出阶段压缩

开启map输出阶段压缩能够减小jobmapReduce 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;

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组成,每一个stripe通常为HDFS的块大小,每个stripe包含多条记录,这些记录按照列进行独立存储,对应到Parquet中的row group的概念。每一个Stripe里有三部分组成,分别是Index Data,Row Data,Stripe 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文件是以二进制方式存储的,因此是不能够直接读取的,文件中包括该文件的数据和元数据,所以Parquet格式文件是自解析的。

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

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

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

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

 

6-12  Parquet格式

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

8.5.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 ;

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

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

268,435,456

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)

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

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

4.存储方式和压缩总结

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

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在适当的时候自动启动这个优化,默认是false

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小表进行了优化。小表放在左边和右边已经没有明显区别。

案例实操

需求

测试大表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: 35.921 seconds

No rows affected (44.456 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: 34.196 seconds

No rows affected (26.287 seconds)

9.3.2 大表Join大表

1.KEY过滤

有时join超时是由于某些key对应的数据太多,而相同key对应的数据都会发送到相同的reducer上,从而致使内存不够。此时咱们应该仔细分析这些异常的key,不少状况下,这些key对应的数据是异常数据,咱们须要在SQL语句中进行过滤。例如key对应的字段为空,操做以下:

案例实操

1)配置历史服务器

配置mapred-site.xml

<property>

<name>mapreduce.jobhistory.address</name>

<value>hadoop102:10020</value>

</property>

<property>

    <name>mapreduce.jobhistory.webapp.address</name>

    <value>hadoop102:19888</value>

</property>

启动历史服务器

sbin/mr-jobhistory-daemon.sh start historyserver

查看jobhistory

http://hadoop102:19888/jobhistory

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

// 建立原始表

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

// 建立空id表

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

// 建立join后表的语句

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

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

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

Time taken: 31.725 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(小表join大表)

若是不指定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所示

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

set hive.map.aggr = true

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

set hive.groupby.mapaggr.checkinterval = 100000

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

set hive.groupby.skewindata = true

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

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

优化之后

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

9.3.5 Count(Distinct) 去重统计

数据量小的时候无所谓,数据量大的状况下,因为COUNT DISTINCT的全聚合操做即便设定了reduce task个数,set mapred.reduce.tasks=100hive也只会启动一个reducer。,这就形成一个Reduce处理的数据量太大,致使整个Job很难完成,通常COUNT DISTINCT使用先GROUP BYCOUNT的方式替换:

案例实操

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查询

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只能使用1reducer来完成笛卡尔积

9.3.7 行列过滤

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

Time taken: 30.058 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的节点上,最大一共能够建立多少个动态分区。默认1000

hive.exec.max.dynamic.partitions=1000

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

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

(5)整个MR Job中,最大能够建立多少个HDFS文件。默认100000

hive.exec.max.created.files=100000

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

hive.error.on.empty.partition=false

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

2)设置动态分区

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

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

3)查看目标分区表的分区状况

hive (default)> show partitions dept_partition;

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

9.3.9 分桶

详见6.6章。

9.3.10 分区

详见4.6章。

9.4 数据倾斜

9.4.1 合理设置Map

1)一般状况下,做业会经过input的目录产生一个或者多个map任务。

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

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

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

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

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

针对上面的问题23,咱们须要采起两种方式来解决:即减小map数和增长map数;

9.4.2 小文件进行合并

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

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

9.4.3 复杂文件增长Map

input的文件都很大,任务逻辑复杂,map执行很是慢的时候,能够考虑增长Map数,来使得每一个map处理的数据量减小,从而提升任务的执行效率。

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

案例实操:

1.执行查询

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

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

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

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

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

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

9.4.4 合理设置Reduce

1.调整reduce个数方法一

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

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

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

hive.exec.reducers.max=1009

(3)计算reducer数的公式

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

2.调整reduce个数方法二

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

设置每一个job的Reduce个数

set mapreduce.job.reduces = 15;

3.reduce个数并非越多越好

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

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

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

9.5 并行执行

Hive会将一个查询转化成一个或者多个阶段。这样的阶段能够是MapReduce阶段、抽样阶段、合并阶段、limit阶段。或者Hive执行过程当中可能须要的其余阶段。默认状况下,Hive一次只会执行一个阶段。不过,某个特定的job可能包含众多的阶段,而这些阶段可能并不是彻底互相依赖的,也就是说有些阶段是能够并行执行的,这样可能使得整个job的执行时间缩短。不过,若是有更多的阶段能够并行执行,那么job可能就越快完成。

经过设置参数hive.exec.parallel值为true,就能够开启并发执行。不过,在共享集群中,须要注意下,若是job中并行阶段增多,那么集群利用率就会增长。

set hive.exec.parallel=true;              //打开任务并行执行

set hive.exec.parallel.thread.number=16;  //同一个sql容许最大并行度,默认为8。

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

9.6 严格模式

Hive提供了一个严格模式,能够防止用户执行那些可能意不到的很差的影响的查询。

经过设置属性hive.mapred.mode值为默认是非严格模式nonstrict 。开启严格模式须要修改hive.mapred.mode值为strict,开启严格模式能够禁止3种类型的查询。

<property>

    <name>hive.mapred.mode</name>

    <value>strict</value>

    <description>

      The mode in which the Hive operations are being performed.

      In strict mode, some risky queries are not allowed to run. They include:

        Cartesian Product.

        No partition being picked up for a query.

        Comparing bigints and strings.

        Comparing bigints and doubles.

        Orderby without limit.

</description>

</property>

1) 对于分区表,除非where语句中含有分区字段过滤条件来限制范围,不然不容许执行。换句话说,就是用户不容许扫描全部分区。进行这个限制的缘由是,一般分区表都拥有很是大的数据集,并且数据增长迅速。没有进行分区限制的查询可能会消耗使人不可接受的巨大资源来处理这个表。

2) 对于使用了order by语句的查询,要求必须使用limit语句。由于order by为了执行排序过程会将全部的结果数据分发到同一个Reducer中进行处理,强制要求用户增长这个LIMIT语句能够防止Reducer额外执行很长一段时间。

3) 限制笛卡尔积的查询。对关系型数据库很是了解的用户可能指望在执行JOIN查询的时候不使用ON语句而是使用where语句,这样关系数据库的执行优化器就能够高效地将WHERE语句转化成那个ON语句。不幸的是,Hive并不会执行这种优化,所以,若是表足够大,那么这个查询就会出现不可控的状况。

9.7 JVM重用

JVM重用是Hadoop调优参数的内容,其对Hive的性能具备很是大的影响,特别是对于很难避免小文件的场景或task特别多的场景,这类场景大多数执行时间都很短。

Hadoop的默认配置一般是使用派生JVM来执行mapReduce任务的。这时JVM的启动过程可能会形成至关大的开销,尤为是执行的job包含有成百上千task任务的状况。JVM重用可使得JVM实例在同一个job中从新使用N次。N的值能够在Hadoopmapred-site.xml文件中进行配置。一般在10-20之间,具体多少须要根据具体业务场景测试得出。

<property>

  <name>mapreduce.job.jvm.numtasks</name>

  <value>10</value>

  <description>How many tasks to run per jvm. If set to -1, there is

  no limit.

  </description>

</property>

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

9.8 推测执行

在分布式集群环境下,由于程序Bug(包括Hadoop自己的bug),负载不均衡或者资源分布不均等缘由,会形成同一个做业的多个任务之间运行速度不一致,有些任务的运行速度可能明显慢于其余任务(好比一个做业的某个任务进度只有50%,而其余全部任务已经运行完毕),则这些任务会拖慢做业的总体执行进度。为了不这种状况发生,Hadoop采用了推测执行(Speculative Execution)机制,它根据必定的法则推测出拖后腿的任务,并为这样的任务启动一个备份任务,让该任务与原始任务同时处理同一份数据,并最终选用最早成功运行完成任务的计算结果做为最终结果。

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

<property>

  <name>mapreduce.map.speculative</name>

  <value>true</value>

  <description>If true, then multiple instances of some map tasks

               may be executed in parallel.</description>

</property>

 

<property>

  <name>mapreduce.reduce.speculative</name>

  <value>true</value>

  <description>If true, then multiple instances of some reduce tasks

               may be executed in parallel.</description>

</property>

不过hive自己也提供了配置项来控制reduce-side的推测执行:默认是true

  <property>

    <name>hive.mapred.reduce.tasks.speculative.execution</name>

    <value>true</value>

    <description>Whether speculative execution for reducers should be turned on. </description>

  </property>

关于调优这些推测执行变量,还很难给一个具体的建议。若是用户对于运行时的误差很是敏感的话,那么能够将这些功能关闭掉。若是用户由于输入数据量很大而须要执行长时间的map或者Reduce task的话,那么启动推测执行形成的浪费是很是巨大大。

9.9 压缩

详见第8章。

9.10 执行计划(Explain

1.基本语法

EXPLAIN [EXTENDED | DEPENDENCY | AUTHORIZATION] query

2.案例实操

(1)查看下面这条语句的执行计划

hive (default)> explain select * from emp;

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

(2)查看详细执行计划

hive (default)> explain extended select * from emp;

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

10 Hive实战之谷粒影音

10.1 需求描述

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

--统计视频观看数Top10

--统计视频类别热度Top10

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

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

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

--统计每一个类别中视频流量Top10

--统计上传视频最多的用户Top10以及他们上传的视频

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

10.2 项目

10.2.1 数据结构

1.视频表

6-13 视频表

字段

备注

详细描述

video id

视频惟一id

11位字符串

uploader

视频上传者

上传视频的用户名String

age

视频年龄

视频在平台上的整数天

category

视频类别

上传视频指定的视频分类

length

视频长度

整形数字标识的视频长度

views

观看次数

视频被浏览的次数

rate

视频评分

满分5

Ratings

流量

视频的流量,整型数字

conments

评论数

一个视频的整数评论数

related ids

相关视频id

相关视频的id,最多20

2.用户表

6-14 用户表

字段

备注

字段类型

uploader

上传者用户名

string

videos

上传视频数

int

friends

朋友数量

int

10.2.2 ETL原始数据

经过观察原始数据形式,能够发现,视频能够有多个所属分类,每一个所属分类用&符号分割,且分割的两边有空格字符,同时相关视频也是能够有多个元素,多个相关视频又用“\t”进行分割。为了分析数据时方便对存在多个子元素的数据进行操做,咱们首先进行数据重组清洗操做。即:将全部的类别用“&”分割,同时去掉两边空格,多个相关视频id也使用“&”进行分割。

1ETLETLUtil

public class ETLUtil {

public static String oriString2ETLString(String ori){

StringBuilder etlString = new StringBuilder();

String[] splits = ori.split("\t");

if(splits.length < 9) return null;

splits[3] = splits[3].replace(" ", "");

for(int i = 0; i < splits.length; i++){

if(i < 9){

if(i == splits.length - 1){

etlString.append(splits[i]);

}else{

etlString.append(splits[i] + "\t");

}

}else{

if(i == splits.length - 1){

etlString.append(splits[i]);

}else{

etlString.append(splits[i] + "&");

}

}

}

 

return etlString.toString();

}

}

2ETLMapper

import java.io.IOException;

 

import org.apache.commons.lang.StringUtils;

import org.apache.hadoop.io.NullWritable;

import org.apache.hadoop.io.Text;

import org.apache.hadoop.mapreduce.Mapper;

 

import com.atguigu.util.ETLUtil;

 

public class VideoETLMapper extends Mapper<Object, Text, NullWritable, Text>{

Text text = new Text();

 

@Override

protected void map(Object key, Text value, Context context) throws IOException, InterruptedException {

String etlString = ETLUtil.oriString2ETLString(value.toString());

 

if(StringUtils.isBlank(etlString)) return;

 

text.set(etlString);

context.write(NullWritable.get(), text);

}

}

3ETLRunner

import java.io.IOException;

 

import org.apache.hadoop.conf.Configuration;

import org.apache.hadoop.fs.FileSystem;

import org.apache.hadoop.fs.Path;

import org.apache.hadoop.io.NullWritable;

import org.apache.hadoop.io.Text;

import org.apache.hadoop.mapreduce.Job;

import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;

import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import org.apache.hadoop.util.Tool;

import org.apache.hadoop.util.ToolRunner;

 

public class VideoETLRunner implements Tool {

private Configuration conf = null;

 

@Override

public void setConf(Configuration conf) {

this.conf = conf;

}

 

@Override

public Configuration getConf() {

return this.conf;

}

 

@Override

public int run(String[] args) throws Exception {

conf = this.getConf();

conf.set("inpath", args[0]);

conf.set("outpath", args[1]);

 

Job job = Job.getInstance(conf);

 

job.setJarByClass(VideoETLRunner.class);

 

job.setMapperClass(VideoETLMapper.class);

job.setMapOutputKeyClass(NullWritable.class);

job.setMapOutputValueClass(Text.class);

job.setNumReduceTasks(0);

 

this.initJobInputPath(job);

this.initJobOutputPath(job);

 

return job.waitForCompletion(true) ? 0 : 1;

}

 

private void initJobOutputPath(Job job) throws IOException {

Configuration conf = job.getConfiguration();

String outPathString = conf.get("outpath");

 

FileSystem fs = FileSystem.get(conf);

 

Path outPath = new Path(outPathString);

if(fs.exists(outPath)){

fs.delete(outPath, true);

}

 

FileOutputFormat.setOutputPath(job, outPath);

 

}

 

private void initJobInputPath(Job job) throws IOException {

Configuration conf = job.getConfiguration();

String inPathString = conf.get("inpath");

 

FileSystem fs = FileSystem.get(conf);

 

Path inPath = new Path(inPathString);

if(fs.exists(inPath)){

FileInputFormat.addInputPath(job, inPath);

}else{

throw new RuntimeException("HDFS中该文件目录不存在:" + inPathString);

}

}

 

public static void main(String[] args) {

try {

int resultCode = ToolRunner.run(new VideoETLRunner(), args);

if(resultCode == 0){

System.out.println("Success!");

}else{

System.out.println("Fail!");

}

System.exit(resultCode);

} catch (Exception e) {

e.printStackTrace();

System.exit(1);

}

}

}

4.执行ETL

$ bin/yarn jar ~/softwares/jars/gulivideo-0.0.1-SNAPSHOT.jar \

com.atguigu.etl.ETLVideosRunner \

/gulivideo/video/2008/0222 \

/gulivideo/output/video/2008/0222

 

10.3 准备工做

10.3.1 建立表

建立表:gulivideo_ori,gulivideo_user_ori

建立表:gulivideo_orc,gulivideo_user_orc

gulivideo_ori:

create table gulivideo_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 "&"

stored as textfile;

gulivideo_user_ori

create table gulivideo_user_ori(

    uploader string,

    videos int,

    friends int)

row format delimited

fields terminated by "\t"

stored as textfile;

 

而后把原始数据插入到orc表中

gulivideo_orc:

create table gulivideo_orc(

    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 "&"

stored as orc;

gulivideo_user_orc:

create table gulivideo_user_orc(

    uploader string,

    videos int,

    friends int)

row format delimited

fields terminated by "\t"

stored as orc;

10.3.2 导入ETL后的数据

gulivideo_ori:

load data inpath "/gulivideo/output/video/2008/0222" into table gulivideo_ori;

gulivideo_user_ori

load data inpath "/gulivideo/user/2008/0903" into table gulivideo_user_ori;

10.3.3 ORC表插入数据

gulivideo_orc:

insert into table gulivideo_orc select * from gulivideo_ori;

 

gulivideo_user_orc:

insert into table gulivideo_user_orc select * from gulivideo_user_ori;

10.4 业务分析

10.4.1 统计视频观看数Top10

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

最终代码:

select

    videoId,

    uploader,

    age,

    category,

    length,

    views,

    rate,

    ratings,

    comments

from

    gulivideo_orc

order by

    views

desc limit

    10;

10.4.2 统计视频类别热度Top10

思路:

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

2) 咱们须要按照类别group by聚合,而后count组内的videoId个数便可。

3) 由于当前表结构为:一个视频对应一个或多个类别。因此若是要group by类别,须要先将类别进行列转行(展开),而后再进行count便可。

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

最终代码:

select

    category_name as category,

    count(t1.videoId) as hot

from (

    select

        videoId,

        category_name

    from

        gulivideo_orc lateral view explode(category) t_catetory as category_name) t1

group by

    t1.category_name

order by

    hot

desc limit

    10;

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

思路:

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

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

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

最终代码:

select

    category_name as category,

    count(t2.videoId) as hot_with_views

from (

    select

        videoId,

        category_name

    from (

        select

            *

        from

            gulivideo_orc

        order by

            views

        desc limit

            20) t1 lateral view explode(category) t_catetory as category_name) t2

group by

    category_name

order by

    hot_with_views

desc;

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

思路:

1) 查询出观看数最多的前50个视频的全部信息(固然包含了每一个视频对应的关联视频),记为临时表t1

t1:观看数前50的视频

select

    *

from

    gulivideo_orc

order by

    views

desc limit

    50;

2) 将找到的50条视频信息的相关视频relatedId列转行,记为临时表t2

t2:将相关视频的id进行列转行操做

select

    explode(relatedId) as videoId

from

t1;

3) 将相关视频的idgulivideo_orc表进行inner join操做

t5:获得两列数据,一列是category,一列是以前查询出来的相关视频id

 (select

    distinct(t2.videoId),

    t3.category

from

    t2

inner join

    gulivideo_orc t3 on t2.videoId = t3.videoId) t4 lateral view explode(category) t_catetory as category_name;

4) 按照视频类别进行分组,统计每组视频个数,而后排行

最终代码:

select

    category_name as category,

    count(t5.videoId) as hot

from (

    select

        videoId,

        category_name

    from (

        select

            distinct(t2.videoId),

            t3.category

        from (

            select

                explode(relatedId) as videoId

            from (

                select

                    *

                from

                    gulivideo_orc

                order by

                    views

                desc limit

                    50) t1) t2

        inner join

            gulivideo_orc t3 on t2.videoId = t3.videoId) t4 lateral view explode(category) t_catetory as category_name) t5

group by

    category_name

order by

    hot

desc;

 

10.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;

向类别表中插入数据:

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;

 

统计Music类别的Top10(也能够统计其余)

select

    videoId,

    views

from

    gulivideo_category

where

    categoryId = "Music"

order by

    views

desc limit

    10;

10.4.6 统计每一个类别中视频流量Top10,以Music为例

思路:

1) 建立视频类别展开表(categoryId列转行后的表)

2) 按照ratings排序便可

最终代码:

select

    videoId,

    views,

    ratings

from

    gulivideo_category

where

    categoryId = "Music"

order by

    ratings

desc limit

    10;

 

10.4.7 统计上传视频最多的用户Top10以及他们上传的观看次数在前20的视频

思路:

1) 先找到上传视频最多的10个用户的用户信息

select

    *

from

    gulivideo_user_orc

order by

    videos

desc limit

    10;

 

2) 经过uploader字段与gulivideo_orc表进行join,获得的信息按照views观看次数进行排序便可。

最终代码:

select

    t2.videoId,

    t2.views,

    t2.ratings,

    t1.videos,

    t1.friends

from (

    select

        *

    from

        gulivideo_user_orc

    order by

        videos desc

    limit

        10) t1

join

    gulivideo_orc t2

on

    t1.uploader = t2.uploader

order by

    views desc

limit

    20;

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

思路:

1) 先获得categoryId展开的表数据

2) 子查询按照categoryId进行分区,而后分区内排序,并生成递增数字,该递增数字这一列起名为rank

3) 经过子查询产生的临时表,查询rank值小于等于10的数据行便可。

最终代码:

select

    t1.*

from (

    select

        videoId,

        categoryId,

        views,

        row_number() over(partition by categoryId order by views desc) rank from gulivideo_category) t1

where

    rank <= 10;

11 常见错误及解决方案

1SecureCRT 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

3hive默认的输入格式处理是CombineHiveInputFormat,会对小文件进行合并。

hive (default)> set hive.input.format;

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

能够采用HiveInputFormat就会根据分区数输出相应的文件。

hive (default)> set hive.input.format=org.apache.hadoop.hive.ql.io.HiveInputFormat;

4)不能执行mapreduce程序

多是hadoopyarn没开启。

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 1222 16:41 hadoop102.pid 文件,并修改权限为 777

7JVM堆内存溢出

描述: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>

相关文章
相关标签/搜索