Hive中分区表及陷阱

分区表

分区表实际就对应hdfs文件系统上的的独立的文件夹,该文件是夹下是该分区所有数据文件。
分区可以理解为分类,通过分类把不同类型的数据放到不同的目录下。
分类的标准就是分区字段,可以一个,也可以多个。
分区表的意义在于优化查询。查询时尽量利用分区字段。如果不使用分区字段,就会全部扫描。

在查询是通过where子句查询来指定所需的分区。

样例

create external table if not exists emp_partition(
empno int,
ename string,
job string,
mgr int,
hiredate string,
sal double,
comm double,
deptno int
)
partitioned by (month string)
row format delimited fields terminated by ‘\t’

操作步骤

创建分区表

create external table if not exists emp_partition(
empno int,
ename string,
job string,
mgr int,
hiredate string,
sal double,
comm double,
deptno int
)

partitioned by (month string)
row format delimited fields terminated by ‘\t’

《Hive中分区表及陷阱》

还可以添加二级分区
partitioned by (month string,day string):相当于创建2个文件夹,在month下创建了day文件夹
day文件下就是具体的文件。

加载数据到指定分区

load data local inpath ‘/opt/datas/emp.txt’ into table default.emp_partition partition (month=’201803′);

《Hive中分区表及陷阱》

《Hive中分区表及陷阱》

load data local inpath ‘/opt/datas/emp.txt’ into table **default.emp_partition partition (month=’201804′);

《Hive中分区表及陷阱》

《Hive中分区表及陷阱》

《Hive中分区表及陷阱》

分区其实就是文件夹名称。分区表就是文件夹。分区相当于对文件坐了分类,根据分类拆分不同的文件。

分区中的数据查询

查询201803分区数据

命令:select * from emp_partition where month=’201803′ ;

《Hive中分区表及陷阱》

查询201803分区数据

命令:select * from emp_partition where month=’201804′ ;

《Hive中分区表及陷阱》

  • 201803分区与201804分区组合统计总人数
编写sql文件
sql内容

select count(ename) from emp_partition where month=’201803′ union all select count(ename) from emp_partition where month=’201804′

执行sql文件

bin/hive -f /opt/datas/emp_partition.sql

《Hive中分区表及陷阱》

分区陷阱

创建分区表

create table dept_partition(
deptno int,
dname string,
loc string
)
partitioned by (day string)
row format delimited fields terminated by ‘\t’;

在分区表下创建分区文件夹。

创建分区目录:
dfs -mkdir /user/hive/warehouse/dept_partition/day=20180306

把数据文件上传到分区文件夹下

通过 dfs -put /本地文件 /hdfs目录 ,完成文件上传。
dfs -put /opt/datas/dept.txt /user/hive/warehouse/dept_partition/day=20180306;

查询数据没有结果

select * from dept_partition ;

《Hive中分区表及陷阱》

原因 mysql下的matehouse下的分区表中没有分区数据

《Hive中分区表及陷阱》

解决方法1

msck repair table dept

说明:users can run a metastore check command with the repair table option
msck的意思就是matestore check的意思

《Hive中分区表及陷阱》

解决方法2

alter table dept_partition add partition(day=’20180306′);

测试结果

select * from dept_partition;

《Hive中分区表及陷阱》

为什么会出现这样的问题。

因为通过HDFS put/cp命令往表目录下拷贝分区目录数据文件时并没有在metastore中创建分区数据。所以即使你把数据copy、put到文件夹下也不会查询到。

    原文作者:志辉聊码
    原文地址: https://www.jianshu.com/p/a2df1e6b8d8e
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