hive表的使用——创建修改删除

时间:2024-04-07 14:34:26

hive表的使用——创建修改删除

本文主要介绍hive中表的增加,修改和删除等。

好,下面上货。

创建表:
1、新建数据库xytestdatabase
2、编写建表脚本createtable
create table if not exists xytestdatabase.employee(
name string,
salary float,
familys array<string>,
properties map<string,string>,
address struct<street:string,city:string>
)
3、在hive命令行下执行建表脚本
source /root/xytest/hivehql/createtable
hive表的使用——创建修改删除

4、查看表的详细信息
describe xytestdatabase.employee;
describe extened xytestdatabase.employee;
hive表的使用——创建修改删除

可以查看在hdfs中表保存的位置
hive表的使用——创建修改删除
hive表的使用——创建修改删除

5、可以用更加美观的方式查看表信息
describe formatted xytestdatabase.employee;
hive表的使用——创建修改删除

拷贝表:
create table if not exists xytestdatabase.employee2 like xytestdatabase.employee;
hive表的使用——创建修改删除

管理表(内部表)和外部表
管理表和外部表的主要区别是表中数据的归属,可以近似的理解为管理表的数据归hive所有,而外部表的数据不归hive所有。更直白的说法是当hive删除表时,管理表的数据会同时别删除,但是外部表的数据不会被删除,只会删除表的定义(表的定义保存在mysql中)。

下面是创建外部表的脚本
create external table if not exists xytestdatabase.employeeout(
name string,
salary float,
familys array<string>,
properties map<string,string>,
address struct<street:string,city:string>
)
row format delimited fields terminated by ','
location '/data/xytestdatabase.employeeout'
执行建表语句
hive表的使用——创建修改删除\

查看表详情
describe formatted xytestdatabase.employeeout;

hive表的使用——创建修改删除

分区表:
管理表和外部表都可以创建分区成为分区表,也就是管理分区表和外部分区表。分区表的本质就是在保存表中数据的时候保存到如下的文件夹中:
/employeepartition/street=a/country=b
/employeepartition/street=a/country=c
分区表的作用是优化查询的效率,不用每次都进行所有文件的扫描,只需要扫描指定的文件夹即可。
下面是创建分区表的语句。
create table if not exists xytestdatabase.employeepartition(
name string,
salary float,
familys array<string>,
properties map<string,string>,
address struct<street:string,city:string>
)
partitioned by (street string,country string)
hive表的使用——创建修改删除

查看分区表详情:
hive表的使用——创建修改删除

能够通过show partitions查看分区情况。

hive表的使用——创建修改删除

外部表也能够建立分区,略。

自定义表存储格式:
表存储时能够指定使用的分隔符。

create table if not exists xytestdatabase.employeeselfdelimiter(
name string,
salary float,
familys array<string>,
properties map<string,string>,
address struct<street:string,city:string>
)
row format delimited
fields terminated by '\001'
collection items terminated by '\002'
map keys terminated by '\003'
lines terminated by '\n'
stored as textfile;

hive表的使用——创建修改删除

查看分隔符信息

hive表的使用——创建修改删除

修改表:
修改表名称:
alter table test rename to test001;
把表test的名称修改为test001。

修改表中的列,添加列、修改列、删除列。
alter table test add columns(
name:string,
age:int
)

增加分区
alter table employeepartition add if not exists
partition(street = 'aa',country='bb')
partition(street = 'ee',country='ff')


运行后结果:
hive表的使用——创建修改删除


hive表的使用——创建修改删除


hive表的使用——创建修改删除


删除表:
drop table if exists xytestdatabase.employee2;
hive表的使用——创建修改删除