一些Hive的常用操作总结。

DDL数据定义

创建数据库
create database db_hive;
//if not exists判断
create database if not exists db_hive;
//指定hdfs存储位置
create database db_hive2 location '/db_hive2.db';
查询数据库
show databases;
//过滤显示查询的数据库
show databases like 'db_hive*';
//显示数据库信息
desc database db_hive;
//显示数据库详细信息
desc database extended db_hive;
//切换当前数据库
use db_hive;
修改数据库
alter database hive set dbproperties('createtime'='20170830');

可以使用ALTER DATABASE命令为某个数据库的DBPROPERTIES设置键-值对属性值,来描述这个数据库的属性信息。数据库的其他元数据信息都是不可更改的,包括数据库名和数据库所在的目录位置。

删除数据库
//删除空数据库
drop database db_hive2;
//if not exists判断
drop database if exists db_hive2;
//数据库不为空,强制删除
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]

(1)CREATE TABLE 创建一个指定名字的表。如果相同名字的表已经存在,则抛出异常;用户可以用 IF NOT EXISTS 选项来忽略这个异常。
(2)EXTERNAL关键字可以让用户创建一个外部表,在建表的同时指定一个指向实际数据的路径(LOCATION),Hive创建内部表时,会将数据移动到数据仓库指向的路径;若创建外部表,仅记录数据所在的路径,不对数据的位置做任何改变。在删除表的时候,内部表的元数据和数据会被一起删除,而外部表只删除元数据,不删除数据。
(3)COMMENT:为表和列添加注释。
(4)PARTITIONED BY创建分区表
(5)CLUSTERED BY创建分桶表
(6)SORTED BY不常用
(7)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, …)]
用户在建表的时候可以自定义SerDe或者使用自带的SerDe。如果没有指定ROW FORMAT 或者ROW FORMAT DELIMITED,将会使用自带的SerDe。在建表的时候,用户还需要为表指定列,用户在指定表的列的同时也会指定自定义的SerDe,Hive通过SerDe确定表的具体的列的数据。
SerDe是Serialize/Deserilize的简称,目的是用于序列化和反序列化。
(8)STORED AS指定存储文件类型
常用的存储文件类型:SEQUENCEFILE(二进制序列文件)、TEXTFILE(文本)、RCFILE(列式存储格式文件)
如果文件数据是纯文本,可以使用STORED AS TEXTFILE。如果数据需要压缩,使用 STORED AS SEQUENCEFILE。
(9)LOCATION :指定表在HDFS上的存储位置。
(10)LIKE允许用户复制现有的表结构,但是不复制数据。

管理表
//普通创建表
create table if not exists student2(
id int, name string
)
row format delimited fields terminated by '\t'
stored as textfile
location '/user/hive/warehouse/student2';
//根据查询结果创建表
create table if not exists student3 as select id, name from student;
//根据已经存在的表结构创建表
create table if not exists student4 like student;
//查询表的类型
desc formatted student2;

外部表

内部表和外部表场景:

每天将收集到的网站日志定期流入HDFS文本文件。在外部表(原始日志表)的基础上做大量的统计分析,用到的中间表、结果表使用内部表存储,数据通过SELECT+INSERT进入内部表。

操作:分别创建部门和员工外部表,并向表中导入数据。

dept表

create external table if not exists default.dept(
deptno int,
dname string,
loc int
)
row format delimited fields terminated by '\t';

emp表

create external table if not exists default.emp(
empno int,
ename string,
job string,
mgr int,
hiredate string, 
sal double, 
comm double,
deptno int)
row format delimited fields terminated by '\t';

导入数据:

load data local inpath '/opt/module/data/dept.txt' into table default.dept;
load data local inpath '/opt/module/data/emp.txt' into table default.emp;

查询结果

select * from emp;
select * from dept;

管理表与外部表的互相转换

修改内部表student2为外部表

alter table student2 set tblproperties('EXTERNAL'='TRUE');

修改外部表student2为内部表

alter table student2 set tblproperties('EXTERNAL'='FALSE');

注意:(‘EXTERNAL’=‘TRUE’)和(‘EXTERNAL’=‘FALSE’)为固定写法,区分大小写!

分区表

分区表实际上就是对应一个HDFS文件系统上的独立的文件夹,该文件夹下是该分区所有的数据文件。Hive中的分区就是分目录,把一个大的数据集根据业务需要分割成小的数据集。在查询时通过WHERE子句中的表达式选择查询所需要的指定的分区,这样的查询效率会提高很多。

分区表基本操作

引入分区表(需要根据日期对日志进行管理):

