hive基础(二) hive操作大全

目录

注:只是为了以后忘了,好翻。。。。。。。做个总结

一) hive 操作

1) hive -e

2) hive -f

3) 查看在hive中输入的所有历史命令

4) hive运行日志修改

二) hive参数配置

三) hive数据类型

基本数据类型

集合数据类型

1)复杂类型解释

2)建表语句:

3)  造数据 :text.txt

4)load数据

5)  访问方式

hive类型转换

四) DDL操作

库操作

1) 创建数据库

2)修改数据库

3) 删除数据库

表操作

创建表

栗子

外部表

修改表

增加、修改表分区

增加、修改、替换列信息

删除表

五) DML操作

加载数据方式

一:load

二:insert

三:As select(查询的结果会添加到新建的表中)

四:建表时通过location指定加载数据路径

五: import

六) 查询

基本语法

排序

七)分区表和分桶表

分区

一级分区

二级分区

动态分区

分桶表

抽样查询

八) 函数

1)NVL( value,default_value)

2) case when then else end

3)行转列

列转行

窗口函数

over

九)压缩和存储


注:只是为了以后忘了,好翻。。。。。。。做个总结

一) hive 操作

1) hive -e

hive -e “sql” 不需要进入交互窗口

2) hive -f

hive -f  hive.sql 执行hql的文件

hive -f  hive.sql  > path/result.txt

3) 查看在hive中输入的所有历史命令

[root@henghe-052 bin]# cd /root

[root@henghe-052 ~]# cat .hivehistory

4) hive运行日志修改

hive的log默认放在 /tmp/用户

[root@henghe-052 ~]# cd /tmp/root/
修改地址

[root@henghe-052 conf]# mv hive-log4j2.properties.template  hive-log4j2.properties

[root@henghe-052 conf]# vim hive-log4j2.properties

二) hive参数配置

1)配置文件

在hive-site.xml和hive-default.xml中配置

2)命令行方式

[root@henghe-052 apache-hive-3.1.2-bin]#  bin/hive -hiveconf mapred.reduce.tasks=10;

3)参数声明方式

hive> set mapred.reduce.tasks=100;

参数声明>命令行>配置文件

三) hive数据类型

基本数据类型

集合数据类型

1)复杂类型解释

数组:"name":["bb","cc"]-> namearry<string>

集合:  "aa":{"bb":1,"cc":2}-> aa map<string,int>

struct: "address":{"street":"wangjing","city":"beijing"}-> address struct<street:string,city:string>

2)建表语句:

create table test(
name string,
friends array<string>,
children map<string, int>,
address struct<street:string, city:string> )
row format delimited fields terminated by ','
collection items terminated by '_'
map keys terminated by ':'
lines terminated by '\n';
字段解释:
row format delimited fields terminated by ',' -- 列分隔符
collection items terminated by '_' --MAP STRUCT 和 ARRAY 的分隔符 ( 数据分割符号 )
map keys terminated by ':' -- MAP 中的 key value 的分隔符
lines terminated by '\n'; -- 行分隔符

3)  造数据 :text.txt

cy,tt_susu,yuanyuan:didi,chao yang_beijing

4)load数据

load data local inpath '/data/test.txt' into table test;

5)  访问方式

hive> select friends[1],children['xiao song'],address.city from test

hive类型转换

1 )隐式类型转换规则如下
1 )任何整数类型都可以隐式地转换为一个范围更广的类型,如 TINYINT 可以转换成
INT INT 可以转换成 BIGINT
2 )所有整数类型、 FLOAT STRING 类型 都可以隐式地转换成 DOUBLE
3 TINYINT SMALLINT INT 都可以转换为 FLOAT
4 BOOLEAN 类型不可以转换为任何其它的类型。
2 )可以使用 CAST 操作显示进行数据类型转换
例如 CAST('1' AS INT) 将把字符串 '1' 转换成整数 1 ;如果强制类型转换失败,如执行
CAST('X' AS INT) ,表达式返回空值 NULL
sql例子: select '1'+2, cast('1'as int) + 2;

