创建分区表
create external table user_article( uid int, aid int)
partitioned by (`date` string)
row format delimited fields terminated by ',';
解释:
- uid:用户的id
- aid:该用户查看文章的id
- date:日期,分区字段
注意: 分区字段 不能是 表中的字段,可以将 分区字段 看作表的 伪字段
查看是否动态分区表
set hive.exec.dynamic.partition
执行结果如下:
hive.exec.dynamic.partition=true
说明是 动态分区表
提示: 默认是 动态分区表
设置 全局 静态分区
set hive.exec.dynamic.partition=false;
特点
不能根据数据 生成分区
静态分区,不能根据插入的数据,动态的生成分区,执行会报错
INSERT into table user_article(uid,aid,`date`) values (103,1634,'20200108');
必须指定分区
静态分区模式下,插入数据,必须手动指定要插入到哪个分区中
insert into table user_article partition(`date`='20200107') (uid,aid) values ('200','2001')
导入数据
数据准备
假设每个 .log 文件有上百万条记录
mkdir /program/datas
cd /program/datas
编辑 user_article_20200101.log
vim user_article_20200101.log
内容
10,1000
20,1001
编辑 user_article_20200102.log
vim user_article_20200102.log
内容
30,1002
40,1003
编辑 user_article_20200103.log
vim user_article_20200103.log
内容
50,1004
60,1005
导入数据
注意: 分区表加载数据时,必须指定分区
load data local inpath
'/program/datas/user_article_20200101.log' into table user_article partition(`date`='20200101');
load data local inpath
'/program/datas/user_article_20200102.log' into table user_article partition(`date`='20200102');
load data local inpath
'/program/datas/user_article_20200103.log' into table user_article partition(`date`='20200103');
hdfs web管理页面
查询
普通查询
select * from user_article
显示该表中 所有数据(不考虑是哪个分区)
单分区查询
select * from user_article where `date`='20200101';
注意: 加上分区字段,就 不是全表扫描,查询速度快
多分区联合查询
方式一:
select * from user_article where `date` in ('20200101','20200102','20200103');
执行结果:
uid|aid |date |
---|----|--------|
10|1000|20200101|
20|1001|20200101|
30|1002|20200102|
40|1003|20200102|
50|1004|20200103|
60|1005|20200103|
方式二:
select * from user_article where `date`='20200101' or `date`='20200102' or `date`='20200103';
方式三:(不推荐)
执行特别慢,一个结果集拼另一个结果集
select * from user_article where `date`='20200101'
union
select * from user_article where `date`='20200102'
union
select * from user_article where `date`='20200103';
转成 MR 程序运行,速度慢
插入数据
insert into table user_article partition(`date`='20200101') (uid,aid) values ('200','2001')
当所有字段都有数据时,可省略如下:
insert into table user_article partition(`date`='20200101') values ('200','2001')
注意: 可以向不存在的分区插入数据
增加分区
创建单个分区
alter table user_article add partition(`date`='20200104');
查看 hdfs web管理页面
同时创建多个分区
alter table user_article add partition(`date`='20200105') partition(`date`='20200106');
删除分区
删除单个分区
alter table user_article drop partition (`date`='20200106');
查看 hdfs web管理页面
date=20200106 文件夹已经没有了
同时删除多个分区
alter table user_article drop partition (`date`='20200104'), partition(`date`='20200105');
查看表的分区
show partitions user_article;
显示结果:
partition |
-------------|
date=20200101|
date=20200102|
date=20200103|


