hive-sql学习及笔记

hive 笔记

hive-site.xml 配置文件

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>
    <!--配置mysql 连接-->
	<property>
		<name>javax.jdo.option.ConnectionURL</name>
		<value>jdbc:mysql://hadoop100:3306/metastore?createDatabaseIfNotExist=true</value>
		<description>JDBC connect string for a JDBC metastore</description>
	</property>
    <!--配置mysql 连接类-->
	<property>
		<name>javax.jdo.option.ConnectionDriverName</name>
		<value>com.mysql.cj.jdbc.Driver</value>
		<description>Driver class name for a JDBC metastore</description>
	</property>
    <!--配置mysql 账号-->
	<property>
		<name>javax.jdo.option.ConnectionUserName</name>
		<value>root</value>
		<description>username to use against metastoredatabase</description>
	</property>
    <!--配置mysql 密码-->
	<property>
		<name>javax.jdo.option.ConnectionPassword</name>
		<value>****</value>
		<description>password to use against metastore database</description>
	</property>
    <!--hive 客户端启动头打印-->
	<property>
		<name>hive.cli.print.header</name>
		<value>true</value>
	</property>
    <!--hive 客户端显示当前db-->
	<property>
		<name>hive.cli.print.current.db</name>
		<value>true</value>
	</property>
    <!--配置hive 的路径-->
	<property>
		<name>hive.metastore.warehouse.dir</name>
		<value>/user/hive/warehouse</value>
		<description>location of default database ofr the warehouse</description>
	</property>
</configuration>

常用交互命令

// 1. 查看帮助
bin/hive -help
// 2. 不进入hive的交互窗口执行sql语句
bin/hive -e "select * from student;"
// 3. 执行脚本中SQL语句
bin/hive -f /opt/data/hive/hivef.sql
// 4. 执行文件sql 语句,将结果写入到文件中
bin/hive -f /opt/data/hive/hivef.sql /opt/data/hive/hive_result.txt

其他命令操作

// 1. hive cli 窗口查看 hdfs 文件系统
hive> dfs -ls /;
// 2. cli 查看本地文件系统
hive> ! ls /opt/module/datas;
// 3. 查看hive中输入的所有历史命令
cat .hivehistory // 当前用户根目录

参数配置方式

// 1. 查看当前所有配置信息
hive>set;
// 2. 配置优先级
1. 配置文件
	1. 默认配置文件——hive-default.xml
	2. 用户自定义配置文件—— hive-site.xml
	3. 用户自定义配置会覆盖默认配置,
2. 命令行
	1. 只对当前启动hive 有效

类型

特殊类型

请添加图片描述

类型转化
  1. 隐式类型转换规则如下:

    1. 任何整数类型都可以隐式地转换为一个范围更广的类型,如 TINYINT 可以转换int,
    2. 所有整数类型,FLOAT和STRING类型都可以隐式转换为DOUBLE
    3. TINYINT、SMALLINT、INT都可以转换为FLOAT
    4. BOOLEAN 不可以转换为任何其他类型
  2. 可以使用CAST 操作进行数据类型转换

    CAST(‘1’ AS INT) 如果强转失败,变为null

DDL 数据定义

创建数据库

// 1. 创建数据库
create database db_hive;
// 2. if not exists 判断 (标准写法)
create database if not exists db_hive;
// 3. 指定 数据库在 HDFS 存放的位置
create database db_hive2 location '/db_hive2.db';

查询数据库

// 1. 显示数据库
show databases;
// 2. 过滤显示查询数据库
show databases like 'db_hive*'
// 3. 查看数据库信息
desc database db_hive
// 4. 显示数据库详细信息
desc database extended db_hive;
// 5. 切换数据库
use db_hive;
// 6. 修改数据库(`数据库的其他元数据信息都是不可更改的,包括数据库名和数据库所在目录位置`)
alter database hive set dbproperties('createtime'='20210902')

删除数据库

// 1. 删除空的数据
drop database db_hive2;
// 2. if exists 判断数据库时是否存在删除
drop database if exists db_hive2;
// 3. 数据库不为空,采用`cascade`强制删除
drop database db_hive cascade;

创建表

//1. 建表语法
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]

