分区表导入

创建分区表

  1. create table stu_ptn
  2. (id int , name string ,sex string , age int)
  3. partitioned by (dept string)
  4. row format delimited
  5. fields terminated by ',' ;

补充说明:load / insert ()需要有分配资源进程 ——> hadoop04 执行:start-yarn.sh

load导入数据,需要手动的指定分区

(文件夹不需要提前存在,自动创建)

load data local inpath '/home/hadoop/student.txt'
into table stu_ptn partition(dept = 'IS');

缺陷

  1. select * from stu_ptn; ——> 验证数据,发现所有部门都是一样的,程序没有报任何的错
  2. cat student.txt—-> 验证数据文件,发现数据文件没有问题

原因:数据仓库是读模式,导入数据的时候,没有数据检查
说明: 分区表导入 和内部表和外部表差不多,需要额外指定partition(分区字段 = 分区值);

insert数据插入

单条数据插入

insert into table stu_ptn partition(dept='IS') values(1,"haha",'q',-1);

单重数据插入

insert into table stu_ptn partition(dept='IS') 
select  id , name , sex , age  from stu_managed where dept = 'IS';
  1. select 查询出来的字段要和分区表创建字段进行对应
  2. insert 一般要结合 where 来使用

    多重数据插入

    from 数据库.stu_managed
    insert into table 数据库.stu_ptn  partition(dept='IS') 
    select  id , name , sex , age   where dept = 'IS'
    insert into table 数据库.stu_ptn  partition(dept='CS') 
    select  id , name , sex , age   where dept = 'CS'
    insert into table 数据库.stu_ptn  partition(dept='MA') 
    select  id , name , sex , age   where dept = 'MA';
    

    动态导入: insert

    一级动态分区

  3. insert 导入数据的时候 partition(dept)字段不需要指定具体的分区

  4. select 的最后一个字段必须是partition(dept)分区字段
    insert into table stu_ptn1 partition(dept)
    select id , name , sex , age , dept  from stu_managed;
    

    二级的动态分区

    ```plsql create table stu_ptn3 (id int , name string , age int) partitioned by (dept string,sex string ) row format delimited fields terminated by ‘,’ ;

select 正常表字段 + 分区字段 insert into table stu_ptn3 partition(dept,sex) select id , name , age ,dept ,sex from stu_managed;

注:公司一般没有人来做三级动态分区?<br />动态分区,从大的维度变成一个小的维度,维度越多,一个分区下产生小文件概率会很大(namenode)
<a name="svwhf"></a>
#### 一个静态分区和一个动态分区的组合 :
```plsql
insert into table stu_ptn4 partition(dept='IS',sex)
select id , name , age  ,sex from stu_managed;

分桶表导入

创建表

create table stu_buk
(id int , name string , sex string , age int , dept string)
clustered by (dept) 
sorted by (age desc)
into 3 buckets 
row format delimited
fields terminated by ',' ;

导入数据

load导入

load(复制,剪切)方式可以把数据导入分桶表,但分桶表的作用不会真正产生
load data local inpath '/home/hadoop/student.txt'
into table stu_buk;

insert导入

建表语义:

//期望向表里面导入数据的时候,
create table stu_buk
(id int , name string , sex string , age int , dept string)
clustered by (dept)        //期望 dept分区
sorted by (age desc)       //age排序
into 3 buckets             //期望 启动3个reduceTask
row format delimited
fields terminated by ',' ;

//实际导入设置
//分桶导入
insert into table stu_buk 
select id,name,sex,age ,dept from stu_managed
distribute by(dept) sort by(age desc);

//设置reduceTask个数:启动的MR程序,启动3个reduceTask
set mapreduce.job.reduces = 3 ;
//设置分桶:hive 会话支持分桶导入 
set hive.enforce.bucketing = true ;