/user/hive/warehouse/log_partition/20170702/20170702.log
/user/hive/warehouse/log_partition/20170703/20170703.log
/user/hive/warehouse/log_partition/20170704/20170704.log

创建分区表语法:

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

加载数据到分区表中:

load data local inpath '/opt/module/datas/dept.txt' into table default.dept_partition partition(month='201709');
load data local inpath '/opt/module/datas/dept.txt' into table default.dept_partition partition(month='201708');
load data local inpath '/opt/module/datas/dept.txt' into table default.dept_partition partition(month='201707);

查询分区表中数据:

//单分区查询
select * from dept_partition where month='201709';
//多分区联合查询
select * from dept_partition where month='201709'
              union
              select * from dept_partition where month='201708'
              union
              select * from dept_partition where month='201707';

增加分区:

//添加单个分区
alter table dept_partition add partition(month='201706') ;
//同时创建多个分区
alter table dept_partition add partition(month='201705') partition(month='201704');

删除分区:

//删除单个分区
alter table dept_partition drop partition (month='201704');
//同时删除多个分区
alter table dept_partition drop partition (month='201705'), partition (month='201706');

查看分区表有多少分区:

show partitions dept_partition;

创建二级分区表

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

加载数据到二级分区表:

load data local inpath '/opt/module/datas/dept.txt' into table
 default.dept_partition2 partition(month='201709', day='13');

查询分区数据:

select * from dept_partition2 where month='201709' and day='13';
修改表

重命名表:

alter table dept_partition2 rename to dept_partition3;

更新列:

ALTER TABLE table_name CHANGE [COLUMN] col_old_name col_new_name column_type [COMMENT col_comment] [FIRST|AFTER column_name]
//栗子:
alter table dept_partition change column deptdesc desc int;

添加和替换列:

ALTER TABLE table_name ADD|REPLACE COLUMNS (col_name data_type [COMMENT col_comment], ...) 
//添加列
alter table dept_partition add columns(deptdesc string);
//替换列
alter table dept_partition replace columns(deptno string, dname string, loc string);
删除表
drop table dept_partition;

DML数据操作

数据导入

向表中装载数据(Load)

load data [local] inpath '/opt/module/datas/student.txt' [overwrite] | into table student [partition (partcol1=val1,)];

(1)load data:表示加载数据
(2)local:表示从本地加载数据到hive表;否则从HDFS加载数据到hive表
(3)inpath:表示加载数据的路径
(4)overwrite:表示覆盖表中已有数据,否则表示追加
(5)into table:表示加载到哪张表
(6)student:表示具体的表
(7)partition:表示上传到指定分区

栗子:

  1. 创建表:
create table student(id string, name string) row format delimited fields terminated by '\t';
  1. 加载本地文件到hive
load data local inpath '/opt/module/datas/student.txt' into table default.student;
  1. 加载HDFS文件到hive中上传文件到HDFS
dfs -put /opt/module/datas/student.txt /user/atguigu/hive;
//加载HDFS上数据
load data inpath '/user/atguigu/hive/student.txt' into table default.student;
  1. 加载数据覆盖表中已有的数据上传文件到HDFS
dfs -put /opt/module/datas/student.txt /user/atguigu/hive;
//加载数据覆盖表中已有的数据
load data inpath '/user/atguigu/hive/student.txt' overwrite into table default.student;

通过查询语句向表中插入数据(Insert)

  1. 创建一张分区表
create table student(id int, name string) partitioned by (month string) row format delimited fields terminated by '\t';
  1. 基本插入数据
insert into table  student partition(month='201709') values(1,'wangwu');
  1. 基本模式插入(根据单张表查询结果)
insert overwrite table student partition(month='201708')
             select id, name from student where month='201709';
  1. 多插入模式(根据多张表查询结果)
from student
              insert overwrite table student partition(month='201707')
              select id, name where month='201709'
              insert overwrite table student partition(month='201706')
              select id, name where month='201709';

查询语句中创建表并加载数据(As Select)

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

创建表时通过Location指定加载数据路径

  1. 创建表,并指定在hdfs上的位置
create table if not exists student5(
              id int, name string
              )
              row format delimited fields terminated by '\t'
              location '/user/hive/warehouse/student5';
  1. 上传数据到hdfs上
dfs -put /opt/module/datas/student.txt  /user/hive/warehouse/student5;

Import数据到指定Hive表中

import table student2 partition(month='201709') from
 '/user/hive/warehouse/export/student';
数据导出

Insert导出

  1. 将查询的结果导出到本地
insert overwrite local directory '/opt/module/datas/export/student'
            select * from student;
  1. 将查询的结果格式化导出到本地
insert overwrite local directory '/opt/module/datas/export/student1'
           ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t'             
select * from student;
  1. 将查询的结果导出到HDFS上(没有local)
insert overwrite directory '/user/atguigu/student2'
             ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t' 
             select * from student;

Hadoop命令导出到本地

dfs -get /user/hive/warehouse/student/month=201709/000000_0
/opt/module/datas/export/student3.txt;

Hive Shell 命令导出

bin/hive -e 'select * from default.student;' >
 /opt/module/datas/export/student4.txt;

Export导出到HDFS上

export table default.student to   '/user/hive/warehouse/export/student';

清除表中数据(Truncate)

truncate table student;
//注意:Truncate只能删除内部表,不能删除外部表中数据

查询

基本查询(Select…From)
//全表查询
select * from emp;
//特定列查询
select empno, ename from emp;
列别名
select ename AS name, deptno dn from emp;
1.重命名一个列
2.便于计算
3.紧跟列名,也可以在列名和别名之间加入关键字‘AS
算术运算符
运算符描述
A+BA和B 相加
A-BA减去B
A*BA和B 相乘
A/BA除以B
A%BA对B取余
A&BA和B按位取与
A|BA和B按位取或
A^BA和B按位取异或
~AA按位取反

查询出所有员工的薪水后加1显示。

select sal +1 from emp;
常用函数
//1.求总行数(count)
select count(*) cnt from emp;
//2.求工资的最大值(max)
select max(sal) max_sal from emp;
//3.求工资的最小值(min)
select min(sal) min_sal from emp;
//4.求工资的总和(sum)
select sum(sal) sum_sal from emp; 
//5.求工资的平均值(avg)
select avg(sal) avg_sal from emp;
Limit语句

典型的查询会返回多行数据。LIMIT子句用于限制返回的行数

select * from emp limit 5;
Where语句
1.使用WHERE子句,将不满足条件的行过滤掉
2WHERE子句紧随FROM子句
select * from emp where sal >1000;
操作符支持的数据类型描述
A=B基本数据类型如果A等于B则返回TRUE,反之返回FALSE
A<=>B基本数据类型如果A和B都为NULL,则返回TRUE,其他的和等号(=)操作符的结果一致,如果任一为NULL则结果为NULL
A<>B, A!=B基本数据类型A或者B为NULL则返回NULL;如果A不等于B,则返回TRUE,反之返回FALSE
A<B基本数据类型A或者B为NULL,则返回NULL;如果A小于B,则返回TRUE,反之返回FALSE
A<=B基本数据类型A或者B为NULL,则返回NULL;如果A小于等于B,则返回TRUE,反之返回FALSE
A>B基本数据类型A或者B为NULL,则返回NULL;如果A大于B,则返回TRUE,反之返回FALSE
A>=B基本数据类型A或者B为NULL,则返回NULL;如果A大于等于B,则返回TRUE,反之返回FALSE
A [NOT] BETWEEN B AND C基本数据类型如果A,B或者C任一为NULL,则结果为NULL。如果A的值大于等于B而且小于或等于C,则结果为TRUE,反之为FALSE。如果使用NOT关键字则可达到相反的效果。
A IS NULL所有数据类型如果A等于NULL,则返回TRUE,反之返回FALSE
A IS NOT NULL所有数据类型如果A不等于NULL,则返回TRUE,反之返回FALSE
IN(数值1, 数值2)所有数据类型使用 IN运算显示列表中的值
A [NOT] LIKE BSTRING 类型B是一个SQL下的简单正则表达式,如果A与其匹配的话,则返回TRUE;反之返回FALSE。B的表达式说明如下:‘x%’表示A必须以字母‘x’开头,‘%x’表示A必须以字母’x’结尾,而‘%x%’表示A包含有字母’x’,可以位于开头,结尾或者字符串中间。如果使用NOT关键字则可达到相反的效果。
A RLIKE B, A REGEXP BSTRING 类型B是一个正则表达式,如果A与其匹配,则返回TRUE;反之返回FALSE。匹配使用的是JDK中的正则表达式接口实现的,因为正则也依据其中的规则。例如,正则表达式必须和整个字符串A相匹配,而不是只需与其字符串匹配。

操作符同样可以用于JOIN…ON和HAVING语句中。

//(1)查询出薪水等于5000的所有员工
select * from emp where sal =5000;
//(2)查询工资在500到1000的员工信息
select * from emp where sal between 500 and 1000;
//(3)查询comm为空的所有员工信息
select * from emp where comm is null;
//(4)查询工资是1500或5000的员工信息
select * from emp where sal IN (1500, 5000);
Like和RLike

1)使用LIKE运算选择类似的值
2)选择条件可以包含字符或数字: % 代表零个或多个字符(任意个字符)。_ 代表一个字符。
3)RLIKE子句是Hive中这个功能的一个扩展,其可以通过Java的正则表达式这个更强大的语言来指定匹配条件。

