安利初学者:大数据基础学习教程之Hive的分区

Hive Select查询中一般会扫描整个表的内容,会消耗很多时间做没必要的工作。有时候只需要扫描表中我们关心的一部分数据,因此建表时引入了partition概念。分区是一种根据“分区列”(partition column)的值对表进行粗略划分的机制。Hive中的每个分区对应数据库中相应分区列的一个索引,每个分区对应着表下的一个目录,在HDFS上的表现形式与表在HDFS上的表现形式相同,都是以子目录的形式存在。

1. 什么是分区

分区是表的部分列的集合,可以为频繁使用的数据建立分区,这样查找分区中的数据时就不需要扫描全表,这对于提高查找效率很有帮助。创建分区本质上是在表的目录下创建目录,是对数据的细粒度的管理。

2. 为什么分区

数据量越来越大,hive查询会全表扫描,浪费时间。创建分区,只查询我们关心的那部分数据,提高查询效率。

3. 怎么分区

主要根据具体业务进行分区,数据会依照单个或多个列进行分区,通常按照时间、地域或者是商业维度进行分区。创建表的时候使用partitioned by (字段名 字段类型)进行分区,可以创建多级分区。

4. 分区的操作

4.1 创建一级分区

##创建数据库名为studentinfo

create database if not exists studentinfo;

##在数据库下创建大数据学生表bigdata_stu,并按照字段 year 进行分区

create table if not exists studentinfo.bigdata_stu(

id  int,

name string,

sex tinyint

)

partitioned by (year int)

row format delimited fields terminated by ‘,'

;

##为分区表加载加载数据

load data local inpath ‘/root/Desktop/bigdata_stu.txt' into table bigdata_stu partition (YEAR=2017);

load data local inpath ‘/root/Desktop/bigdata_stu1.txt' into table bigdata_stu partition (YEAR=2018);

##查询分区为2017的数据

select * from studentinfo.bigdata_stu where yeAr=2017;

4.2 创建二级分区

##在数据库下创建大数据学生表bigdata_stu1,并按照字段 year,month 进行分区

create table if not exists studentinfo.bigdata_stu1(

id  int,

name string,

sex tinyint

)

partitioned by (year int,month int)

row format delimited fields terminated by ‘,'

;

##为分区表加载数据

load data local inpath ‘/root/Desktop/bigdata_stu.txt' into table bigdata_stu1 partition (year=2017,month=1);

load data local inpath ‘/root/Desktop/bigdata_stu.txt' into table bigdata_stu1 partition (YEAR=2017,month=2);

##查询2017年1月的大数据学员信息

select * from studentinfo.bigdata_stu1 where year=2017 and month=1;

4.3 对分区进行操作

4.3.1 显示分区

show partitions studentinfo.bigdata_stu1;

4.3.2 新增分区

alter table studentinfo.bigdata_stu1 add

partition(year=2017,month=3);

alter table studentinfo.bigdata_stu1 add partition(year=2017,month=4) partition(year=2016,month=12);

4.3.3 新增分区并加载数据:

alter table studentinfo.bigdata_stu1 add partition(year=2016,month=11) location "/user/hive/warehouse/studentinfo.db/bigdata_stu/year=2017/month=2";

4.3.4 修改分区所对应的存储路径:

##路径必须从hdfs写起

alter table studentinfo.bigdata_stu1 partition(year=2016,month=11) set location "hdfs://linux1:9000/user/hive/studentinfo.db/bigdata_stu/year=2017/month=3";

4.3.5 删除分区:删除分区将会删除对应的分区目录(数据)

##删除某个分区

alter table studentinfo.bigdata_stu1 drop partition(year=2017,month=2);

##删除多个

alter table studentinfo.bigdata_stu1 drop partition(year=2017,month=3),partition(year=2017,month=4);

5.分区的细节

5.1 分区名不区分大小写,不建议使用中文

5.2 分区使用的字段是表外字段,只存在于元数据中,数据中不存在

5.3 分区的本质就是在表的目录下创建目录

5.4 可以创建多级分区

 


猜你喜欢

转载自blog.csdn.net/programmer_feng/article/details/80198161
今日推荐