1. 什么是分区
直白一点来说,分区就是在表目录下建立子目录。
2. 为什么要使用分区
随着系统运行时间的增长,数据文件就会越来越大,当Hive对文件进行搜索时,会对全表进行搜索,导致效率降低。而分区的作用就是将表目录下的文件进行分类,将数据分类后进行存储,这样就会避免全表搜索,提高查询效率。
3.什么是静态分区
静态分区就是添加数据时需要手动指定分区
4. 创建静态分区
4.1 语法
CREATE [EXTERNAL
] TABLE [IF NOT EXISTS] [db_name
.]table_name
[(col_name data_type
[COMMENT col_comment
], ...)]
[COMMENT table_comment
]
[PARTITIONED
BY (col_name data_type
[COMMENT col_comment
], ...)]
[CLUSTERED BY (col_name
, col_name
, ...)
[SORTED
BY (col_name
[ASC|DESC], ...)] INTO num_buckets BUCKETS
]
[ROW FORMAT row_format
]
[STORED
AS file_format
]
[LOCATION hdfs_path
]
4.2 案例
CREATE TABLE IF NOT EXISTS t_part
(
uid
int,
uname string
,
sex string
,
age
int
)
PARTITIONED
BY(country string
)
ROW FORMAT DELIMITED
FIELDS TERMINATED BY '\t';
load data local inpath
'/home/user_china.txt' into table t_part
partition(country
='china');
create table if not exists t_part
(
uid
int,
uname string
,
sex string
,
age
int)
partitioned
by(year string
, month string
)
row format delimited
fields terminated by '\t';
load data local inpath
'/home/user-2019-11-11.txt' into table t_part
partition(year='2019', month='11');
load data local inpath
'/home/user-2019-12-12.txt' into table t_part
partition(year='2019', month='12');
load data local inpath
'/home/user-2019-01-12.txt' into table t_part
partition(year='2019', month='01');
4.3 注意事项
1. hive的分区名称区分大小写
2. hive分区的本质是在表下创建子目录,但是该分区字段是一个伪列(在数据中不存在,但是却可以查询)
e.g.
分区目录名:province='杭州'
- hive的分区和mysql分区的区别:
* hive的分区使用表外字段,是一个伪列
* mysql使用的是表内字段,即不用分区也可以直接查询
3. 一张表中可以存在一个或多个分区;分区之下又可以存在一个或多个分区。
4. 在分区的时候分区值是有区别的,比如day=1和day=01是两个不同的参数值,申明一定请注意。
5 显示分区
show partitions tablename
;
6 修改分区
6.1 修改分区名称
ALTER TABLE table_name
PARTITION partition_spec
RENAME TO PARTITION partition_spec
;
e
.g
.
alter table t_2
partition(country
='japon') rename to partition(country
='usa');
6.2 增加分区
ALTER TABLE t_part
ADD PARTITION(country
='korea');
ALTER TABLE t_part
ADD PARTITION(country
='france') PARTITION(country
='italy');
6.3 添加分区并设置数据
ALTER TABLE t_part
ADD PARTITION(country
='korea')
LOCATION
'/user/hive/warehourse/hive.db/t_part/country=china';
6.4 修改分区在hdfs中存储路径
ALTER TABLE t_part
PARTITION(country
='korea')
SET LOCATION
'hdfs://hbase1:9000/user/hive/warehourse/hive.db/t_part/country=spain';
6.5 删除分区
ALTER TABLE t_part
DROP PARTITION(country
='korea');
ALTER TABLE t_part
DROP PARTITION(country
='france'),PARTITION(country
='italy');