Hive分区表

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

创建分区表语法

Hive分区表

Hive分区表

查询分区表中数据

Hive分区表

增加分区

Hive分区表

删除分区

Hive分区表

同时删除多个分区

Hive分区表

查看分区表有多少分区

Hive分区表

查看分区表结构

Hive分区表

创建二级分区表

Hive分区表

加载数据到二级分区表中

Hive分区表

查询分区数据

Hive分区表

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

方式一:上传数据后修复

上传数据

dfs -mkdir -p /user/hive/warehouse/dept_partition2/month=201709/day=12;
dfs -put /home/hadoop/data/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';

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

上传数据

dfs -mkdir -p /user/hive/warehouse/dept_partition2/month=201709/day=11;

dfs -put /home/hadoop/data/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 '/home/hadoop/data/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;

增加、修改和删除表分区

添加列

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

删除表

drop table dept_partition;