文章目录
4.0 绪论
Hive不支持行级别的插入操作,更新操作和删除操作。
4.1 Hive中的数据库
Hive数据库本质上是表的一个目录或者说是命名空间。
如果用户没有指定使用的数据库,那么就会使用default数据库。
- 创建一个数据库
- Hive为每个数据库创建一个目录,数据库中的表是以子目录的形式存储的。
- 数据库所在默认目录位于属性hive.metastore.warehouse.dir所指定的目录。
create database if not exists db_name;
# 通过参数指定数据库目录的地址
create database if not exists db_name location 'new Location';
# 为数据库添加描述信息
create database if not exists db_name comment 'comment msg';
# 为数据库增加一些K-V描述信息
create database if not exists db_name with dbproperties("K"="V","K1"="V1");
# 显示当前数据库
set hive.cli.print.current.db = true;
- 删除一个数据库
- 默认情况下,Hive是不允许用户删除一个数据库(这个数据库中还含有表),要么用户把数据库中的表全部删除完,要么使用cascade关键字,hive会级联的删除表。
drop database if exists db_name;
# 级联删除
drop database if exists db_name cascade;
- 查看数据库
show databases; # 显示所有
show databases like 'h_*'; # 正则表达式匹配
4.2 修改数据库
只能修改dbproperties,其他不能修改。
alter database db_name set dbproperties("k"="V");
4.3 创建表
create table 遵循sql规范,但是具有哦更加广泛的灵活性,比如可以指定数据的存储路径,以及和指定数据的存储格式等。
create table if not exists db.tbl_name(
filed1 dtype comment
...
)
comment ..
location ..
tblproperties("k"="v",...)
1.tblproperties的作用是以k-v格式为表增加额外的文档说明,还可以表示关于数据库连接的必要的连接信息。
2. Hive会自动增加两个表属性,last_modified_by最后一个修改表结构的用户名
和last_modified_time最后修改的时间。
3.show tblproperties tbl_name
用户展示表的tblproperties。
4.location属性
可以指定表在文件系统中的存储路径。
- copy表的结构
# copy表的结构 create table if not exists new_tbl like old tbl_name;
- 查看表的详细结构
show create table tbl_name; describe extended tbl_name; # 结果输出杂乱无章 不建议使用 describe formatted tbl_name; # 建议使用
4.3.1 管理表(内部表)
管理表也称内部表,这种表,hive会控制数据的生命周期,hive默认会将管理表的数据存储在hive.metastore.warehouse.dir中,当前我们删除一个管理表时,其所对应的数据也会被删除。
4.3.2 外部表
删除表模式并不会影响数据。
create external table if not exists tbl_name(
...
)
location ...; # 指定外部表所在位置
4.4 删除表
drop table if exists `tbl_name`
4.5 修改表
4.5.1 表重命名
alter table `tbl_name` rename to `new_name`
4.5.2 修改分区
增加分区
alter table `tbl_name` add if not exists
partition(year = 2021) location 'a/b/c'
partition(year = 2022) location 'a/b/c'
移动分区的location
alter table `tbl_name` partition(...)
set location 'a/b/c/d..'
删除分区
alter table drop `tbl_name` if exists partition(...)
4.5.3 修改列名
alter table `tbl_name` change column `old_attr` `new_attr`
[after attr | first]
# after attr,将字段移动到attr属性之后
# first 将字段移动到第一位
4.5.4 增加列
alter table `tbl_name` add columns (
app_name string comment 'xxxxx',
app_name2 string comment 'xxxxx2',
....
);
4.5.5 删除或者替换列
alter table `tbl_name` replace columns (
// new columns...
)
4.5.6 修改表属性
用户可以增加,修改表属性,但是不能删除表属性。
alter table `tbl_name` set tblproperties(
'P_key' = 'P_value'
....
)
4.6 自定义表的存储格式
row format delimited
lines terminated by '\n' 指定行与行之间的分隔符
fields terminated by ' ' 指定字段之间的分隔符
collection items terminated by ',' 指定集合元素之间的分隔符
map keys terminated by ':' 指定k:v之间的分隔符