//1)查找以2开头薪水的员工信息
 select * from emp where sal LIKE '2%';
//(2)查找第二个数值为2的薪水的员工信息
 select * from emp where sal LIKE '_2%';
//(3)查找薪水中含有2的员工信息
 select * from emp where sal RLIKE '[2]';
逻辑运算符(And/Or/Not)
操作符含义
AND逻辑并
OR逻辑或
NOT逻辑否
//(1)查询薪水大于1000,部门是30
select * from emp where sal>1000 and deptno=30;
//(2)查询薪水大于1000,或者部门是30
select * from emp where sal>1000 or deptno=30;
//(3)查询除了20部门和30部门以外的员工信息
select * from emp where deptno not IN(30, 20);
Group By语句

GROUP BY语句通常会和聚合函数一起使用,按照一个或者多个列队结果进行分组,然后对每个组执行聚合操作。

//(1)计算emp表每个部门的平均工资
select t.deptno, avg(t.sal) avg_sal from emp t group by t.deptno;
//(2)计算emp每个部门中每个岗位的最高薪水
select t.deptno, t.job, max(t.sal) max_sal from emp t group by t.deptno, t.job;
Having语句

having与where不同点

(1)where针对表中的列发挥作用,查询数据;having针对查询结果中的列发挥作用,筛选数据。
(2)where后面不能写聚合函数,而having后面可以使用聚合函数。
(3)having只用于group by分组统计语句。

