内部表:
1.创建表:
create table stu(id int);
2.插入数据:
hive插入数据不能用insert语句,需要从外部文件中加载数据,比如创建一个文件stu_data,内容为:
1
2
3
4
5
命令为(其中/home/hadoop/Public/stu_data为文件路径):
load data local inpath '/home/hadoop/Public/stu_data' into table stu
3.如果是要创建有多个字段的表,就需要区分一下:
create table stu2(id int, name string) row format delimited fields terminated by ' ';
需要加载数据时就要是这样的:
1 john
2 tom
3 gary
插入数据的方法跟上面一样。
查看数据:
select * from stu2
如果将加载语句中的local去掉:
load data inpath '/stu2_data' into table stu2
意思是从hdfs上面加载。
4.删除表:
drop table stu;
外部表:
内部表与外部表的区别是内部表如果删除表,数据一起删除,而外部表如果你删除表,则创建的数据并不会删除。
1.创建表结构:
create external table stu_info(id int, name string) row format delimited fields terminated by ' ' location '/data_stu';
external:指的是一个外部表
location指定数据的位置,注意这里数据在hdfs存储的位置。
2.本地编写文件并上传到hdfs中/data的位置:
1 gary
2 tom
hadoop fs -put /stu2_data /data/stu_data
加载数据跟内部表一样:
load data inpath '/data/stu_data' into table stu_info;
分区表
在hive中表中的一个partition对应的是表下面的一个目录,所有的partition的数据都存储在对应的目录下面:
例如:test表中含data和city两个partition, 则对应于date=20130201,city=bj的HDFS子目录为:
/warehouse/test/date=20130201/city=bj
创建表:
create table partition_tmp(id int, name string)partitioned by(d string) row format delimited fields terminated by ' ';
然后存入数据:
load data local inpath '/stu2_data' into table partition_tmp partition(d='0902');
查看的时候可以全部查看:
select * from partition_tmp;
显示内容如下:
hive> select * from partition_tmp;
OK
1 john 0901
2 tom 0901
3 gary 0901
1 john 0902
2 tom 0902
3 gary 0902
如果按照下面的方式查询:
select * from partition_tmp where d='0901'
hive> select * from partition_tmp where d='0901'
> ;
OK
1 john 0901
2 tom 0901
3 gary 0901
Time taken: 0.308 seconds
桶表
桶表是对数据进行哈希取值,然后放到不同的文件中进行存储。
创建表:
create table bucket_tmp(id int) clustered by (id) into 4 buckets;
加载数据。
set hive.enforce.bucketing=true;
insert into table bucket_tmp select id from partition_stu;
抽样查询:
select * from bucket_tmp tablesample(bucket 1 out of 4 on id);