四) DDL操作

库操作

1) 创建数据库

CREATE DATABASE [IF NOT EXISTS] database_name
[COMMENT database_comment]
[LOCATION hdfs_path]
[WITH DBPROPERTIES (property_name=property_value, ...)];

location:指定在hdfs位置

create database if not exists db_hive2 location '/db_hive2.db';

2)修改数据库

alter database db_hive2 set dbproperties('createtime'='20210730');

3) 删除数据库

hive>drop if not exists  database db_hive2;

如果数据库不为空,加上cascade命令,强制删除

hive> drop database db_hive cascade;

表操作

创建表

CREATE [EXTERNAL] TABLE [IF NOT EXISTS] table_name
[(col_name data_type [COMMENT col_comment], ...)]
[COMMENT table_comment]
[PARTITIONED BY (col_name data_type [COMMENT col_comment], ...)]
[CLUSTERED BY (col_name, col_name, ...)
[SORTED BY (col_name [ASC|DESC], ...)] INTO num_buckets BUCKETS]
[ROW FORMAT row_format]
[STORED AS file_format]
[LOCATION hdfs_path]
[TBLPROPERTIES (property_name=property_value, ...)]
[AS select_statement]

字段解释:

EXTERNAL: 外部表

COMMENT :注释

PARTITIONED BY: 分区表

CLUSTERED BY:分桶表

SORTED BY:对桶中的一个或多个列另外排序

ROW FORMAT:

DELIMITED [FIELDS TERMINATED BY char] [COLLECTION ITEMS TERMINATED BY char]
[MAP KEYS TERMINATED BY char] [LINES TERMINATED BY char]
| SERDE serde_name [WITH SERDEPROPERTIES (property_name=property_value,
property_name=property_value, ...)]
STORED AS : 存储文件类型(textfile sequencefile orc)
LOCATION : hdfs上位置
AS:后跟查询语句,根据查询结果创建表

LIKE: 复制表结构,但是不复制数据

栗子

1.创建普通表

create table if not exists student(
id int, name string
)
row format delimited fields terminated by '\t'
stored as textfile
location '/user/hive/warehouse/student';

2.根据查询结果创建表

create table if not exists student2 as select id, name from student;

3.根据已经存在的表结构创建表

create table if not exists student3 like student;

外部表

当hive执行删除表操作时,只会删元数据信息,不会删除hdfs上的数据
1)创建外部表
create external table if not exists dept(
deptno int,
dname string,
loc int
)
row format delimited fields terminated by '\t';
2)查看 desc formatted dept;

3)管理表表外部表互换
hive> alter table student set tblproperties('EXTERNAL'='TRUE');

('EXTERNAL'='TRUE')  为固定写法,区分大小写

修改表

hive> alter table student2 rename to student22;

增加、修改表分区

增加、修改、替换列信息

增加

hive> alter table student22 add columns (sex  string);

修改

hive> alter table table_name change column name newName string;

替换列

hive> alter table student22 replace columns(sid string,sname string,ssex string);

删除表

drop table student22

五) DML操作

加载数据方式

一:load

0)语法

hive> load data [local] inpath ' 数据的 path' [overwrite] into table
student [partition (partcol1=val1,…)];

1)创建一张表

hive> load data inpath local '/opt/moudle/apache-hive-3.1.2-bin/testData/test.txt' into table student;

2)加载本地数据

hive> load data local inpath '/opt/moudle/apache-hive-3.1.2-bin/testData/test.txt' into table student;

3)  加载hdfs数据

hive> dfs -put /opt/moudle/apache-hive-3.1.2-bin/testData/test.txt /hivetestdata;

二:insert

insert into table student values(1,"cy"),(2,"cxy");

三:As select(查询的结果会添加到新建的表中)

create table if not exists student3 as select id, name from student; 