//(1)求每个部门的平均薪水大于2000的部门
//求每个部门的平均工资
select deptno, avg(sal) from emp group by deptno;
//求每个部门的平均薪水大于2000的部门
select deptno, avg(sal) avg_sal from emp group by deptno having avg_sal > 2000;
Join语句

等值Join

Hive支持通常的SQL JOIN语句,但是只支持等值连接,不支持非等值连接。

select e.empno, e.ename, d.deptno, d.dname from emp e join dept d
 on e.deptno = d.deptno;

表的别名

(1)使用别名可以简化查询。

(2)使用表名前缀可以提高执行效率。

select e.empno, e.ename, d.deptno from emp e join dept d on e.deptno
 = d.deptno;

内连接

内连接:只有进行连接的两个表中都存在与连接条件相匹配的数据才会被保留下来。

select e.empno, e.ename, d.deptno from emp e join dept d on e.deptno
 = d.deptno;

左外连接

JOIN操作符左边表中符合WHERE子句的所有记录将会被返回。

 select e.empno, e.ename, d.deptno from emp e left join dept d on e.deptno = d.deptno;

右外连接

JOIN操作符右边表中符合WHERE子句的所有记录将会被返回。

select e.empno, e.ename, d.deptno from emp e right join dept d on e.deptno = d.deptno;

满外连接

将会返回所有表中符合WHERE语句条件的所有记录。如果任一表的指定字段没有符合条件的值的话,那么就使用NULL值替代。

select e.empno, e.ename, d.deptno from emp e full join dept d on e.deptno = d.deptno;
笛卡尔积

产生:

(1)省略连接条件
(2)连接条件无效
(3)所有表中的所有行互相连接

select empno, dname from emp, dept;
连接谓词中不支持or
select 
            e.empno,
            e.ename,
            d.deptno
            from
            emp e 
            join
            dept d 
            on
            e.deptno=d.deptno or e.ename=d.dname;

FAILED: SemanticException [Error 10019]: Line 10:3 OR not supported in JOIN currently ‘dname’

排序

全局排序(Order By)

Order By:全局排序,一个Reducer

1.使用 ORDER BY 子句排序

ASC(ascend): 升序(默认)
DESC(descend): 降序

2.ORDER BY 子句在SELECT语句的结尾

1)查询员工信息按工资升序排列

select * from emp order by sal;

2)查询员工信息按工资降序排列

select * from emp order by sal desc;

分区排序(Distribute By)

Distribute By:类似MR中partition,进行分区,结合sort by使用。
注意,Hive要求DISTRIBUTE BY语句要写在SORT BY语句之前。

