一、内部表和外部表
创建表时,未被external修饰的是内部表(managed table),被external修饰的为外部表(external table);
内部表(MANAGED_TABLE):表目录按照hive的规范来部署,位于hive的仓库目录/user/hive/warehouse中
外部表(EXTERNAL_TABLE):表目录由建表用户自己指定
create external table t_access(ip string,url string,access_time string)
row format delimited
fields terminated by ','
location '/access/log';
外部表和内部表的特性差别:
1、内部表的目录在hive的仓库目录中 VS 外部表的目录由用户指定
2、drop一个内部表时:hive会清除相关元数据,并删除表数据目录
3、drop一个外部表时:hive只会清除相关元数据,HDFS上的数据不会被删除;
4、对内部表的修改会将修改直接同步给元数据,而对外部表的表结构和分区进行修改,则需要修复(MSCK REPAIR TABLE table_name;)
一个hive的数据仓库,最底层的表,一定是来自于外部系统,为了不影响外部系统的工作逻辑,在hive中可建external表来映射这些外部系统产生的数据目录;
然后,后续的etl操作,产生的各种表建议用managed_table
二、分区表
create table t_pv_log(ip string,url string,access_time string) partitioned by(day string) row format delimited fields terminated by ','
分区表的实质:在表目录中为数据文件创建分区子目录,这样在查询的时候MR程序就可以针对分区子目录中的数据进行处理,减少读取数据的范围。例如,统计每日pv的时候,可以只读取当日数据。这时将表建为分区表,将每天的日志数据分别存放。
注,分区字段不能和表中已定义字段冲突
比如,网站每天产生的浏览记录,浏览记录应该建一个表来存放,但是,有时候,我们可能只需要对某一天的浏览记录进行分析
这时,就可以将这个表建为分区表,每天的数据导入其中的一个分区;
当然,每日的分区目录,应该有一个目录名(分区字段)
2-1 一个分区字段的实例:
示例如下:
1、创建带分区的表
create table t_access(ip string,url string,access_time string) partitioned by(dt string) row format delimited fields terminated by ',';
注意:分区字段不能是表定义中的已存在字段
2、向分区中导入数据
load data local inpath '/root/access.log.2017-08-04.log' into table t_access partition(dt='20170804');
load data local inpath '/root/access.log.2017-08-05.log' into table t_access partition(dt='20170805');
注意这里的local是针对hive服务运行机器而言的。
3、针对分区数据进行查询
a、统计8月4号的总PV:
select count(*) from t_access where dt='20170804';
实质:就是将分区字段当成表字段来用,就可以使用where子句指定分区了
b、统计表中所有数据总的PV:
select count(*) from t_access;
实质:不指定分区条件即可
2-2 多个分区字段示例
1、建表:
create table t_partition(id int,name string,age int) partitioned by(department string,sex string,howold int) row format delimited fields terminated by ',';
2、导数据:
load data local inpath '/root/p1.dat' into table t_partition partition(department='xiangsheng',sex='male',howold=20);