Hive 学习
1.Hive是什么?
Hive是一个可以将sql翻译为MapReduce程序的工具
2.Hive使用方法
(1)在命令行执行sql语句:hive -e “use default;create table test_1(id int,name string)”
创建一个txt文件
vi /home/userinfo.txt //向txt文件中写入
use default;//使用默认
create table test_2(id int,name string,age int) row format delimited fields terminated by',';//创建表
load data local inpath '/home/userinfo.txt' into table test_2; //将本地文件写入test_2表中
3.Hadoop01上启动服务
在 /usr/local/src/hive-1.2.1/bin 下有一个服务:hiveserver2
进入bin目录下./hiveserver2
4.建表
表定义信息会被记录到hive的元数据中(mysql的hive库)
HDFS上的hive库目录中创建一个跟表名一致的文件夹
表目录中放入文件
create table test_1(id string,name string,age int) row format delimited fields terminated by ',';//创建表
desc test_1 ;//查看表结构
//创建一个文件,上传到hdfs对应的test_1表对应的目录下
vi test_1.txt;
hadoop fs -put test_1.txt /user/hive/warehouse/test_1;
select * from test_1;//显示test_1表
vi test_1.txt.1;
hadoop fs -put test_1.txt.1 /user/hive/warehouse/test_1;//将txt文件传到test_1表中
select * from test_1;
内部表和外部表(external)
1.建立内部表,若删除表 hdfs中的文件也会被删除。
create table t_2(id int,name string,salary bigint,add string) row format delimited fields terminated by ',' location '/aa/bb';//创建表
vi /home/salary.txt //编写txt文件
load data local inpath'/home/salary.txt' into table t_2 ;//将txt文件传入t_2中
select * from t_2;
2.外部表,删除表,表的元数据但表数据目录都不会被删掉。(external)
create external table t_3(id int,name string,salary bigint,add string) row format delimited fields terminated by ',' location '/aa/bb';
hadoop fs -put salary.txt /aa/bb/ //上传到hdfs上
hadoop fs -cat /aa/bb/salary.txt //查看一下文件
select * from t_3;
分区(Partitioned By)
create table test_4(ip string,url string,staylong int) partitioned by (day string) row format delimited fields terminated by ',';//创建一个表,分区day不能位于表字段中。
vi pv.data.2019-05-10 //写入分区中
load data local inpath '/home/pv.data.2019-05-10' into table test_4 partition(day='2019-05-10');//将文件内容写入test_4位于分区2019-05-10
//导入不同的目录中
vi pv.data.2019-05-11
load data local inpath '/home/pv.data.2019-05-11' into table test_4 partition(day='2019-05-11');
select * from test_4;
//分区查,查2019-05-11
select * from test_4 where day="2019-05-11";
//查看访问的人数
select distinct ip from test_4 where day="2019-05-11";//distinct是去重的意思,去重IP才可以查出访问人数
导入数据
将hive运行所在机器的本地磁盘上的文件导入表中
load data local inpath '/home/pv.data.2019-05-11' overwrite into table test_4 partition(day=”2019-05-12”);
//覆盖test_4表的day=”2019-05-12”分区 的数据,将2019-05-11导入进去
将hdfs中的文件导入表中
load data inpath '/user.data.2' into table t_1;
//不加local关键字,则是从hdfs的路径中移动文件到表目录中
从别的表查询数据后插入到一张新建表中
create table t_1_jz
as
select id,name from test_1;
从别的表查询数据后插入到一张已存在的表中
create table t_1_hd like test_1;
//从test_1中查询数据插入到t_1_hd中
insert into table t_1_hd select id,name,age from test_1 where name='ZDP';//插入name为‘ZDP’的数据
insert into table t_1_hd select id,name,age from test_1 where name like '%L';//插入‘%L’的数据
select * from t_1_hd;//查看一下表中是否含有数据
insert over write table t_1_hd select id,name,age from test_1 where name like 'l%';//over write会覆盖已存在的文件
关于分区数据导入另外一张表 连表
create table t_4_hd like test_4;//创建一个类似表
insert into t_4_hd partition(day=