表结构
1 , 小明1 , lol- book- movie, dalian:ganjingzi- shenyang:sujiatun
2 , 小明2 , lol- book- movie, dalian:ganjingzi2- shenyang:sujiatun2
对于Hive多了以下几种类型
string
array
map
struct
创建表(DDL)
自定义分隔符
create table psn(
id int ,
name string,
likes ARRAY< string> ,
address map< string, string>
) row format delimited
fields terminated by ','
collection items terminated by '-'
map keys terminated by ':' ;
默认分隔符
属性:^ A
集合:^ B
map :^ C
分隔符从^ A到^ F共8 个
cat - A filename
老的大数据公司你可能会见到
\001 对应^ A
\002 对应^ B
\003 对应^ C
老公司有这么用的,不过不要这么用
查看字段
desc psn;
查看详细信息
desc formatted psn;
内部表与外部表
create external table psn4(
id int ,
name string,
likes array< string> ,
address map< string, string>
) row format delimited
fields terminated by ','
collection items terminated by '-'
map keys terminated by ':'
location '/data/local' ;
分区表
hive默认将表数据保存在某个hdfs的存储目录下
当需要检索某些数据的时候,需要全量遍历数据,io量很大,效率低
因此可以采用分而治之的思想,将符合某些条件的数据放置在某一个目录
此时检索的时候只需要搜索指定目录即可,不需要全量遍历数据。
创建单分区表
create table psn5(
id int ,
name string,
likes array< string> ,
address map< string, string>
)
partitioned by ( gender string)
row format delimited
fields terminated by ','
collection items terminated by '-'
map keys terminated by ':' ;
load data local inpath '/root/data/data.txt' into table psn partition ( gender= man) ;
创建多分区表
partitioned by ( gender string, age int )
load data local inpath '/root/data/data.txt' into table psn partition ( gender= man, age= 12 ) ;
单独操作分区表的值
alter table table_name add partition ( gender= girl, age= 12 )
alter table table_name drop partition ( age= 12 )
修复分区
我们手动创建目录、上传数据、并且创建外部表后,是查询不到数据的
因为mysql元数据里并没有更新分区表的元数据
所以我们要修复分区,更新mysql元数据,才能查询到数据
/ tongyuzhe/ data / age= 10
/ tongyuzhe/ data / age= 20
/ tongyuzhe/ data / age= 10 / data . txt
/ tongyuzhe/ data / age= 20 / data . txt
create external table psn7(
id int ,
name string,
likes array< string> ,
address map< string, string>
)
partitioned by ( age int )
row format delimited
fields terminated by ','
collection items terminated by '-'
map keys terminated by ':'
location '/tongyuzhe/data' ;
select * from psn7;
msck repair table psn7;
select * from psn7;
动态分区
以上面的方式创建hive的分区表会存在问题,每次插入的数据都是人为指定分区列的值,我们更加希望能够根据记录中的某一个字段来判断将数据插入到哪一个分区目录下,此时利用我们上面的分区方式是无法完成操作 的,需要使用动态分区来完成相关操作,现在学的知识点无法满足,后续讲解。
写入数据
利用load写入数据
load data local inpath '/root/data/data.txt' overwrite into table psn;
实际上这些数据只是按照指定分隔符分割的文本文档,手动将指定文本格式的文档put到hdfs数据库目录下,select也可以读出数据。
查询数据插入结果表
INSERT OVERWRITE TABLE psn9 SELECT id, name FROM psn
from psn
insert overwrite table psn9
select id, name
insert into table psn10
select id
将查询到的结果插入到文件系统中
insert overwrite directory '/result' select * from psn;
insert overwrite local directory '/result' select * from psn;
传统方式插入数据
insert into psn values ( 1 , 'zhangsan' )
事务
其他