在hive终端执行shell语句,行首加!
!ls /opt;
建库
本质:在数仓目录下创建一个目录(库名.db)
create database [if not exists] dbName [comment 'this is dbName'];
建表
create [external] table [if not exists] tableName (
col_name data_type [comment 'column'],
col1 data_type [comment 'column']
)
[comment 'table comment']
[partitioned by (col_name data_type [comment 'comment'],...)]
[clustered by (col1, col2...)]
[sorted by (col [desc | asc]) into num_buckets buckets]
[row format row_format]
[sorted as file_format]
[location hdfs_path]
;
# 分隔符只能在建表的时候指定,建好后无法修改
# 例
create table if not exists person (
age int comment '这是年龄',
id int comment '这是id'
)
comment '这是tableName'
row format delimited
fields terminated by '\t'
lines terminated by '\n'
;
外部表、内部表:
(1)默认都建在数仓目录下,如果外部表指定location,建在location 位置
(2)删除表 : 内部表全部删除 ,外部表只删除元数据和表结构,表数据不受影响
加载数据方式
(1) insert into table tn
partition(date_time=‘2020-03-16’)
select * from …
覆盖表
insert overwrite table dwd_active_background_log
partition(date_time=‘2020-03-16’)
select * from …
(2) hdfs上传
(3) load data [local] inpath ‘数据原路径’ into table 表名;
如果是从本地加载,是copy到表目录下
如果是从HDFS加载,相当于mv到表目录下
(4) 多行加载
insert into tableName
select * from table_src
conditon
;
克隆表
# 不带数据,只克隆结构
create table if not exists t2 like t1;
# 带数据,此种情况 t2 可以建好,但在hdfs上看不到 t2
create table if not exists t2 like t1 location t1_path;
# 带数据
create table if not exists t2
as
select *from t1
condition
;
关于hive本地模式
如果hive的输入的数据量非常小,为查询触发执行任务时消耗可能会比实际job的执行时间要多的多。对于大多数这种情况,Hive可以通过本地模式在单台机器上处理所有的任务。对于小数据集,执行时间可以明显被缩短。
用户可以通过设置hive.exec.mode.local.auto的值为true,来让Hive在适当的时候自动启动这个优化。
set hive.exec.mode.local.auto = true; # 修改本地模式
set hive.exec.mode.local.auto; # 查询本地模式状态
或者去 hive-default.xml.template 文件中修改该属性的值
DDL
alter
- 修改表名 alter table t1 rename to t2;
- 修改列名 alter table t1 change column col_name new_name data_type;
- 修改列数据类型 同上
- 修改列前后顺序 alter table tt change column id id int after name; #没错就这么写 alter table tt change column id id int first; # 没有last 参数,只有 first参数
- 增加列 alter table tt add columns(id int, age int);
- 删除列 本质是先删除表,再创建 alter table tt replace columns(); # 括弧里面不写要删除的列就行
- 内部表外部表转换 alter table tt set tblproperties(“EXTERNAL”=“TRUE”) TRUE一定要大写,false 大小写都行
drop
- 删除空库 drop databases [if exists] db;
- drop databases db purge; 永久删除
- 强制删库 drop databases [if exists] db cascade;
- trucate tt 删除表数据,保留表结构, 不能用于外部表
划重点:分区
CREATE EXTERNAL TABLE dwd_error_log(
mid_id
string,
user_id
string
)
PARTITIONED BY (date_time string)
;