hive分区

1.分区(partitions)

   分区器 partitioner

 hive = hdfs + mysql中的模板 我们分区是将hdfs中的数据分为多份

2.静态分区   例子,单个分区字段

 创建一个temb表,分区字段 month 列与列用空格隔开

   create table tem(id int,tem double) partitioned by (month int) row format delimited fields terminated by " ";

 创建成功
 

 查看表结构   desc tem;

 

 编写tem.txt文件 vim /tem.txt

 

 注意:分区表中的数据分区的列也是表中的一个列,但是这个列不能直接操作,比如在加载数据的时候不能直接将数据加载到表中的这个字段上
    我们需要手动指定,因为我们指定的这个字段将会保存在hdfs中的一个文件夹上

 将本地数据tem.txt上传到tem表里   load data local inpath '/tem.txt' into table tem partition(month=5);

 上传成功

 

 从表里查看数据   select * from tem;
 

 从web页面查看

 

 

 查看tem表的分区   show partitions tem;

 

 再一次上传文件到tem表

 

 查看tem表

 

 可以通过分区号来查询   select * from tem where month=6;
 

 注意:查询数据的时候把分区字段作为一个基础字段进行使用就可以了

3.静态分区   例子,多层分区

 创建一个tem1表,分区字段month、day,分隔符空格

 create table tem1(id int,tem double) partitioned by(month int,day int) row format delimited fields terminated by " ";

 

 编写tem.txt文件   vim /tem.txt

 

 上传文件到tem1表

 load data local inpath '/tem.txt' into table tem1 partition(month=5,day=9);
 load data local inpath '/tem.txt' into table tem1 partition(month=5,day=10);
 load data local inpath '/tem.txt' into table tem1 partition(month=6,day=9);
 load data local inpath '/tem.txt' into table tem1 partition(month=6,day=10);

 现在有四个分区,从web页面查看

 

  

 

 

 查看tem1的分区   show partitions tem1;

 展示的分区数据在mysql中    好处:可以很大增加查询效率,因为直接指向的就是哪个小文件夹的路径
 

4.动态分区

 实际上分区数量越多越精确查询效率越高,不能越多越好?因为如果分区数量特别大那么会使得元数据压力太大,所以我们会取中间值

 分区不需要我们手动指定,我们只需要将数据插入到表中,那么hive会根据字段的值进行自动的分区

 例子,动态分区

 创建tem2表

 create table tem2(id int,tem double) partition by(month int,day int) row format delimited fields terminated by " ";

 

 编写tem2.txt文件

 

 把文件上传到tem2表  load data local inpath '/tem2.txt' into table tem2 partition(month,day);

 

 设置   set hive.exec.dynamic.partition.mode=nonstrict;
 

 

 注意:因为是动态分区所以我们不会指定分区字段,会根据字段的值自己识别,load数据的时候hive表没有办法识别谁是分区字段
    insert数据到这个分区表中,这个表就会知道谁是分区字段insert into table values(1,2,3,4)

    load数据到一个临时表中 然后再从临时表中查询数据  再将数据插入到这个d_p的表中

 创建临时表   create table tem2_e(id int,tem double,month int,day int) row format delimited fields terminated by " ";

 

 把tem2.txt文件上传到临时表tem2_e   load data local inpath '/tem2.txt' into table tem2_e;

 

 将tem2_e表里的数据插入tem2表   insert into tem2 partition(month,day) select * from tem2_e;
 

 从web页面查看

 

 注意:是按照位置进行动态分区,而不是字段名

5.混合分区





 




 



 



 

 



 

 

 

 

原文地址:https://www.cnblogs.com/yezihan/p/10852654.html