四:建表时通过location指定加载数据路径

1)上传数据到hdfs上

hive (default)> dfs -mkdir /student;

hive (default)> dfs -put /opt/module/datas/student.txt /student; 

2)创建表,并指定在hdfs上的位置

hive (default)> create external table if not exists student5(  id int, name string  )  row format delimited fields terminated by '\t'  location '/student';

3)查询数据 hive (default)> select * from student5; 

五: import

注意:先用export导出后,再将数据导入。

hive (default)> import table student2   from '/user/hive/warehouse/export/student';

六) 查询

基本语法

SELECT [ALL | DISTINCT] select_expr, select_expr, ...   FROM table_reference   [WHERE where_condition]   [GROUP BY col_list]   [ORDER BY col_list]   [CLUSTER BY col_list     | [DISTRIBUTE BY col_list] [SORT BY col_list]   ]  [LIMIT number]

like和rlike 、and /or /not int、group by 、having(跟在group by 后)

hive (default)> select deptno, avg(sal) avg_sal from emp group by deptno having avg_sal > 2000; 

join/left join/right join/full join

排序

全局排序: order by 最终用一个reduceTask完成排序

局部排序:sort by 使用多个reduceTask,reduceTask中有序,全局没有序

分桶查询: distribute by (控制哪个行到特定的reduceTask) 和sort by一起使用

hive (default)> set mapreduce.job.reduces=3;

hive (default)> insert overwrite local directory '/opt/module/data/distribute-result' select * from emp distribute by deptno sort by empno desc; 

前置条件: 多个reduceTask  set mapreduce.job.reduces= 

                   分桶规则:hash散列

cluster by: 当diistribute by和sort by字段相同时用 cluster by

七)分区表和分桶表

分区

一级分区

1)创建分区表

hive (default)> create table dept_partition( deptno int, dname string, loc string) partitioned by (day string) row format delimited fields terminated by '\t';

注意:分区字段不能是表中已经存在的数据,可以将分区字段看作表的伪列。 

2)加载数据

hive (default)> load data local inpath '/opt/module/hive/datas/dept_20200401.log' into table dept_partition partition(day='20200401'); 

3)查询

hive (default)> select * from dept_partition where day='20200401';

4)添加分区

hive (default)> alter table dept_partition add partition(day='20200404'); 

5)删除单分区

hive (default)> alter table dept_partition drop partition (day='20200406'); 

删除多分区

hive (default)> alter table dept_partition drop partition (day='20200404'), partition(day='20200405');

二级分区

1)建表语句

hive (default)> create table dept_partition2(  deptno int, dname string, loc string                )                partitioned by (day string, hour string) row format delimited fields terminated by '\t'; 

2)加载数据

hive (default)> load data local inpath '/opt/module/hive/datas/dept_20200401.log' into table dept_partition2 partition(day='20200401', hour='12');

3) 查询分区数据

hive (default)> select * from dept_partition2 where day='20200401' and hour='12'; 

4)将数据直接上传到分区目录上,让分区表和数据产生关联的三种方式

4.1)上传数据后修复

hive (default)> dfs -mkdir -p  /user/hive/warehouse/mydb.db/dept_partition2/day=20200401/hour=13;

查询数据(查询不到刚上传的数据)

hive (default)> select * from dept_partition2 where day='20200401' and hour='13'; 

hive> msck repair table dept_partition2; 

再次查询

hive (default)> select * from dept_partition2 where day='20200401' and hour='13'; 

4.2)上传数据后添加分区

上传数据

hive (default)> dfs -mkdir -p  /user/hive/warehouse/mydb.db/dept_partition2/day=20200401/hour=14;

添加分区

 hive (default)> alter table dept_partition2 add partition(day='201709',hour='14'); 

查询数据

hive (default)> select * from dept_partition2 where day='20200401' and hour='14'; 

4.3)创建文件夹之后load数据到分区

创建目录

