Hive中分区表及陷阱

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’

还可以添加二级分区
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’);

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

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

分区中的数据查询
查询201803分区数据

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

查询201803分区数据

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

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

分区陷阱
创建分区表

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 ;

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

解决方法
msck repair table dept

说明:users can run a metastore check command with the repair table option

msck的意思就是matestore check的意思

测试结果

select * from dept_partition;

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

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值