// 2. 对建表说明1CREATE TABLE 创建一个指定名字的表。如果相同名字的表已经存在,则抛出
异常;用户可以用 IF NOT EXISTS 选项来忽略这个异常。
(2)EXTERNAL 关键字可以让用户创建一个外部表,在建表的同时指定一个指向实际
数据的路径(LOCATION),Hive 创建内部表时,会将数据移动到数据仓库指向的路
径;若创建外部表,仅记录数据所在的路径,不对数据的位置做任何改变。在删除表的
时候,内部表的元数据和数据会被一起删除,而外部表只删除元数据,不删除数据。
(3COMMENT:为表和列添加注释。
(4)PARTITIONED BY 创建分区表
(5CLUSTERED BY 创建分桶表
(6)SORTED BY 不常用
(7ROW 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 上的存储位置。
(10LIKE 允许用户复制现有的表结构,但是不复制数据。

管理表

默认创建的表都是管理表(内部表) 。 这种表hive 会控制着数据的生命周期。Hive 默认情况下会将这些表的数据存储在由配置项 hive.metastore.warehouse.dir(例如,/user/hive/warehouse)所定义的目录的子目录下。当我们 删除一个管理表时,Hive 也会删除这个表中数据。管理表不适合和其他工具共享数据

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

外部表,hive 会认为其完全拥有这份数据。删除该表并不会删除这份数据,不过描述表的元数据信息会被删除掉。

外部表和内部表的使用场景

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

//1. 创建部门表
create external table if not exists default.dept(
deptno int,
dname string,
loc int
)
row format delimited fields terminated by '\t';
// 2. 创建员工表
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';
// 3. 查看创建的表
show tables;
// 4. 向外部表导入数据
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;
// 5. 查询结果
hive (default)> select * from emp;
hive (default)> select * from dept;
// 6. 查看表格式化数据
desc formatted dept;
管理表与外部表的互相转换
// 1. 查询表的类型
desc formatted dept;
// 2. 修改内部表为外部表
alter table student2 set tblproperties('EXTERNAL'='TRUE'); // 区分大小写,固定写法,TRUE OR FALSE
// 3. 查询表的类型
desc formatted student2;

分区表

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

请添加图片描述

// 1. 创建分区表语法
create table dept_partition (
deptno int,dname string ,loc string)
partitioned by (month string)
row format delimited fields terminated by '\t';

// 2. 加载数据到分区表中
load data local inpath 
'/opt/data/hive-3.1.2/data/dept.txt' into table default.dept_partition 
partition(month='201709');
load data local inpath 
'/opt/data/hive-3.1.2/data/dept.txt' into table default.dept_partition 
partition(month='201708');
load data local inpath '/opt/data/hive-3.1.2/data/dept.txt' into table default.dept_partition partition(month='201707');

// 3. 单分区查询
select * from dept_partition where month='201709';
// 4. 多分区联合查询
select * from dept_partition where month='201709'
union select * from dept_partition where month='201708';
// 5. 增加一个分区
alter table dept_partition add partition(month='201706');
// 6. 增加多个分区
alter table dept_partition add partition(month='201705') partition(month='201705');
// 7. 删除一个分区
alter table dept_partition drop partition(month='201704');
// 8. 删除多个分区
alter table dept_partition drop partition(month='201704'),partition(month='201706');
// 9. 查看分区表有多少分区
show partitions dept_partition;
// 10. 查看分区表结构
desc formatted dept_partition;
··1. 如果碰见异常

reason: 没有开启分区
set hive.exec.dynamic.partition=true; 
set hive.exec.dynamic.partition.mode=nonstrict;
分区表注意事项
// 1. 创建二级分区表
create table dept_partition2(deptno int,dname string,loc string)
partitioned by (month string,day string)
row format delimited fields terminated by '\t';
// 2. 加载数据到二级分区表中
load data local inpath 
'/opt/data/hive-3.1.2/data/dept.txt' into table
default.dept_partition2 partition(month='201709', day='13');
// 3. 查看分区数据
select * from dept_partition2 where 
month='201709' and day='13';

// 4. 数据直接上传分区目录,让分区表和数据产生关联的三种方式
 1. 上传数据后修复
 dfs -mkdir -p
/user/hive/warehouse/dept_partition2/month=201709/day=12;
/ a  把文件放到对应的文件夹中
dfs -put /opt/module/datas/dept.txt 
/user/hive/warehouse/dept_partition2/month=201709/day=12;
/  b  修复数据
select * from dept_partition2 where 
month='201709' and day='12';
/ c 查询数据
select * from dept_partition2 where 
month='201709' and day='12';

 2. 上传数据后添加分区
/ 上传数据
select * from dept_partition2 where 
month='201709' and day='12';
select * from dept_partition2 where 
month='201709' and day='12';
/ 添加分区
alter table dept_partition2 add 
partition(month='201709',
day='11');

/ 查询


  创建文件夹后load数据到分区
/ 创建目录
alter table dept_partition2 add 
partition(month='201709',
day='11');
/ 上传数据
load data local inpath 
'/opt/module/datas/dept.txt' into table
dept_partition2 partition(month='201709',day='10');

修改表

// 1. 重命名表
alter table dept_partion2 rename to dept_partition3;
增加/修改/替换列信息
// 1. 查询表结构
desc dept_partition;
// 2. 添加列
alter table dept_partition add columns (deptdesc string);
// 3. 更新列
alter table dept_partition change column deptdes desc int;
// 删除修改列,是成功的,但是数据无法转换过来会变成null
// 替换列,replace 是替换表中所有字段
alter table dept_partition replace columns(deptno string,dname string, loc string);
删除表
drop table dept_partition;

DML 数据操作

向表中装载数据load

请添加图片描述

// 1. 创建一张表
create table student (id string,name string) row format delimited fields terminated by '\t';
// 2. 加载本地文件到hive
load data local inpath '/opt/module/datas/student.txt' into table default.student;
// 3. 上传文件到hdsf
dfs -put /opt/module/datas/student.txt /usr/lan/hive;
// 3.1 加载HDFS上数据
load data inpath 
'/user/lan/hive/student.txt' into table default.student;
// 3.2 加载数据覆盖表中已有的数据
load data inpath 
'/user/lan/hive/student.txt' into table default.student;
通过查询语句向表中插入数据Insert
// 创建一张分区表
load data inpath 
'/user/atguigu/hive/student.txt' into table default.student;
// 基本插入数据
insert into table student 
partition(month='201709') values(1,'wangwu');
// 3. 基本模式插入(根据单张表查询结果)
insert overwrite table student 
partition(month='201708')
 select id, name from student where month='201709';
 
// 4. 多插入模式
from student insert  overwrite table student 
partition(month='201708')
 select id, name from student where month='201709';
 
 // 5. 根据查询结果创建表
 create table if not exists student3 as select id,name from student;
 // 6. 创建表时通过location 指定加载数据路径
> create table if not exists student5(
 id int, name string
 )
 row format delimited fields terminated by '\t'
 location '/user/hive/warehouse/student5';
 
 // 7. import 数据到指定hive 表中
 import table student2_partition(month='201709')from '/usr/hive/warehouse/export/student';
 
 
数据导出
insert 导出
// 1. 将查询的数据导出到本地
insert overwrite local directory '/opt/module/datas/export/student' select * from student;

// 2. 将查询结果格式化导出到本地
> create table if not exists student5(
 id int, name string
 )
 row format delimited fields terminated by '\t'
 location '/user/hive/warehouse/student5';
 
 // 3. 将查询结果导出hdfs上
 > create table if not exists student5(
 id int, name string
 )
 row format delimited fields terminated by '\t'
 location '/user/hive/warehouse/student5';
 
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';
sqoop 导出
清楚表的数据
// 1. Truncate 只能删除管理表,不能删除外部表中数据
truncate table student;

查询

基本查询
// 1. 全表查询
select * from emp;
// 2. 选择特定列查询
select empno,ename from emp;

注意!!!:

  1. sql语言大小写敏感
  2. sql 可以写在一行或者多行
  3. 关键字不能缩写也不能分行
  4. 各子句一般要分行写
  5. 使用缩进提高语句的可读性
// 查询员工的薪水加1显示
select sal + 1 from emp;
常用函数
// 1. 求总行数
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_sql from emp;
// 5. avg
select avg(sal) avg_sql from emp;
// 6. limit 语句
select * from emp limit 5;
比较运算符

请添加图片描述

请添加图片描述

// 1. 查询薪水等于5000 的所有员工
select * from emp where sal = 5000;
// 2. 查询工资在 500 到 1000 的员工信息
 select * from emp where sal between 500 and 1000;

like 和 RLike
  1. 使用LIKE 运算类似的值
  2. 选择条件可以包含字符或数字
    1. % 代表零个或多个字符
    2. _ 代表一个字符
  3. RLike 是Hive 功能的扩展,可以通过java的正则表达式来指定匹配条件
// 开头2
select * from emp where sal LIKE '2%';
// 有2
select * from emp where sal RLIKE '[2]';

group by 与mysql一样
Having语句

请添加图片描述

join语句

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

  1. 内连接 join
  2. 左外连接 left join
  3. 右外连接 right join
  4. 满外连接 full join 将会返回所有表中符合where 语句条件的所有记录。但是字段没有符合条件的值,null 代替
笛卡尔积
  1. 笛卡尔集会在下面条件下产生
    1. 省略连接条件
    2. 连接条件无效
    3. 所有表中的所有行互相连接

select empno, dname from emp, dept;

排序
全局排序

Order by : 全局排序 ,一个Reducer

每个MapReduce 内部排序(Sort By)

虽然内部进行排序,但是对全局结果集来说不是排序。

  1. 设置reduce个数

    set mapreduce.job.reduces = 3;

  2. 查看设置reduce 个数

    set mapreduce.job.reduces;

分区排序(Distribute By)

Hive 要求DISTRIBUTE By 语句要写在sort by 语句之前

// 1. 先按照部门编号分区,再按照员工编号降序排序
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 的功能。但是排序只能是升序排序

select * from emp culuster by deptno;
select * from emp distribute by deptno sort by deptno;
分桶及抽样查询

分区针对的是数据的存储路径;分桶针对的是数据文件。

分区提供一个隔离数据和优化查询的便利方式。不过,并非所有的数据集都可形成合理 的分区,特别是之前所提到过的要确定合适的划分大小这个疑虑。

分桶是将数据集分解成更容易管理的若干部分的另一个技术

// 1. 创建分桶表
create table stu_buck(int int,name string)
clustered by (id) into 4 buckets
row format delimited fields terminated by '\t';
// 2. 导入数据
load data local inpath '/opt/module/datas/student.txt' into table stu_buck;

但是上述,并没有创建成功4个桶

// 1. 先建一个普通的表
create table stu(id int,name string)
row format delimited fields terminated by '\t';
// 2. 导入数据
load data local inpath '/opt/module/datas/student.txt' into table stu;
// 3. 清空stu_buck 表中数据
truncate table stu_buck;
// 4.  导入数据到分桶表,通过子查询的方式
insert into table stu_buck
select id,name from stu;

但是hdfs 还是只显示一个桶

// 1. 设置属性
set hive.enforce.bucketing=true
set mapreduce.job.reduces=-1
insert into table stu_buck select id,name from stu;
分桶抽样查询
select * from stu_buck tablesample(bucket 1 out of 4 on id);
// tablesample 是抽样语句,
// tablesample (bucket x out of y)
// y  必须是table 总 bucket 数的倍数 或者因子。
x 的值 必须小于等于 y 的值,不然会报错
其他常用查询函数
空字段赋值

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

 select nvl(comm,-1) 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)
// 4. datediff 两个时间相减
 select datediff('2019-06-29','2019-06-24');
CASE WHEN
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;

行转列

请添加图片描述

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

请添加图片描述

select
 movie,
 category_name
from
 movie_info lateral view explode(category) table_tmp as 
category_name;
窗口函数

请添加图片描述

数据

jack,2017-01-01,10
tony,2017-01-02,15
jack,2017-02-03,23
tony,2017-01-04,29
jack,2017-01-05,46
jack,2017-04-06,42
tony,2017-01-07,50
jack,2017-01-08,55
mart,2017-04-08,62
jack,2017-01-01,10
tony,2017-01-02,15
jack,2017-02-03,23
tony,2017-01-04,29
jack,2017-01-05,46
jack,2017-04-06,42
tony,2017-01-07,50
jack,2017-01-08,55
mart,2017-04-08,62
// 1. 创建表并导入数据
create table business (
name string,
orderdate string,
cost int)
row format delimited fields terminated by ',';

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


// 3. 查询在2017 年4月 购买过的顾客及总人数
select name,count(*) over ()
from business 
where substring(orderdate,1,7) = '2017-04'
group by name;

// 4. 查询顾客的购买明细及月购买总额
select name,orderdate ,cost,sum(cost) over(partition by month(orderdate)) from business;
// 5. 上述场景,要将cost 按照日志进行累加
select name,orderdate ,cost,sum(cost) over() as samplel,--所有行相加
sum(cost) over(partition by name) as sample2,--按 name 分组,组内
数据相加
sum(cost) over(partition by name order by orderdate) as sample3,--
按 name 分组,组内数据累加
sum(cost) over(partition by name order by orderdate rows between
UNBOUNDED PRECEDING and current row ) as sample4 ,--和 sample3 一,由起点到当前行的聚合
sum(cost) over(partition by name order by orderdate rows between 
1 PRECEDING and current row) as sample5, --当前行和前面一行做聚合
sum(cost) over(partition by name order by orderdate rows between
  1 PRECEDING AND 1 FOLLOWING ) as sample6,--当前行和前边一行及后面一sum(cost) over(partition by name order by orderdate rows between 
current row and UNBOUNDED FOLLOWING ) as sample7 --当前行及后面所
有行
from business;
// 6 查看顾客上次的购买时间
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;
// 7 查询前20%时间的订单信息
select * from (
    select aame,orderdate,cost,ntile(5) over (order by orderdate) sorted from business) t
    where sorted = 1
Rank
  1. 函数说明

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

    DENSE_RANK() 排序相同时会重复,总数会减少 ROW_NUMBER() 会根据顺序计算

//1 创建表并导入数据
create table score(
name string,
subject string, 
score int) 
row format delimited fields terminated by "\t";
load data local inpath '/opt/module/datas/score.txt' into table 
score;

// 计算每门学科成绩排名
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;

函数

// 1. 查看系统自带的函数
show functions;
// 2. 显示自带的函数的用法
desc fucntion upper;
// 3. 详细显示自带的函数的用法
desc function extended upper;

自定义函数,需要的查看官网文档,又不常用。

请添加图片描述

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值