set mapreduce.job.reduces=3;
//先按照部门编号分区,再按照员工编号降序排序。
insert overwrite local directory '/opt/module/datas/distribute-result' select * from emp distribute by deptno sort by empno desc;
Cluster By

当distribute by和sorts by字段相同时,可以使用cluster by方式。

cluster by除了具有distribute by的功能外还兼具sort by的功能。但是排序只能是升序排序,不能指定排序规则为ASC或者DESC。

select * from emp cluster by deptno;
空字段赋值

NVL:给值为NULL的数据赋值,它的格式是NVL( string1, replace_with)。它的功能是如果string1为NULL,则NVL函数返回replace_with的值,否则返回string1的值,如果两个参数都为NULL ,则返回NULL。

1)如果员工的comm为NULL,则用-1代替

select nvl(comm,-1) from emp;

如果员工的comm为NULL,则用领导id代替

select nvl(comm,mgr) from emp;
时间类

1)date_format:格式化时间

select date_format('2019-06-29','yyyy-MM-dd');

2)date_add:时间跟天数相加

select date_add('2019-06-29',5);
select date_add('2019-06-29',-5);

3)date_sub:时间跟天数相减

select date_sub('2019-06-29',5);
select date_sub('2019-06-29 12:12:12',5);
select date_sub('2019-06-29',-5);

4)datediff:两个时间相减

select datediff('2019-06-29','2019-06-24');
select datediff('2019-06-24','2019-06-29');
select datediff('2019-06-24 12:12:12','2019-06-29');
select datediff('2019-06-24 12:12:12','2019-06-29 13:13:13');
CASE WHEN

1)数据准备

namedept_idsex
悟空A
大海A
宋宋B
凤姐A
婷姐B
婷婷B

2)需求:求出不同部门男女各多少人。结果如下:

A 2 1

B 1 2

3)创建本地emp_sex.txt,添加数据

4)创建hive表并导入数据

create table emp_sex(
name string, 
dept_id string, 
sex string) 
row format delimited fields terminated by "\t";
load data local inpath '/opt/module/data/emp_sex.txt' into table emp_sex;

5)按需求查询数据

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;
行转列

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

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

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

1)数据准备:

nameconstellationblood_type
孙悟空白羊座A
大海射手座A
宋宋白羊座B
猪八戒白羊座A
凤姐射手座A

2)需求:把星座和血型一样的人归类到一起。结果如下

射手座,A 大海|凤姐
白羊座,A 孙悟空|猪八戒
白羊座,B 宋宋

3)创建本地constellation.txt,导入数据

vim xxxx.txt
孙悟空 白羊座 A
大海 射手座 A
宋宋 白羊座 B
猪八戒 白羊座 A
凤姐 射手座 A

4)创建hive表并导入数据

create table person_info(
name string, 
constellation string, 
blood_type string) 
row format delimited fields terminated by "\t";

load data local inpath "/opt/module/data/person_info.txt" into table person_info;

按需求查询数据

select
    t1.base,
    concat_ws('|', collect_set(t1.name)) name
from
    (select
        name,
        concat(constellation, ",", blood_type) base
    from
        person_info) t1
group by
    t1.base;
列转行

EXPLODE(col):将hive一列中复杂的array或者map结构拆分成多行。

LATERAL VIEW

用法:LATERAL VIEW udtf(expression) tableAlias AS columnAlias

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

1)数据准备

moviecategory
《疑犯追踪》悬疑,动作,科幻,剧情
《Lie to me》悬疑,警匪,动作,心理,剧情
《战狼2》战争,动作,灾难

2)需求: 将电影分类中的数组数据展开。结果如下:

《疑犯追踪》 悬疑
《疑犯追踪》 动作
《疑犯追踪》 科幻
《疑犯追踪》 剧情
《Lie to me》 悬疑
《Lie to me》 警匪
《Lie to me》 动作
《Lie to me》 心理
《Lie to me》 剧情
《战狼2》 战争
《战狼2》 动作
《战狼2》 灾难

3)创建本地movie.txt,导入数据

《疑犯追踪》 悬疑,动作,科幻,剧情
《Lie to me》 悬疑,警匪,动作,心理,剧情
《战狼2》 战争,动作,灾难

4)创建hive表并导入数据

create table movie_info(
    movie string,
    category array<string>)
row format delimited fields terminated by "\t"
collection items terminated by ",";

load data local inpath "/opt/module/datas/movie.txt" into table movie_info;

5)按需求查询数据

select
    movie,
    category_name
from
    movie_info lateral view explode(category) table_tmp as category_name;
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值