hive (default)> dfs -mkdir -p  /user/hive/warehouse/mydb.db/dept_partition2/day=20200401/hour=15;

上传数据

hive (default)> load data local inpath '/opt/module/hive/datas/dept_20200401.log' into table  dept_partition2 partition(day='20200401',hour='15');

查询数据

hive (default)> select * from dept_partition2 where day='20200401' and hour='15'; 

动态分区

(1)开启动态分区功能(默认true,开启)

hive.exec.dynamic.partition=true

(2)设置为非严格模式(动态分区的模式,默认strict,表示必须指定至少一个分区为静态分区,nonstrict模式表示允许所有的分区字段都可以使用动态分区。)

hive.exec.dynamic.partition.mode=nonstrict

(3)在所有执行MR的节点上,最大一共可以创建多少个动态分区。默认1000

hive.exec.max.dynamic.partitions=1000

(4)在每个执行MR的节点上,最大可以创建多少个动态分区。该参数需要根据实际

的数据来设定。比如:源数据中包含了一年的数据,即day字段有365个值,那么该参数就需要设置成大于365,如果使用默认值100,则会报错。 

hive.exec.max.dynamic.partitions.pernode=100

(5)整个MR Job中,最大可以创建多少个HDFS文件。默认100000

hive.exec.max.created.files=100000 

(6)当有空分区生成时,是否抛出异常。一般不需要设置。默认false 

hive.error.on.empty.partition=false

2)案例实操 需求:将dept表中的数据按照地区(loc字段),插入到目标表dept_partition的相应分区中。

(1)创建目标分区表 

hive (default)> create table dept_partition_dy(id int, name string) partitioned by (loc int) row format delimited fields terminated by '\t';

2)设置动态分区

set hive.exec.dynamic.partition.mode = nonstrict; hive (default)> insert into table dept_partition_dy partition(loc) select deptno, dname, loc from dept; 

分桶表

分桶规则:根据结果可知:Hive的分桶采用对分桶字段的值进行哈希,然后除以桶的个数求余的方

式决定该条记录存放在哪个桶当中

1)建表

create table stu_buck(id int, name string) clustered by(id)  into 4 buckets row format delimited fields terminated by '\t';

注意的事项

(1)reduce的个数设置为-1,让Job自行决定需要用多少个reduce或者将reduce的个

数设置为大于等于分桶表的桶数

(2)从hdfs中load数据到分桶表中,避免本地文件找不到问题 

(3)不要使用本地模式 

2)导表

hive(default)>insert into table stu_buck select * from student_insert; 

抽样查询

语法: TABLESAMPLE(BUCKET x OUT OF y)  

hive (default)> select * from stu_buck tablesample(bucket 1 out of 4 on id); 

注意:x的值必须小于等于y的值

八) 函数

1)NVL( value,default_value)

如果value为NULL,则NVL函数返回default_value的值,否则返回value的值,如果两个参数都为NULL ,则返回NULL

hive (default)> select comm,nvl(comm, -1) from emp;

OK comm    _c1 

NULL    -1.0

300.0   300.0

500.0   500.0

NULL    -1.0

2) case when then else end

查询语句

select   dept_id,   sum(case sex when '男' then 1 else 0 end) male_count,   sum(case sex when '女' then 1 else 0 end) female_count from emp_sex group by dept_id; 

3)行转列

1)相关函数

CONCAT(string A/col, string B/col…):返回输入字符串连接后的结果,支持任意个输入字符串;

CONCAT_WS(separator, str1, str2,...):它是一个特殊形式的 CONCAT()。第一个参数剩余参数间的分隔符。分隔符可以是与剩余参数一样的字符串。如果分隔符是 NULL,返回值也将为 NULL。这个函数会跳过分隔符参数后的任何 NULL 和空字符串。分隔符将被加到被连接的字符串之间;

注意: CONCAT_WS must be "string or array<string>

