HIVE表基本相关
HIVE分为分区表和桶表。
分区表
分区表:将整个表的数据在存储时划分成多个子目录来存储(子目录就是以分区名来名称),根据业务来,通常就是使用 年,月,日,地区等。
静态分区表
- 创建分区表
CREATE TABLE test.dw_user_orders(
id bigint,
name varchar(255)
) partitioned by (dt char(6))
COMMENT '员工信息表'
ROW FORMAT DELIMITED
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
STORED AS TEXTFILE;
- 添加分区
alter table test.dw_user_orders add partition (dt='202009');
- 分区重命名
alter table test.dw_user_orders partition(dt='202009') rename to partition(dt='202010');
- 删除分区
alter table test.dw_user_orders drop if exists partition(dt='202009');
- 向表分区导入数据
# 导入HDFS数据文件
LOAD DATA INPATH '/data/d2.dat' OVERWRITE INTO TABLE test.dw_user_orders partition (dt='202009');
# 导入本地数据文件。注意:如果是用beeline连接的hiverserver2,数据必须要在所连接的hiverserver2节点上
LOAD DATA LOCAL INPATH '/home/mapsuser/data/d2.dat' OVERWRITE INTO TABLE test.dw_user_orders partition (dt='202009');
动态分区表
动态分区:往hive分区表中插入数据时,如果需要创建的分区很多,比如以表中某个字段进行分区存储,则需要复制粘贴修改很多sql去执行,效率低。因为hive是批处理系统,所以hive提供了一个动态分区功能,其可以基于查询参数的位置去推断分区的名称,从而建立分区。
- 开启动态分区
# 表示开启动态分区功能(默认false)
set hive.exec.dynamic.partition =true
# 表示允许所有分区都是动态的,否则必须有静态分区字段(默认strict)
set hive.exec.dynamic.partition.mode = nonstrict
# 每个mapper或reduce可以创建的最大分区数,超出则会报错(默认100)
set hive.exec.max.dynamic.partitions.pernode=100
# 表示一个动态分区语句可以创建的最大动态分区个数,超出报错(默认1000)
set hive.exec.max.dynamic.partitions =1000
# 全局可以创建的最大文件个数,超出报错(默10000认)
set hive.exec.max.created.files =10000
桶表
桶是比表或分区更为细粒度的数据范围划分。针对某一列进行桶的组织,对列值哈希,然后除以桶的个数求余,决定将该条记录存放到哪个桶中。
- 创建桶表
create table bdm.cust_info(
id int,
name string
)
clustered by (id) into 4 buckets
stored as parquet;
注意:桶表导入数据前需要开启:set hive.enforce.bucketing=true;
- 导入数据
insert into table bdm.cust_info select id,name from bdm.cust_info_tmp;
- 查询数据
select * from bdm.cust_info tablesample(bucket 1 out of 16 on id) limit 50;
tablesample(bucket x out of y):
x:表示从第几桶开始抽数据
y:表示抽数据的比例,是抽数据的分母。
比如: 有8个分桶
tablesample(bucket 1 out of 16):表示从第1桶开始抽数据,抽取第一桶数据的比例为(8(桶数)/16(分母))=1/2,抽取第一桶1/4。