Hive 数据类型
基本数据类型
常用的为标红的。
对于 Hive 的 String 类型相当于数据库的 varchar 类型,该类型是一个可变的字符串,不过它不能声明其中最多能存储多少个字符,理论上它可以存储 2GB 的字符数。
集合数据类型
Hive 有三种复杂数据类型 ARRAY、MAP 和 STRUCT。ARRAY 和 MAP 与 Java 中的Array 和 Map 类似,而 STRUCT 与 C 语言中的 Struct 类似,它封装了一个命名字段集合,复杂数据类型允许任意层次的嵌套。
使用案例
假设某表有如下一行,我们用 JSON 格式来表示其数据结构。在 Hive 下访问的格式为
{
"name": "songsong",
"friends": ["bingbing" , "lili"] , //列表 Array,
"children": //键值 Map,
{
"xiao song": 18 ,
"xiaoxiao song": 19
}
"address": //结构 Struct,
{
"street": "hui long guan" ,
"city": "beijing"
}
}
基于上述数据结构,在 Hive 里创建对应的表,并导入数据。创建本地测试文件 test.txt
songsong,bingbing_lili,xiao song:18_xiaoxiao song:19,huilongguan_beijing
yangyang,caicai_susu,xiao yang:18_xiaoxiao yang:19,chaoyang_beijing
注意:MAP、STRUCT 和 ARRAY 里的元素间关系都可以用同一个字符表示,这里用“_”。
Hive 上创建测试表 test
create table test(name string, friends array<string>, children map<string, int>,
address struct<street:string, city:string>) row format delimited fields terminated by ','
collection items terminated by '_' map keys terminated by ':' lines terminated by '\n';
字段解释
row format delimited fields terminated by ',' -- 列分隔符
collection items terminated by '_' -- MAP、STRUCT 和 ARRAY 的分隔符(数据分割符号)
map keys terminated by ':' -- MAP 中的 key 与 value 的分隔符
lines terminated by '\n'; -- 行分隔符(可省略这句话,默认也是\n)
导入文本数据到测试表
load data local inpath "/application/data/test.txt" into table test;
访问三种集合列里的数据,以下分别是 ARRAY,MAP,STRUCT 的访问方式
hive (default)> select friends[1],children['xiaosong'],address.city from test where name="songsong";
OK
_c0 _c1 city
lili 18 beijing
Time taken: 0.076 seconds, Fetched: 1 row(s)
类型转化
Hive 的原子数据类型是可以进行隐式转换的,类似于 Java 的类型转换,例如某表达式使用 INT 类型,TINYINT 会自动转换为 INT 类型,但是 Hive 不会进行反向转化,例如,某表达式使用 TINYINT 类型,INT 不会自动转换为 TINYINT 类型,它会返回错误,除非使用 CAST 操作。
- 隐式类型转换规则如下
- 任何整数类型都可以隐式地转换为一个范围更广的类型,如 TINYINT 可以转换成 INT,INT 可以转换成 BIGINT。
- 所有整数类型、FLOAT 和 STRING 类型都可以隐式地转换成 DOUBLE。
- TINYINT、SMALLINT、INT 都可以转换为 FLOAT。
- BOOLEAN 类型不可以转换为任何其它的类型。
- 可以使用 CAST 操作显示进行数据类型转换
例如 CAST(‘1’ AS INT)将把字符串’1’ 转换成整数 1;如果强制类型转换失败,如执行CAST(‘X’ AS INT),表达式返回空值 NULL。
DDL 数据定义
创建数据库
- 创建一个数据库,数据库在 HDFS 上的默认存储路径是/user/hive/warehouse/*.db。
hive (default)> create database db_hive;
- 避免要创建的数据库已经存在错误,增加 if not exists 判断。(标准写法)
create database if not exists db_hive;
- 创建一个数据库,指定数据库在 HDFS 上存放的位置
hive (default)> create database db_hive2 location '/user/db_hive2.db';
查询数据库
- 显示数据库 ```shell show databases;
过滤显示查询的数据库
show databases like ‘db_hive*’;
- 查看数据库详情
```shell
desc database db_hive;
# 显示数据库详细信息,extended
desc database extended db_hive;
- 切换当前数据库
use db_hive;
修改数据库
用户可以使用 ALTER DATABASE 命令为某个数据库的 DBPROPERTIES 设置键-值对 属性值,来描述这个数据库的属性信息。数据库的其他元数据信息都是不可更改的,包括数据库名和数据库所在的目录位置。
alter database hive set dbproperties('createtime'='20170830');
删除数据库
删除空数据库
drop database db_hive2;
如果删除的数据库不存在,最好采用 if exists 判断数据库是否存在
drop database if exists db_hive2;
如果数据库不为空,可以采用 cascade 命令,强制删除
drop database db_hive cascade;
创建表
建表语法
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]
字段解释说明
1.CREATE TABLE 创建一个指定名字的表。如果相同名字的表已经存在,则抛出异常;
用户可以用 IF NOT EXISTS 选项来忽略这个异常。
2.EXTERNAL 关键字可以让用户创建一个外部表,在建表的同时指定一个指向实际数据的路径(LOCATION),
Hive 创建内部表时,会将数据移动到数据仓库指向的路径;若创建外部表,仅记录数据所在的路径,
不对数据的位置做任何改变。在删除表的时候,内部表的元数据和数据会被一起删除,而外部表只删除元数据,
不删除数据。
3.COMMENT:为表和列添加注释。
4.PARTITIONED BY 创建分区表(分文件夹)
5.CLUSTERED BY 创建分桶表(分文件)
6.SORTED BY 不常用
7.ROW FORMAT DELIMITED [FIELDS TERMINATED BY char] [COLLECTION ITEMS TERMINATED BY char]
[MAP KEYS TERMINATED BY char] [LINES TERMINATED BY char] | SERDE serde_name
[WITH SERDEPROPERTIES (property_name=property_value, property_name=property_value, ...)]
用户在建表的时候可以自定义 SerDe 或者使用自带的 SerDe。如果没有指定 ROW FORMAT 或者
ROW FORMAT DELIMITED,将会使用自带的 SerDe。在建表的时候,用户还需要为表指定列,
用户在指定表的列的同时也会指定自定义的 SerDe,Hive 通过 SerDe确定表的具体的列的数据。
SerDe 是 Serialize/Deserilize 的简称,目的是用于序列化和反序列化。
8.STORED AS 指定存储文件类型
常用的存储文件类型:SEQUENCEFILE(二进制序列文件)、TEXTFILE(文本)、RCFILE(列式存储格式文件)
如果文件数据是纯文本,可以使用 STORED AS TEXTFILE。如果数据需要压缩,使用 STORED AS SEQUENCEFILE。
9.LOCATION :指定表在 HDFS 上的存储位置。
10.LIKE 允许用户复制现有的表结构,但是不复制数据。
管理表
无EXTERNAL修饰,默认创建的表都是所谓的管理表,有时也被称为内部表。因为这种表,Hive 会(或多或少地)控制着数据的生命周期。Hive 默认情况下会将这些表的数据存储在由配置项 hive.metastore.warehouse.dir(例如,/user/hive/warehouse)所定义的目录的子目录下。当我们删除一个管理表时,Hive 也会删除这个表中数据。管理表不适合和其他工具共享数据。
外部表
有EXTERNAL修饰,因为表是外部表,表数据保存在HDFS上,该位置由用户指定,所以 Hive 并非认为其完全拥有这份数据。删除该表并不会删除掉这份数据,不过描述表的元数据信息会被删除掉。
- 管理表和外部表的使用场景
每天将收集到的网站日志定期流入 HDFS 文本文件。在外部表(原始日志表)的基础上做大量的统计分析,用到的中间表、结果表使用内部表存储,数据通过 SELECT+INSERT 进入内部表。
- 希望做数据备份并且不经常改变的数据,存放在外部表可以减少失误操作
- 数据清洗转换后的中间结果,可以存放在内部表,因为Hive对内部表支持的功能比较全面,方便管理
- 处理完成的数据由于需要共享,可以存储在外部表,这样能够防止失误操作,增加数据的安全性
管理表与外部表的互相转换
查询表的类型
desc formatted student2;
修改内部表 student2 为外部表
alter table student2 set tblproperties('EXTERNAL'='TRUE');
修改外部表 student2 为内部表
alter table student2 set tblproperties('EXTERNAL'='FALSE');
注意:(‘EXTERNAL’=’TRUE’)和(‘EXTERNAL’=’FALSE’)为固定写法,区分大小写!
分区表
分区表实际上就是对应一个 HDFS 文件系统上的独立的文件夹,该文件夹下是该分区所有的数据文件。Hive 中的分区就是分目录,把一个大的数据集根据业务需要分割成小的数据集。在查询时通过 WHERE 子句中的表达式选择查询所需要的指定的分区,这样的查询效率会提高很多。分区表是:PARTITIONS
分区表基本操作
引入分区表(需要根据日期对日志进行管理)
/user/hive/warehouse/log_partition/20170702/20170702.log
/user/hive/warehouse/log_partition/20170703/20170703.log
/user/hive/warehouse/log_partition/20170704/20170704.log
创建分区表语法
create table dept_partition(
deptno int, dname string, loc string
)
partitioned by (month string)
row format delimited fields terminated by '\t';
- 加载数据到分区表中
load data local inpath '/application/data/dept.txt' into table default.dept_partition partition(month='202003');
load data local inpath '/application/data/dept.txt' into table default.dept_partition partition(month='202002');
load data local inpath '/application/data/dept.txt' into table default.dept_partition partition(month='202001’);
查询分区表中数据
select * from dept_partition where month='202001';
多分区联合查询
select * from dept_partition where month='202001'
union select * from dept_partition where month='202002'
union select * from dept_partition where month='202003';
增加分区
创建单个分区
alter table dept_partition add partition(month='202004');
同时创建多个分区
alter table dept_partition add partition(month='202004') partition(month='202005');
同时创建多个分区
alter table dept_partition add partition(month='202001') partition(month='202002');
删除分区
删除单个分区
alter table dept_partition drop partition (month='202001');
同时删除多个分区
alter table dept_partition drop partition (month='202001'), partition (month='202002');
查看分区表有多少分区
show partitions dept_partition;
查看分区表结构
desc formatted dept_partition;
分区表注意事项
创建二级分区表
create table dept_partition2( deptno int, dname string, loc string ) partitioned by (month string, day string) row format delimited fields terminated by '\t';
正常的加载数据
加载数据到二级分区表中
load data local inpath '/opt/module/datas/dept.txt' into table
default.dept_partition2 partition(month='202001', day='13');
查询分区数据
select * from dept_partition2 where month='202001' and day='13';
- 把数据直接上传到分区目录上,让分区表和数据产生关联的三种方式
方式一:上传数据后修复
上传数据
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;
查询数据(查询不到刚上传的数据)
select * from dept_partition2 where month='201709' and day='12';
执行修复命令
msck repair table dept_partition2;
再次查询数据
select * from dept_partition2 where month='201709' and day='12';
方式二:上传数据后添加分区
上传数据
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;
执行添加分区
alter table dept_partition2 add partition(month='201709',day='11');
查询数据
select * from dept_partition2 where month='201709' and day='11';
方式三:创建文件夹后 load 数据到分区
创建目录
dfs -mkdir -p /user/hive/warehouse/dept_partition2/month=201709/day=10;
上传数据
load data local inpath '/opt/module/datas/dept.txt' into table dept_partition2 partition(month='201709',day='10');
查询数据
select * from dept_partition2 where month='201709' and day='10';
修改表
重命名表
语法:ALTER TABLE table_name RENAME TO new_table_name 举例:ALTER TABLE dept_partition2 rename to dept_partition3;
增加/修改/替换列信息 ```shell 更新列语法: 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 则是表示替换表中所有字段。
添加列: alter table dept_partition add columns(deptdesc string);
更新列: alter table dept_partition change column deptdesc desc int;
替换列: alter table dept_partition replace columns(deptno string, dname string, loc string);
<a name="DL8Xk"></a>
### 删除表
```shell
drop table dept_partition;
DML 数据操作
数据导入
- 向表中装载数据(Load) ```shell 语法 load data [local] inpath ‘/opt/module/datas/student.txt’ [overwrite] | into table student [partition (partcol1=val1,…)]; 1.load data:表示加载数据 2.local:表示从本地加载数据到 hive 表;否则从 HDFS 加载数据到 hive 表 3.inpath:表示加载数据的路径 4.overwrite:表示覆盖表中已有数据,否则表示追加 5.into table:表示加载到哪张表 6.student:表示具体的表 7.partition:表示上传到指定分区
案例操作 创建一张表 create table student(id string, name string) row format delimited fields terminated by ‘\t’; 加载本地文件到 hive load data local inpath ‘/opt/module/datas/student.txt’ into table default.student;
加载 HDFS 文件到 hive 中 1.上传文件到 HDFS dfs -put /opt/module/datas/student.txt /user/atguigu/hive; 2.加载 HDFS 上的数据 load data inpath ‘/user/atguigu/hive/student.txt’ into table default.student;
加载数据覆盖表中已有的数据 1.上传文件到 HDFS dfs -put /opt/module/datas/student.txt /user/atguigu/hive; 2.加载数据覆盖表中已有的数据 load data inpath ‘/user/atguigu/hive/student.txt’ overwrite into table default.student;
<a name="obHZm"></a>
#### 通过查询语句向表中插入数据(Insert)
- 创建一张分区表
```shell
create table student(id int, name string) partitioned by (month string) row format delimited fields terminated by '\t';
- 基本插入数据
insert into table student partition(month='202001') values(1,'wangwu');
- 基本模式插入(根据单张表查询结果)
insert overwrite table student partition(month='202001') select id, name from student where month='201709';
- 多插入模式(根据多张表查询结果)
from student insert overwrite table student partition(month='201707')
select id, name where month='202001' insert overwrite table student
partition(month='201706') select id, name where month='201709';
查询语句中创建表并加载数据(As Select)
根据查询结果创建表(查询的结果会添加到新创建的表中)
create table if not exists student3 as select id, name from student;
创建表时通过 Location 指定加载数据路径
创建表,并指定在 hdfs 上的位置
create table if not exists student5( id int, name string ) row format delimited fields terminated by '\t' location '/user/hive/warehouse/student5';
上传数据到 hdfs 上
hive (default)> dfs -put /opt/module/datas/student.txt /user/hive/warehouse/student5;
Import 数据到指定 Hive 表中
注意:先用 export 导出后,再将数据导入。
import table student2 partition(month='201709') from '/user/hive/warehouse/export/student';
数据导出
Insert 导出
将查询的结果导出到本地
insert overwrite local directory '/opt/module/datas/export/student' select * from student;
将查询的结果格式化导出到本地
insert overwrite local directory '/opt/module/datas/export/student1'
ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t' select * from student;
- 将查询的结果导出到 HDFS 上(没有 local)
insert overwrite directory '/user/atguigu/student2' ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t' select * from student;
Hadoop 命令导出到本地
dfs -get /user/hive/warehouse/student/month=201709/000000_0 /opt/module/datas/export/student3.txt;
Hive Shell 命令导出
基本语法:(hive -f/-e 执行语句或者脚本 > file)
bin/hive -e 'select * from default.student;' > /opt/module/datas/export/student4.txt;
Export 导出到 HDFS 上
export table default.student to '/user/hive/warehouse/export/student';
清除表中数据(Truncate)
注意:Truncate 只能删除管理表,不能删除外部表中数据
truncate table student;
数据查询
查询语句语法:
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]
基本查询(Select…From)
全表和特定列查询
全表查询
select * from emp;
选择特定列查询
select empno, ename from emp;
注意:
1.SQL 语言大小写不敏感。
2.SQL 可以写在一行或者多行
3.关键字不能被缩写也不能分行
4.各子句一般要分行写。
5.使用缩进提高语句的可读性。
列别名
1.重命名一个列
2.便于计算
3.紧跟列名,也可以在列名和别名之间加入关键字‘AS’
查询名称和部门
select ename AS name, deptno dn from emp;
算术运算符
查询出所有员工的薪水后加 1 显示。
select sal +1 from emp;
常用函数
1.求总行数(count)
select count(*) cnt from emp;
2.求工资的最大值(max)
select max(sal) max_sal from emp;
3.求工资的最小值(min)
select min(sal) min_sal from emp;
4.求工资的总和(sum)
select sum(sal) sum_sal from emp;
5.求工资的平均值(avg)
select avg(sal) avg_sal from emp;
Limit 语句
典型的查询会返回多行数据。LIMIT 子句用于限制返回的行数。
select * from emp limit 5;
Where 语句
1.使用 WHERE 子句,将不满足条件的行过滤掉
2.WHERE 子句紧随 FROM 子句
查询出薪水大于 1000 的所有员工
select * from emp where sal >1000;
比较运算符(Between/In/ Is Null)
查询出薪水等于 5000 的所有员工
select * from emp where sal =5000;
查询工资在 500 到 1000 的员工信息
select * from emp where sal between 500 and 1000;
查询 comm 为空的所有员工信息
select * from emp where comm is null;
查询工资是 1500 或 5000 的员工信息
select * from emp where sal IN (1500, 5000);
Like 和 RLike
1.使用 LIKE 运算选择类似的值
2.选择条件可以包含字符或数字:
% 代表零个或多个字符(任意个字符)。
_ 代表一个字符。
3.RLIKE 子句是 Hive 中这个功能的一个扩展,其可以通过 Java 的正则表达式这个更强大的语言来指定匹配条件。
查找以 2 开头薪水的员工信息
select * from emp where sal LIKE '2%';
查找第二个数值为 2 的薪水的员工信息
select * from emp where sal LIKE '_2%';
查找薪水中含有 2 的员工信息
select * from emp where sal RLIKE '[2]';
逻辑运算符(And/Or/Not)
查询薪水大于 1000,部门是 30
select * from emp where sal>1000 and deptno=30;
查询薪水大于 1000,或者部门是 30
select * from emp where sal>1000 or deptno=30;
查询除了 20 部门和 30 部门以外的员工信息
select * from emp where deptno not IN(30, 20);
Group By 语句
GROUP BY 语句通常会和聚合函数一起使用,按照一个或者多个列队结果进行分组, 然后对每个组执行聚合操作。
计算 emp 表每个部门的平均工资
select t.deptno, avg(t.sal) avg_sal from emp t group by t.deptno;
计算 emp 每个部门中每个岗位的最高薪水
select t.deptno, t.job, max(t.sal) max_sal from emp t group by t.deptno, t.job;
Having 语句
having 与 where 不同点
1.where 针对表中的列发挥作用,查询数据;having 针对查询结果中的列发挥作用,筛选数据。
2.where 后面不能写聚合函数,而 having 后面可以使用聚合函数。
3.having 只用于 group by 分组统计语句。
求每个部门的平均工资
select deptno, avg(sal) from emp group by deptno;
求每个部门的平均薪水大于 2000 的部门
select deptno, avg(sal) avg_sal from emp group by deptno having avg_sal > 2000;
Join 语句
等值 Join
Hive 支持通常的 SQL JOIN 语句,但是只支持等值连接,不支持非等值连接。
根据员工表和部门表中的部门编号相等,查询员工编号、员工名称和部门名称;
select e.empno, e.ename, d.deptno, d.dname from emp e join dept d on e.deptno = d.deptno;
内连接
内连接:只有进行连接的两个表中都存在与连接条件相匹配的数据才会被保留下来。
select e.empno, e.ename, d.deptno from emp e join dept d on e.deptno = d.deptno;
左外连接
左外连接:JOIN 操作符左边表中符合 WHERE 子句的所有记录将会被返回。
select e.empno, e.ename, d.deptno from emp e left join dept d on e.deptno = d.deptno;
右外连接
右外连接:JOIN 操作符右边表中符合 WHERE 子句的所有记录将会被返回。
select e.empno, e.ename, d.deptno from emp e right join dept d on e.deptno = d.deptno;
满外连接
满外连接:将会返回所有表中符合 WHERE 语句条件的所有记录。如果任一表的指定字段没有符合条件的值的话,那么就使用 NULL 值替代。
select e.empno, e.ename, d.deptno from emp e full join dept d on e.deptno = d.deptno;
多表连接
注意:连接 n 个表,至少需要 n-1 个连接条件。例如:连接三个表,至少需要两个连接条件。
SELECT e.ename, d.deptno, l.loc_name FROM emp e JOIN dept d ON d.deptno = e.deptno
JOIN location l ON d.loc = l.loc;
大多数情况下,Hive 会对每对 JOIN 连接对象启动一个 MapReduce 任务。
本例中会首先启动一个 MapReduce job 对表 e 和表 d 进行连接操作,
然后会再启动一个 MapReduce job将第一个 MapReduce job 的输出和表 l;进行连接操作
注意:为什么不是表 d 和表 l 先进行连接操作呢?这是因为 Hive 总是按照从左到右的
顺序执行的。
笛卡尔积
笛卡尔集会在下面条件下产生
1.省略连接条件
2.连接条件无效
3.所有表中的所有行互相连接
select empno, dname from emp, dept;
连接谓词中不支持 or
> select
> e.empno,
> e.ename,
> d.deptno
> from
> emp e
> join
> dept d
> on
> e.deptno=d.deptno or e.ename=d.dname;
FAILED: SemanticException [Error 10019]: Line 10:3 OR not
supported in JOIN currently 'dname'
排序
全局排序(Order By)
Order By:全局排序,一个 Reducer
1.使用 ORDER BY 子句排序
ASC(ascend): 升序(默认)
DESC(descend): 降序
2.ORDER BY 子句在 SELECT 语句的结尾
查询员工信息按工资升序排列
select * from emp order by sal;
查询员工信息按工资降序排列
select * from emp order by sal desc;
按照别名排序
按照员工薪水的 2 倍排序
select ename, sal*2 twosal from emp order by twosal;
多个列排序
按照部门和工资升序排序
select ename, deptno, sal from emp order by deptno, sal ;
每个 MapReduce 内部排序(Sort By)
Sort By:每个 Reducer 内部进行排序,对全局结果集来说不是排序。
1.设置 reduce 个数
set mapreduce.job.reduces=3;
2.查看设置 reduce 个数
set mapreduce.job.reduces;
3.根据部门编号降序查看员工信息
select * from emp sort by empno desc;
4.将查询结果导入到文件中(按照部门编号降序排序)
insert overwrite local directory '/opt/module/datas/sortby-result' select * from emp sort by deptno desc;
分区排序(Distribute By)
Distribute By:类似 MR 中 partition,进行分区,结合 sort by 使用。
注意,Hive 要求 DISTRIBUTE BY 语句要写在 SORT BY 语句之前。
对于 distribute by 进行测试,一定要分配多 reduce 进行处理,否则无法看到 distribute by
的效果。
先按照部门编号分区,再按照员工编号降序排序。
set mapreduce.job.reduces=3;
insert overwrite local directory '/opt/module/datas/distribute-result' select * from emp
distribute by deptno sort by empno desc;
Cluster By
当 distribute by 和 sorts by 字段相同时,可以使用 cluster by 方式。
cluster by 除了具有 distribute by 的功能外还兼具 sort by 的功能。但是排序只能是升序排序,不能指定排序规则为 ASC 或者 DESC。
以下两种写法等价
select * from emp cluster by deptno;
select * from emp distribute by deptno sort by deptno;
注意:按照部门编号分区,不一定就是固定死的数值,可以是 20 号和 30 号部门分到一个分区里面去。
分桶及抽样查询
分桶表数据存储
分区针对的是数据的存储路径;分桶针对的是数据文件。
分区提供一个隔离数据和优化查询的便利方式。不过,并非所有的数据集都可形成合理的分区,特别是之前所提到过的要确定合适的划分大小这个疑虑。
分桶是将数据集分解成更容易管理的若干部分的另一个技术。
- 先创建分桶表,通过直接导入数据文件的方式
create table stu_buck(id int, name string) clustered by(id) into 4 buckets
row format delimited fields terminated by '\t';
导入数据到分桶表中
load data local inpath '/opt/module/datas/student.txt' into table stu_buck;
- 创建分桶表时,数据通过子查询的方式导入
先建一个普通的 stu 表
create table stu(id int, name string) row format delimited fields terminated by '\t';
向普通的 stu 表中导入数据
load data local inpath '/opt/module/datas/student.txt' into table stu;
清空 stu_buck 表中数据
truncate table stu_buck;
select * from stu_buck;
导入数据到分桶表,通过子查询的方式
insert into table stu_buck select id, name from stu;
设置一个属性
set hive.enforce.bucketing=true;
set mapreduce.job.reduces=-1;
insert into table stu_buck select id, name from stu;
分桶抽样查询
对于非常大的数据集,有时用户需要使用的是一个具有代表性的查询结果而不是全部结果。Hive 可以通过对表进行抽样来满足这个需求。
查询表 stu_buck 中的数据。
select * from stu_buck tablesample(bucket 1 out of 4 on id);
注:tablesample 是抽样语句,语法:TABLESAMPLE(BUCKET x OUT OF y) 。
y 必须是 table 总 bucket 数的倍数或者因子。hive 根据 y 的大小,决定抽样的比例。例
如,table 总共分了 4 份,当 y=2 时,抽取(4/2=)2 个 bucket 的数据,当 y=8 时,抽取(4/8=)1/2
个 bucket 的数据。
x 表示从哪个 bucket 开始抽取,如果需要取多个分区,以后的分区号为当前分区号加上y。
例如,table 总 bucket 数为 4,tablesample(bucket 1 out of 2),表示总共抽取(4/2=)2 个
bucket 的数据,抽取第 1(x)个和第 3(x+y)个 bucket 的数据。
注意:x 的值必须小于等于 y 的值,否则
FAILED: SemanticException [Error 10061]: Numerator should not be bigger than
denominator in sample clause for table stu_buck
其他常用查询函数
空字段赋值
1.函数说明
NVL:给值为 NULL 的数据赋值,它的格式是 NVL( string1, replace_with)。它的功能是如果
string1 为 NULL,则 NVL 函数返回 replace_with 的值,否则返回 string1 的值,如果两个参
数都为 NULL ,则返回 NULL。
2.数据准备:采用员工表
3.查询:如果员工的 comm 为 NULL,则用-1 代替
select nvl(comm,-1) from emp;
4.如果员工的 comm 为 NULL,则用领导 id 代替
select nvl(comm,mgr) from emp;
时间类
1.date_format:格式化时间
select date_format('2019-06-29','yyyy-MM-dd');
2.date_add:时间跟天数相加
select date_add('2019-06-29',5);
select date_add('2019-06-29',-5);
3.date_sub:时间跟天数相减
select date_sub('2019-06-29',5);
select date_sub('2019-06-29 12:12:12',5);
select date_sub('2019-06-29',-5);
4.datediff:两个时间相减
select datediff('2019-06-29','2019-06-24');
select datediff('2019-06-24','2019-06-29');
select datediff('2019-06-24 12:12:12','2019-06-29');
select datediff('2019-06-24 12:12:12','2019-06-29 13:13:13');
CASE WHEN
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;
行转列
CONCAT(string A/col, string B/col…):返回输入字符串连接后的结果,支持任意个输入字符串;
CONCAT_WS(separator, str1, str2,…):它是一个特殊形式的 CONCAT()。第一个参数剩余参数间的分隔符。分隔符可以是与剩余参数一样的字符串。如果分隔符是 NULL,返回值也将为 NULL。这个函数会跳过分隔符参数后的任何 NULL 和空字符串。分隔符将被加到被连接的字符串之间;
COLLECT_SET(col):函数只接受基本数据类型,它的主要作用是将某字段的值进行去重汇总,产生 array 类型字段。
把星座和血型一样的人归类到一起。结果如下:
射手座,A 大海|凤姐
白羊座,A 孙悟空|猪八戒
白羊座,B 宋宋
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;
列转行
EXPLODE(col):将 hive 一列中复杂的 array 或者 map 结构拆分成多行。
LATERAL VIEW
用法:LATERAL VIEW udtf(expression) tableAlias AS columnAlias
解释:用于和 split, explode 等 UDTF 一起使用,它能够将一列数据拆成多行数据,在此基础上可以对拆分后的数据进行聚合。
将电影分类中的数组数据展开。结果如下:
《疑犯追踪》 悬疑
《疑犯追踪》 动作
《疑犯追踪》 科幻
《疑犯追踪》 剧情
《Lie to me》 悬疑
《Lie to me》 警匪
《Lie to me》 动作
《Lie to me》 心理
《Lie to me》 剧情
《战狼 2》 战争
《战狼 2》 动作
《战狼 2》 灾难
select
movie,
category_name
from
movie_info lateral view explode(category) table_tmp as
category_name;
Rank
RANK() 排序相同时会重复,总数不会变
DENSE_RANK() 排序相同时会重复,总数会减少
ROW_NUMBER() 会根据顺序计算
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