COLLECT_SET(col):函数只接受基本数据类型,它的主要作用是将某字段的值进行去重汇总,产生Array类型字段。 

SELECT t1.c_b, CONCAT_WS("|",collect_set(t1.name)) FROM ( SELECT NAME, CONCAT_WS(',',constellation,blood_type) c_b FROM person_info )t1 GROUP BY t1.c_b 

结果:白羊座,A       孙悟空|猪八戒 

列转行

1)函数说明 EXPLODE(col)

将hive一列中复杂的Array或者Map结构拆分成多行。

LATERAL VIEW 用法:LATERAL VIEW udtf(expression) tableAlias AS columnAlias 解释:用于和split, explode等UDTF一起使用,它能够将一列数据拆成多行数据,在此基础上可以对拆分后的数据进行聚合。 

原始数据

《疑犯追踪》 悬疑,动作,科幻,剧情

《Lie to me》 悬疑,警匪,动作,心理,剧情

《战狼2》 战争,动作,灾难

目标

《疑犯追踪》 悬疑

《疑犯追踪》 动作

《疑犯追踪》 科幻

《疑犯追踪》 剧情

《Lie to me》 悬疑

《Lie to me》 警匪

《Lie to me》 动作

《Lie to me》 心理

《Lie to me》 剧情

《战狼2》 战争

《战狼2》 动作

《战狼2》 灾难 

SELECT movie, category_name FROM movie_info lateral VIEW explode(split(category,",")) movie_info_tmp AS category_name;

窗口函数

over()

数据准备

 需求

(1)查询在2017年4月份购买过的顾客及总人数

(2)查询顾客的购买明细及月购买总额

(3)上述的场景, 将每个顾客的cost按照日期进行累加

(4)查询每个顾客上次的购买时间

(5)查询前20%时间的订单信息 

1)创建表

create table business( name string, orderdate string, cost int ) ROW FORMAT DELIMITED FIELDS TERMINATED BY ',';

load data local inpath "/data/business.txt" into table business; 

(1) 查询在2017年4月份购买过的顾客及总人数 

select name,count(*) over () from business where substring(orderdate,1,7) = '2017-04' group by name;

2)查询顾客的购买明细及月购买总额 

select name,orderdate,cost,sum(cost) over(partition by month(orderdate)) from business;

 (3) 将每个顾客的cost按照日期进行累加 

LAG(col,n,DEFAULT) 用于统计窗口内往上第n行值

col 列

n往上第几行

default 默认

 (4) 查看顾客上次的购买时间 

select name,orderdate,cost, lag(orderdate,1,'1900-01-01') over(partition by name order by orderdate ) as time1, lag(orderdate,2) over (partition by name order by orderdate) as time2 from business;

(5) 查询前20%时间的订单信息 

ntile(5),将数据分5片取前一片就是20%

select * from (  select name,orderdate,cost, ntile(5) over(order by orderdate) sorted  from business ) t where sorted = 1; 

Rank

1) RANK()排序相同时会重复,总数不会变

2)DENSE_RANK() 排序相同时会重复,总数会减少

3)ROW_NUMBER() 会根据顺序计算

select name, subject, score, rank() over(partition by subject order by score desc) rp, dense_rank() over(partition by subject order by score desc) drp, row_number() over(partition by subject order by score desc) rmp from score;

 name subject score rp drp rmp

cc 数学 95 1 1 1

yy 数学 95  1 1 2

leilei 数学 85 3 2 3

lili 数学 56 4 3 4 

自定义函数

  (1) UDF(User-Defined-Function) 一进一出

  (2) UDAF(User-Defined Aggregation Function) 聚集函数,多进一出

  (3) UDTF(User-Defined Table-Generating Functions) 一进多出

九)压缩和存储

压缩格式算法文件扩展名是否可切分
DefaultDEFAULT.default
gzipDEFAULT.gz
bzip2bzip2.bz2
lzoLZO.lzo
snappysnappy.snappy

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值