4.1 管理表
由Hive全权管理的表
所谓的管理表指hive是否具备数据的管理权限,如果该表是管理表,当用户删除表的同时,hive也会将表所对应的数据删除,因此在生产环境下,为了防止误操作,带来数据损失,一般考虑将表修改为非管理表-外部表
总结:Hive的管理,表结构,hdfs中表的数据文件,都归Hive全权管理。---- hive删除管理表,HDFS对应文件也会被删除。
缺点:数据不安全。
4.2 外部表
引用映射HDFS数据作为表管理,但无法删除数据
外部表和管理表最大的区别在于删除外部表,只是将MySQL中对应该表的元数据信息删除,并不会删除hdfs上的数据,因此外部表可以实现和第三方应用共享数据。在创建外表的时候需要添加一个关键字"external"即可。create external xxx()...
# 创建外部表 1. 准备数据文件personout.txt 2. 上传至hdfs中,该数据文件必须被放在一个单独的文件夹内。该文件夹内的数据文件被作为表数据 3. 创建表: create external location 在最后使用location 指定hdfs中数据文件所在的文件夹即可。 create external table t_personout( id int, name string, salary double, birthday date, sex char(1), hobbies array<string>, cards map<string,string>, addr struct<city:string,zipCode:string> )row format delimited fields terminated by ',' --列的分割 collection items terminated by '-'--数组 struct的属性 map的kv和kv之间 map keys terminated by '|' lines terminated by '\n' location '/file/personout.tb';
4.3 分区表
将表按照某个列的一定规则进行分区存放,减少海量数据情况下的数据检索范围,提高查询效率;
举例:电影表、用户表
分区方案:按照用户区域、电影类型
应用:依据实际业务功能,拿查询条件的列作为分区列来进行分区,缩小MapReduce的扫描范围,提高MapReduce的执行效率,
总结:
table中的多个分区的数据是分区管理
1:删除数据按照分区删除。如果删除某个分区,则将分区对应的数据也删除(外部表,数据删除,数据文件依然在)。
2:查询统计,多个分区被一个表管理起来。
select * from 表 where 分区字段为条件。
4.3.1 创建分区表
数据源文件
# 文件"bj.txt" (china bj数据) 1001,张三,1999-1-9,1000.0 1002,李四,1999-2-9,2000.0 1008,孙帅,1999-9-8,50000.0 1010,王宇希,1999-10-9,10000.0 1009,刘春阳,1999-9-9,10.0 # 文件“tj.txt” (china tj数据) 1006,郭德纲,1999-6-9,6000.0 1007,胡鑫喆,1999-7-9,7000.0
建表
create external table t_user_part( id string, name string, birth date, salary double )partitioned by(country string,city string)--指定分区列,按照国家和城市分区。 row format delimited fields terminated by ',' lines terminated by '\n';
创建分区表并导入数据
# 导入china和bj的数据 load data local inpath "/opt/bj.txt" into table t_user_part partition(country='china',city='bj'); # 导入china和heb的数据 load data local inpath "/opt/tj.txt" into table t_user_part partition(country='china',city='tj');
查看分区信息
show partitions t_user_part;
使用分区查询:本质上只要查询条件在存在分区列
select * from t_user_part where city = 'bj'
删除分区信息
会连同分区数据一块删除
alter table t_user_part drop partition(country='china',city='bj');
添加分区(了解)
外部分区表,删除后,hive不管理数据,但是数据文件依然存在
alter table t_user_part add partition(country='china',city='heb') location '/file/t_user_part/heb';
# 表分类 1. 管理表 hive中table数据和hdfs数据文件都是被hive管理。 2. 外部表--常用--hdfs文件安全。 hive的table数据,如果删除hive中的table,外部hdfs的数据文件依旧保留。 3. 分区表--重要。 将table按照不同分区管理。 好处:如果where条件中有分区字段,则Hive会自动对分区内的数据进行检索(不再扫描其他分区数据),提高hive的查询效率。