0
点赞
收藏
分享

微信扫一扫

hive基本操作

心存浪漫 2023-10-24 阅读 38

间隔几年,又开始频繁写hive的sql,整理一点关于hive常用的基本语句,只有天天写的时候才很熟练,过几年很容易遗忘的东西。

hive创建表

drop table if exists       ods.tb_fdn_testtable ;
create table if not exists ods.tb_fdn_testtable  (
    city            string  comment '地市', 
    county          string  comment '区县', 
    juxiang         string  comment '字段释义'
)
comment '表释义'
row format delimited 
fields terminated by '$'
null defined as ''
stored as textfile 
location '/user/hive/warehouse/ods.db/tb_fdn_testtable';

关于hive表的字段分隔符,建议自定义的比较好一些,因为做的项目不是银行金融业的,所以个人常用$符号或者#号。字段分隔符根据操作的数据种类自定义,一般分隔符和数据本身不冲突,但不排除特殊情况,最好设置多个字符作为分隔符,但在hive中还需要去改造配置才能使用。

好处是,格式统一,ETL处理方便,必要时少走弯路。在数据治理过程中少挖坑。

加载hdfs文件到表中

load data   inpath '/import_data/mysql_data/tb_fdn_testtable' overwrite into table ods.tb_fdn_testtable;

加载服务器文件到表中(多了个local)

load data  local inpath '/import_data/mysql_data/tb_fdn_testtable' overwrite into table ods.tb_fdn_testtable;

指定行数加载文件(例如跳过第一行)

用于加载的表第一行是列标题的这种情况

alter table tmp.table_name set tblproperties('skip.header.line.count'='1');

文件映射到表

文件映射到表
alter table ods.tablename add partition(acct_day='2023-08-03') location '/nocccdata/tablename/2023-08-03';

关于分区的简单操作:

批量删除分区
alter table tb_partition drop partition (etl_dt>='20181102',etl_dt<='20181104')
alter table tablename drop if exists partition (acct_day<>'');
删除分区
alter table dwa.tablename drop partition(acct_day='20230720');
增加分区
alter table dwa.tablename add partition(acct_day='20230720');

查看表详细格式(如查看是否为外部表)

desc formatted ods.tablename  ;

hive查询数据导出到本地:

insert overwrite local directory '/export/servers/hiveexport/tablenameFile.csv'  
row format delimited fields terminated by '$'  
collection items terminated by '\n'
select * from hive_tablename   ; 

hive表中字段包含分隔符的,建表语句处理

drop table if exists tmp.table_name;
create table if not exists tmp.table_name (
  id                         string  comment '主键',
  profession                 string  comment '专业类型',
  urban                      string  comment '城市农村'  
)
comment '临时表'
ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.OpenCSVSerde'
WITH SERDEPROPERTIES (
   'separatorChar' = ',',  --分隔符
   'quoteChar'     = '"', --引号
   'escapeChar'    = '\\' --转义字符
) 
 stored as textfile
location '/user/hive/warehouse/tmp.db/table_name'
tblproperties('skip.header.line.count'='1')  ; 
--跳过第一行-- 指定加载文件开始行数-- 这行放location后,不然很容易报错





举报

相关推荐

0 条评论