1. 程式人生 > >學習hive權威指南

學習hive權威指南

目錄:

ETL介紹
大資料平臺架構概述
系統資料流動
hive概述
hive在hadoop生態系統中
hive體系結構
hive安裝及使用
hive客戶端的基本語句
hive在HDFS檔案系統中的結構
修改hive元資料儲存的資料庫
hive操作命令
hive常用配置
hive常用的Linux命令選項
hive三種表的建立方式
hive外部表
hive臨時表
hive分割槽表
hive桶表
hive分析函式
hive資料的匯入和匯出
hive常見的hql語句
hive和MapReduce的相關執行引數
hive自定義UDF函式
hiveserver2與jdbc客戶端
hive執行模式與虛擬列
【案列一】日誌資料檔案分析
【案列二】hive shell 自動化載入資料
hive優化
hadoop & hive壓縮
hive儲存格式
hive總結&應用場景

一、ETL介紹:

在這裡插入圖片描述
資料抽取:把不同的資料來源資料抓取過來,存到某個地方
  資料清洗:過濾那些不符合要求的資料或者修正資料之後再進行抽取
    不完整的資料:比如資料裡一些應該有的資訊缺失,需要補全後再寫入資料倉庫
    錯誤的資料:比如字串資料後面有一個回車操作、日期格式不正確、日期越界等,需要修正之後再抽取
    重複的資料:重複資料記錄的所有欄位,需要去重
  資料轉換:不一致的資料轉換,比如同一個供應商在結算系統的編碼是XX0001,而在CRM中編碼是YY0001,統一編碼 實現有多種方法:
1、藉助ETL工具(如Oracle的OWB、SQL Server的DTS、SQL Server的SSIS服務、Informatic等等)實現
  OWB:Oracle Warehouse Builder
  DTS:Data Transformation Service
  SSIS:SQL Server Integration Services
2、SQL方式實現
3、ETL工具和SQL相結合-----》間接引出hive
  藉助工具可以快速的建立起ETL工程,遮蔽了複雜的編碼任務,提高了速度,降低了難度,但是缺少靈活性。
  SQL的方法優點是靈活,提高ETL執行效率,但是編碼複雜,對技術要求比較高。
  第三種是綜合了前面二種的優點,會極大地提高ETL的開發速度和效率

**

二、大資料平臺架構概述:

**
在這裡插入圖片描述
資料抽取:Canal/Sqoop(主要解決資料庫資料接入問題)、還有大量的資料採用Flume解決方案
  資料儲存:HDFS(檔案儲存)、HBase(KV儲存)、Kafka(訊息快取)
  排程:採用了Yarn的統一排程以及Kubernetes的基於容器的管理和排程的技術
  計算分析:MR、HIVE、Storm、Spark、Kylin以及深度學習平臺比如Caffe、Tensorflow等等
  應用平臺:互動分析sql,多維分析:時間、地域等等,
  視覺化:資料分析tableau,阿里datav、hcharts、echarts
  資料應用就是指資料的業務

**

三、系統資料流動:

**
在這裡插入圖片描述
四、hive概述:
在這裡插入圖片描述
由Facebook開源用於解決海量結構化日誌的資料統計,後稱為Apache Hive為一個開源專案
  結構化資料:資料型別,欄位,value—》hive
  非結構化資料:比如文字、圖片、音訊、視訊—》會有非關係型資料庫儲存,或者轉換為結構化
  結構化日誌資料:伺服器生成的日誌資料,會以空格或者指表符分割的資料,比如:apache、nginx等等

在這裡插入圖片描述
Hive 是一個基於 Hadoop 檔案系統之上的資料倉庫架構,儲存用hdfs,計算用mapreduce
Hive 可以理解為一個工具,不存在主從架構,不需要安裝在每臺伺服器上,只需要安裝幾臺就行了
hive還支援類sql語言,它可以將結構化的資料檔案對映為一張資料庫表,並提供簡單的SQL查詢功能
hive有個預設資料庫:derby,預設儲存元資料—》後期轉換成關係型資料庫儲存mysql
  hive的版本:apache-hive-1.2.1 、hive-0.13.1-cdh5.3.6
  https://github.com/apache/ 主要檢視版本的依賴
下載地址:
  apache的:http://archive.apache.org/dist/hive/
  cdh的:http://archive.cloudera.com/cdh5/cdh/5/
sql on hadoop的框架:
hive–》披著sql外衣的map-reduce
impala–》查詢引擎,適用於互動式的實時處理場景
presto–》分散式的sql查詢引擎,適用於實時的資料分析
spark sql
等等。。。。
詳細瞭解sql on hadoop請訪問博主的部落格:

https://blog.csdn.net/qq_35036995/article/details/80297129

五、Hive在Hadoop生態體系中

在這裡插入圖片描述
六、hive體系結構:
在這裡插入圖片描述
在這裡插入圖片描述
client:
命令列 -常用
JDBC
metastore元資料:儲存在資料庫
預設的資料庫derby 後期開發改成mysql
元資料:表名,表的所屬的資料庫,表的擁有者,表的分割槽資訊,表的型別,表資料的儲存的位置
cli-》metastore

    TBLS-》DBS-》hdfs的路徑

Hadoop:

使用mapreduce的計算模型
使用hdfs進行儲存hive表資料

在這裡插入圖片描述
在這裡插入圖片描述
Driver:
解析器:解析的HQL語句
編譯器:把HQL翻譯成mapreduce程式碼
優化器:優化

執行器:把程式碼提交給yarn

在這裡插入圖片描述
在這裡插入圖片描述
hive通過client提交的job,Driver經過解析、編譯、優化、執行-》最後提交給hadoop的MapReduce處理

**

七、Hive安裝及使用

**
請訪問:https://blog.csdn.net/qq_35036995/article/details/80249944

**

八、Hive客戶端的基礎語句:

**
  1、進入到hive的客戶端:bin/hive;
  2、檢視資料庫:show databases;
  3、建立資料庫:create database test;
  4、進入到資料庫:use test;
  5、查看錶:show tables;
  6、資料型別:
    tinyint、smallint、int、bigint -》int
    float、double、date
    string、vachar、char -》string
  7、create table hive_table(
      id int,
      name string
    );
  8、載入資料:
      load data local inpath ‘/opt/datas/hive_test.txt’ into table hive_table;
      local:指定本地的資料檔案存放路徑
      不加local:指定資料在hdfs的路徑
  9、查詢語句:
    select * from hive_table;
  10、hive的預設資料分隔符是\001,也就是^A ,分割符 " “, “,” ,”\t"等等
    如果說資料的分隔符與表的資料分隔符不一致的話,讀取資料為null
      按下crtl+v然後再按下crtl+a就會出來^A(\001)
    create table row_table(
      id int,
      name string
      )ROW FORMAT DELIMITED FIELDS TERMINATED BY " ";

load data local inpath ‘/opt/datas/hive_test.txt’ into table row_table;
**

九、hive在hdfs上的檔案結構

**
   資料倉庫的位置 資料庫目錄 表目錄 表的資料檔案
  /user/hive/warehouse /test.db /row_table /hive_test.txt
  default預設的資料庫:指的就是這個/user/hive/warehouse路徑
**

十、修改元資料儲存的資料庫:

**
  1、用bin/hive同時開啟多個客戶端會報錯
    java.sql.SQLException: Another instance of Derby may have already booted the database /opt/modules/apache/hive-1.2.1/metastore_db.
在這裡插入圖片描述
derby資料庫預設只能開啟一個客戶端,這是一個缺陷,換個資料庫儲存元資料
    資料庫可選有這幾種:derby mssql mysql oracle postgres
    一般選擇mysql元資料儲存
MySQL安裝請訪問:https://blog.csdn.net/qq_35036995/article/details/80297000

hive與mysql整合請訪問:https://blog.csdn.net/qq_35036995/article/details/80297070

**

十一、Hive操作命令

**
在這裡插入圖片描述
在這裡插入圖片描述
在這裡插入圖片描述
在這裡插入圖片描述
 1、描述表資訊
    desc tablename;
    desc extended 表名;
    desc formatted 表名;
  2、修改表名
    alter table table_oldname rename to new_table_name;
  3、給表增加一個列
    alter table new_table add columns(age int);
    alter table new_table add columns(sex string comment ‘sex’);添加註釋
  4、修改列的名字以及型別
    create table test_change(a int,b int,c int);
    修改列名 a -> a1
    alter table test_change change a a1 int;
    a1改a2,資料型別改成String,並且放在b的後面;
    alter table test_change change a1 a2 string after b int;
    將c改成c1,並放在第一列
    alter table test_change change c c1 int first;
  5、替換列(不能刪除列,但是可以修改和替換,)是全表替換
    ALTER TABLE table_name ADD|REPLACE COLUMNS (col_name data_type [COMMENT col_comment], …)
    alter table test_change replace columns(foo int , too string);
在這裡插入圖片描述
6、清除表資料truncate
    只清除表資料,元資料資訊還是存在的,表的結構已經表還是在的

truncate table row_table;
    在這裡插入圖片描述
    7、刪除表資料drop
    drop table row_table;
    清除資料,表以及表的結構清除,元資料也清除
  8、刪除資料庫
    drop database test_db CASCADE;
   刪除資料庫的資訊,如果資料庫不為空的話,則要加CASCADE欄位
  9、檢視hive自帶的函式: show functions;
    desc function when;
**

十二、hive的常用配置

**
在這裡插入圖片描述
1、hive的日誌檔案log4j:預設是在 j a v a . i o . t m p d i r / {java.io.tmpdir}/ {user.name}也就是/tmp/hadoop/hive.log
    修改 hive-log4j.properties.template 修改為hive-log4j.properties
    修改 hive.log.dir=/opt/modules/apache/hive-1.2.1/logs
  2、顯示資料庫和列名,新增配置資訊到hive-site.xml
    
      hive.cli.print.header
      true
    
    
      hive.cli.print.current.db
      true
    

如下圖:
在這裡插入圖片描述
**

十三、hive常用的linux命令選項

**
  檢視幫助資訊 bin/hive -help
    1、–database指定登陸到哪個database 下面去
      bin/hive --database mydb;
    2、指定一條sql語句,必須用引號包裹
      bin/hive -e ‘show databses’
      bin/hive -e ‘select * from mydb.new_table’
    3、指定寫sql語句的檔案,執行sql
      bin/hive -f hivesql
      指定一些較為的sql語句,週期性的執行
    4、檢視sql語句檔案
      bin/hive -i hivesql
      執行檔案的sql語句並進入到hive的客戶端
      用來初始化一些操作
    5、bin/hive -S hivesql
      靜默模式
    6、在當前回話視窗修改引數的屬性,臨時生效
      bin/hive --hiveconf hive.cli.print.header=false;
    7、在hive的客戶端中使用set修改引數屬性(臨時生效),以及檢視引數的屬性
      set hive.cli.print.header -》檢視引數的屬性
      set hive.cli.print.header=true; -》修改引數屬性
    8、常用的shell : ! 和 dfs
      -》! 表示訪問的linux本地的檔案系統 ->! ls /opt/modules/apache/
      -》dfs表示訪問的是hdfs的檔案系統 -> dfs -ls /;
    9、CREATE database_name[LOCATION hdfs_path]
      create database hive_test LOCATION “/location”;
      自定義資料庫在hdfs上的路徑,把指定/location當成預設的資料庫,
      所以這邊資料庫的名字不顯示

**

十四、hive三種表的建立方式

**
1、【普通的建立】
create table stu_info(
num int,
name string
)
row format delimited fields terminated by " ";
載入資料到本地:將本地的資料複製到表對應的位置

load data local inpath ‘/opt/datas/test.txt’ into table stu_info; 注意:’/opt/datas/test.txt’ 本地資料目錄位置

載入hdfs資料:將hdfs上的資料移動到表對應的位置
load data inpath ‘/table_stu.txt’ into table stu_info; 注意:’/table_stu.txt’ 本地資料目錄位置
在這裡插入圖片描述
2、【子查詢方式: as select】
[AS select_statement];
create table stu_as as select name from stu_info;
將查詢的資料和表的結構賦予一張新的表
類似於儲存一箇中間結果集
在這裡插入圖片描述
3、【like方式】
LIKE existing_table_or_view_name
create table stu_like like stu_info;
複製表的結構賦予一張新的表

接下來建立兩張表(為學習其他表建立基本表):
在這裡插入圖片描述
【databases】

create database db_emp;
【員工表】
create table emp(
empno int comment ‘員工編號’,
ename string comment ‘員工姓名’,
job string comment ‘員工職位’,
mgr int comment ‘領導編號’,
hiredate string comment ‘入職時間’,
sal double comment ‘薪資’,
comm double comment ‘獎金’,
deptno int comment ‘部門編號’
)
row format delimited fields terminated by ‘\t’;
load data local inpath ‘/opt/datas/emp.txt’ into table emp;注意: '/opt/datas/emp.txt’本地資料目錄位置
【部門表】
create table dept(
deptno int comment ‘部門編號’,
dname string comment ‘部門名稱’,
loc string comment ‘地址’
)
row format delimited fields terminated by ‘\t’;
load data local inpath ‘/opt/datas/dept.txt’ into table dept;
【覆蓋表的資料overwrite】內部機制有刪除的操作,刪除原來的資料載入表中

load data local inpath ‘/opt/datas/dept.txt’ overwrite into table dept;注意: ‘/opt/datas/dept.txt’ 本地資料目錄位置

**

十五、hive外部表

**
在這裡插入圖片描述
在這裡插入圖片描述
關鍵詞 [EXTERNAL]
[LOCATION hdfs_path]共享資料:去載入hdfs上所屬路徑下的資料
create table emp_part(
empno int comment ‘員工編號’,
ename string comment ‘員工姓名’,
job string comment ‘員工職位’,
mgr int comment ‘領導編號’,
hiredate string comment ‘入職時間’,
sal double comment ‘薪資’,
comm double comment ‘獎金’,
deptno int comment ‘部門編號’
)
row format delimited fields terminated by ‘\t’

LOCATION ‘/user/hive/warehouse/emp_db.db/emp’;

如果你改變emp這張表的資料,那麼emp1也會發生改變
如果你改變emp1這張表的資料,那麼emp也會發生改變

刪除表
drop table emp1;
-》資料共用一份資料,結果就把共享的資料刪除了
-》刪除表的時候會刪除表對應的元資料資訊(emp)
-》清除表對應的hdfs上的資料夾

建立外部表
create EXTERNAL table dept_ext(
deptno int comment ‘部門編號’,
dname string comment ‘部門名稱’,
loc string comment ‘地址’
)
row format delimited fields terminated by ‘\t’

LOCATION ‘/user/hive/warehouse/db_emp.db/dept’;

表的型別Table Type: EXTERNAL_TABLE

刪除表:drop table dept_ext;
-》外部表只是刪除元資料(dept_ext)
-》不會刪除對應的資料夾

-》一般先建立內部表,然後根據需求建立多張外部表
-》外部表主要是資料安全性的作用

hive內部表和外部表的區別:
1)建立表的時候:建立內部表時,會將資料移動到資料倉庫指向的路徑;若建立外部表,僅記錄資料所在的路徑,不對資料的位置做任何的改變

2)刪除表時:在刪除表的時候,內部表的元資料和資料一起刪除,而外部表只刪除元資料,不刪除資料。這樣外部表相對於內部表來說更加安全一些,資料組織也更加靈活,方便資料共享

**

十六、hive臨時表

**
create table dept_tmp(
deptno int,
dname string,
loc string
)
row format delimited fields terminated by ‘\t’;
load data local inpath ‘/opt/datas/dept.txt’ into table dept_tmp;
資料存放路徑location:
Location:hdfs://hadoop01.com:8020/tmp/hive/hadoop/23a93177-f22f-4035-a2e3-c51cf315625f/_tmp_space.db/962463c2-6563-47a8-9e62-2a1e8eb6ed19
關閉hive cli:
自動刪除臨時表
也可以手動刪除drop
CREATE TEMPORARY TABLE IF NOT EXISTS dept_tmp(
deptno int ,
dname string ,
loc string
)row format delimited fields terminated by ‘\t’;
LOCATION ‘/user/hive/warehouse/db_emp.db/dept’;
關閉hive cli:
自動刪除臨時表的資料

也可以手動刪除drop,刪除臨時表的資料及資料檔案

**

十七、hive分割槽表

**
在這裡插入圖片描述
在這裡插入圖片描述
在這裡插入圖片描述
在這裡插入圖片描述
企業中如何使用分割槽表
在這裡插入圖片描述
[PARTITIONED BY (col_name data_type [COMMENT col_comment], …)]
普通表:select * from logs where date=‘2018120’
執行流程:對全表的資料進行查詢,然後才會進行過濾
分割槽表:select * from logs where date=‘2018120’ and hour=‘00’
執行流程:直接載入對應資料夾路徑下的資料
分割槽表的欄位是邏輯性的,體現在hdfs上形成一個資料夾存在,並不在資料中,

必須不能是資料中包含的欄位

【一級分割槽】
create table emp_part(
empno int ,
ename string ,
job string ,
mgr int ,
hiredate string,
sal double ,
comm double ,
deptno int
)PARTITIONED BY(date string)

row format delimited fields terminated by ‘\t’;

load data local inpath ‘/opt/datas/emp.txt’ into table emp_part partition(date=‘2018120’);
load data local inpath ‘/opt/datas/emp.txt’ into table emp_part partition(date=‘2018121’);
load data local inpath ‘/opt/datas/emp.txt’ into table emp_part partition(date=‘2018122’);

select * from emp_part where date=‘2018120’;

【二級分割槽】
create table emp_part2(
empno int ,
ename string ,
job string ,
mgr int ,
hiredate string,
sal double ,
comm double ,
deptno int
)
PARTITIONED BY(date string,hour string)
row format delimited fields terminated by ‘\t’;

load data local inpath ‘/opt/datas/emp.txt’ into table emp_part2 partition(date=‘2018120’,hour=‘01’);
load data local inpath ‘/opt/datas/emp.txt’ into table emp_part2 partition(date=‘2018120’,hour=‘02’);

select * from emp_part2 where date=‘2018120’;
select * from emp_part2 where date=‘2018120’ and hour=‘01’;

-》分割槽表的作用主要是提高了查詢的效率

**

十八、hive桶表

**
桶表:獲取更高的處理效率、join、抽樣資料

[CLUSTERED BY (col_name, col_name, …) [SORTED BY (col_name [ASC|DESC], …)] INTO num_buckets BUCKETS]

create table emp_bu(
empno int ,
ename string ,
job string ,
mgr int ,
hiredate string,
sal double ,
comm double ,
deptno int
)CLUSTERED BY (empno) INTO 4 BUCKETS
row format delimited fields terminated by ‘\t’;
先建表,然後設定
set hive.enforce.bucketing = true;
insert overwrite table emp_bu select * from emp;

**

十九、hive分析函式

**
在這裡插入圖片描述
在這裡插入圖片描述
官網:https://cwiki.apache.org/confluence/display/Hive/LanguageManual+WindowingAndAnalytics
分析函式over:分析函式用於計算基於組的某種聚合值,它和聚合函式不同之處是對於每個組返回多行,而聚合函式對於每個組返回一行資料。
主要作用:對於分組後的資料進行處理,然後輸出處理後的結果

需求1: 查詢部門編號為10的所有員工,按照薪資進行降序排序desc(預設升序)
select * from emp where deptno=10 order by sal desc;
結果:
7839 KING PRESIDENT NULL 1981-11-17 5000.0 NULL 10
7782 CLARK MANAGER 7839 1981-6-9 2450.0 NULL 10
7934 MILLER CLERK 7782 1982-1-23 1300.0 NULL 10

需求2:將每個部門薪資最高的那個人的薪資顯示在最後一列
select empno,ename, deptno,sal, max(sal) over(partition by deptno order by sal desc ) as sal_111 from emp;
結果:
7839 KING 10 5000.0 5000.0 1
7782 CLARK 10 2450.0 5000.0 2
7934 MILLER 10 1300.0 5000.0 3

7788 SCOTT 20 3000.0 3000.0
7902 FORD 20 3000.0 3000.0
7566 JONES 20 2975.0 3000.0
7876 ADAMS 20 1100.0 3000.0
7369 SMITH 20 800.0 3000.0

7698 BLAKE 30 2850.0 2850.0
7499 ALLEN 30 1600.0 2850.0
7844 TURNER 30 1500.0 2850.0
7654 MARTIN 30 1250.0 2850.0
7521 WARD 30 1250.0 2850.0

7900 JAMES 30 950.0 2850.0

需求3:將每個部門薪資最高的那個人的薪資顯示在最後一列並且顯示唯一的編號

select empno,ename, deptno,sal, row_number() over(partition by deptno order by sal desc ) as sal_111 from emp ;
結果:
7839 KING 10 5000.0 1
7782 CLARK 10 2450.0 2
7934 MILLER 10 1300.0 3

7788 SCOTT 20 3000.0 1
7902 FORD 20 3000.0 2
7566 JONES 20 2975.0 3
7876 ADAMS 20 1100.0 4
7369 SMITH 20 800.0 5

7698 BLAKE 30 2850.0 1
7499 ALLEN 30 1600.0 2
7844 TURNER 30 1500.0 3
7654 MARTIN 30 1250.0 4
7521 WARD 30 1250.0 5
7900 JAMES 30 950.0 6

需求4:獲取每個部門薪資最高的前兩位(巢狀子查詢的方式)
select empno,ename, deptno,sal from(select empno,ename, deptno,sal,row_number() over (partition by deptno order by sal desc) as rn from emp) as tmp where rn < 3;
結果:
7839 KING 10 5000.0
7782 CLARK 10 2450.0
7788 SCOTT 20 3000.0
7902 FORD 20 3000.0
7698 BLAKE 30 2850.0
7499 ALLEN 30 1600.0

**

二十、hive資料匯入和匯出

**
在這裡插入圖片描述

注意:這種方式適合資料量非常小的情況下去使用,如果說資料量大,避免這種操作

show tables出現values__tmp__table__1這個臨時表,關閉會話就消失

5、location方式

在這裡插入圖片描述

【匯出】
1、insert
insert overwrite [local] directory ‘path’ select sql;

-》本地
insert overwrite local directory ‘/opt/datas/emp_in01’ select * from emp;

insert overwrite local directory ‘/opt/datas/emp_in01’ row format delimited fields terminated by “\t” select * from emp;

-》HDFS
insert overwrite directory ‘/emp_insert’ select * from emp;
insert overwrite directory ‘/emp_insert’ row format delimited fields terminated by “\t” select * from emp;

2、bin/hdfs dfs -get xxx 下載資料檔案
hive> dfs -get xxx (hive的客戶端)

3、bin/hive -e 或者 -f + >> 或者 > (追加和覆蓋符號)

4、sqoop 方式:import匯入和export 匯出

**

二十一、hive常見的hql語句

**
在這裡插入圖片描述
在這裡插入圖片描述
在這裡插入圖片描述
【過濾】
where 、limit、distinct、between and 、null、 is not null

select * from emp where sal >3000;
select * from emp limit 5;
select distinct deptno from emp;
select * from emp where sal between 1000 and 3000;
select empno,ename from emp where comm is null;
select empno,ename from emp where comm is not null;

【聚合函式】
count、sum、max、min、avg、group by 、having

select avg(sal) avg_sal from emp;
按部門分組求出每個部門的平均工資
select 中出現的欄位,需要用聚合函式包裹或者放入group by 中
select deptno,avg(sal) from emp group by deptno;
10 2916.6666666666665
20 2175.0
30 1566.6666666666667
select deptno,max(job),avg(sal) from emp group by deptno;
10 PRESIDENT 2916.6666666666665
20 MANAGER 2175.0
30 SALESMAN 1566.6666666666667
select deptno,avg(sal) from emp group by deptno,job;

having和where 是差不多的用法,都是篩選語句
可以一起使用,先執行where後執行having
select deptno,avg(sal) avg_sal from emp group by deptno having avg_sal >2000 ;

【join】
left join, right join,inner join(等值),全join
建立兩張表A,B
A表: B表:
ID Name ID phone
1 張三 1 111
2 李四 2 112
3 王五 3 113
5 趙六 4 114

drop table A;
drop table B;
create table A(
id int,
name string
)row format delimited fields terminated by “\t”;

create table B(
id int,
name int
)row format delimited fields terminated by “\t”;

load data local inpath ‘/opt/datas/A’ into table A;
load data local inpath ‘/opt/datas/B’ into table B;

等值join :id值都會出現
select aaa.ID,aaa.Name ,bbb.ID ,bbb.phone from A aaa join B bbb on aaa.ID=bbb.ID;

左join:以左表為基準,沒有匹配到的欄位就是null
select aaa.ID,aaa.Name ,bbb.ID ,bbb.phone from A aaa left join B bbb on aaa.ID=bbb.ID;

右join: 以右表為基準,沒有匹配到的欄位就是null
select aaa.ID,aaa.Name ,bbb.ID ,bbb.phone from A aaa right join B bbb on aaa.ID=bbb.ID;

全join:所有的欄位都會出現,匹配或者匹配不上都會出現,沒有匹配上的欄位就是null

select aaa.ID,aaa.Name ,bbb.ID ,bbb.phone from A aaa full join B bbb on aaa.ID=bbb.ID;

【排序】

1、order by :全域性排序,設定多個reduce沒有太大的作用
select * from emp order by sal;

2、sort by :區域性排序,對於每個reduce的結果進行排序,設定reduce=4,匯出到本地

insert overwrite local directory ‘/opt/datas/emp_sort’ row format delimited fields terminated by “\t” select * from emp sort by sal;

3、distribute by(底層是mr分割槽)
-》可以按照指定的值進行分割槽
-》先分割槽後排序,一般和sort by連用
insert overwrite local directory ‘/opt/datas/emp_dist’ row format delimited fields terminated by “\t” select * from emp distribute by deptno sort by sal;

4、cluster by :相當於 distribute by +sort by 組合使用
-》排序只能倒序排序,不能指定排序的規則為desc或者asc;
-》相同的工資放在一起,因為資料的原因,相同工資有點少;
insert overwrite local directory ‘/opt/datas/emp_cluster’ row format delimited fields terminated by “\t” select * from emp cluster by sal;

**

二十二、hive和mapreduce的執行引數

**
設定每個reduce處理的資料量:(單位是位元組)
set hive.exec.reducers.bytes.per.reducer=

hive.exec.reducers.bytes.per.reducer
256000000
size per reducer.The default is 256Mb, i.e if the input size is 1G, it will use 4 reducers.

設定最大執行的reduce的個數:預設1009
set hive.exec.reducers.max=

hive.exec.reducers.max
1009

max number of reducers will be used. If the one specified in the configuration parameter mapred.reduce.tasks is
negative, Hive will use this one as the max number of reducers when automatically determine number of reducers.

設定實際執行的reduce的個數,預設是1個
set mapreduce.job.reduces=

**

二十三、hive自定義UDF函式

**
在這裡插入圖片描述
在這裡插入圖片描述
UDF :一進一出

轉換大小寫

用IDEA開發工具寫一個簡單的UDF函式

hive的maven依賴:

在這裡插入圖片描述

org.apache.hadoop
hadoop-client
2.7.3


org.apache.hive
hive-exec
1.2.1


org.apache.hive
hive-jdbc
1.2.1

阿里的映象資源下載:


nexus-aliyun
Nexus aliyun
http://maven.aliyun.com/nexus/content/groups/public


在這裡插入圖片描述
繼承UDF類,實現evaluate(Text str)
public class Lower extends UDF {
public Text evaluate(Text str){
if (str == null) {
return null;
}
if (StringUtils.isBlank(str.toString())) {
return null;
}
return new Text(str.toString().toLowerCase());
}
//測試
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(new Lower().evaluate(new Text(“TAYLOR swift”)));
}
}
包名.類名
com.xningge.Lower

將寫好的程式碼打成jar包,上傳linux
將jar包新增到hive裡面去
add jar /opt/datas/lower_hive.jar;
建立一個函式
create temporary function LowerUdf as ‘com.xningge.Lower’;
檢視函式:show functions;
-》使用函式
select empno,ename, LowerUdf(ename) lower_name from emp;

**

二十四、hiveserver2與jdbc客戶端

**
在這裡插入圖片描述
在這裡插入圖片描述
在這裡插入圖片描述
將hive程式設計一個服務對外開放,通過客戶端去連線
啟動服務端:bin/hiveserver2
後臺啟動:bin/hiveserver2 &

開啟客戶端:bin/beeline
檢視客戶端幫助資訊: bin/beeline --help
beeline> !help (不加分號)
官網:beeline -u jdbc:hive2://hadoop01.xningge.com:10000/ -n scott -w password_file
連線hiveserver2 :
-n 指定使用者名稱:linux上的使用者
-p:指定密碼: linux使用者的密碼
bin/beeline -u jdbc:hive2://hadoop01.xningge.com:10000/ -n xningge -p 123456
或者
bin/beeline
!connect jdbc:hive2://hadoop01.xningge.com:10000

hive JDBC 遠端連線
官網:https://cwiki.apache.org/confluence/display/Hive/HiveServer2+Clients#HiveServer2Clients-JDBC
**

二十五、Hive的執行模式與虛擬列

**
hive的配置模式分為三種:
–依據hive的安裝和metastore的設定機器而言
嵌入模式:使用自帶的derby資料庫
本地模式:將metastore放在mysql上,且mysql與hive安裝在同一臺機器
遠端模式:將metastore放在mysql上,mysql和hive不在同一臺機器上

對於遠端調控模式,則需要讓mysql向叢集對外提供服務,則需要配置metastore

配置: 指明存放metastore的mysql所在的機器號

hive.metastore.uris

Thrift URI for the remote metastore. Used by metastore client to connect to remote metastore.

啟動服務:bin/hive --service metastore &

fetch模式

hive.fetch.task.conversion
more

Expects one of [none, minimal, more].
Some select queries can be converted to single FETCH task minimizing latency.
Currently the query should be single sourced not having any subquery and should not have
any aggregations or distincts (which incurs RS), lateral views and joins.
0. none : disable hive.fetch.task.conversion
1. minimal : SELECT STAR, FILTER on partition columns, LIMIT only
2. more : SELECT, FILTER, LIMIT only (support TABLESAMPLE and virtual columns)

none: 不管你寫什麼sql都會跑mapreduce,不開啟fetch模式
minimal:當select * 、針對分割槽欄位進行過濾、limit不跑mapreduce
more: 當select 、過濾、limit不跑mapreduce

虛擬列:Virtual Colums
INPUT__FILE__NAME 輸入檔名稱,顯示這行資料所在的絕對路徑
BLOCK__OFFSET__INSIDE__FILE 記錄資料在塊中的偏移量

select *, BLOCK__OFFSET__INSIDE__FILE from dept;
10 ACCOUNTING NEW YORK 0
20 RESEARCH DALLAS 23
30 SALES CHICAGO 42
40 OPERATIONS BOSTON 59

二十六、【案列】日誌資料檔案分析

需求:統計24小時內的每個時段的pv和uv
pv統計總的瀏覽量
uv統計guid去重後的總量
獲取時間欄位,日期和小時-》分割槽表
資料清洗:獲取日期和小時,獲取想要欄位
2015-08-28 18:14:59 -》28和18 substring方式獲取
資料分析
hive :select sql
資料匯出:
sqoop:匯出mysql
最終結果預期:
日期 小時 pv uv
日期和小時:tracktime
pv:url
uv:guid
1、【資料收集】

登陸hive:
啟動服務端:bin/hiveserver2 &
啟動客戶端:bin/beeline -u jdbc:hive2://hadoop01.xningge.com:10000/ -n xningge -p 123456
建立源表:
create database track_log;
create table yhd_source(
id string,
url string,
referer string,
keyword string,
type string,
guid string,
pageId string,
moduleId string,
linkId string,
attachedInfo string,
sessionId string,
trackerU string,
trackerType string,
ip string,
trackerSrc string,
cookie string,
orderCode string,
trackTime string,
endUserId string,
firstLink string,
sessionViewNo string,
productId string,
curMerchantId string,
provinceId string,
cityId string,
fee string,
edmActivity string,
edmEmail string,
edmJobId string,
ieVersion string,
platform string,
internalKeyword string,
resultSum string,
currentPage string,
linkPosition string,
buttonPosition string
)
row format delimited fields terminated by ‘\t’;

load data local inpath ‘/opt/datas/2015082818’ into table yhd_source;
load data local inpath ‘/opt/datas/2015082819’ into table yhd_source;

2、【資料清洗】
create table yhd_qingxi(
id string,
url string,
guid string,
date string,
hour string
)
row format delimited fields terminated by ‘\t’;

insert into table yhd_qingxi select id,url,guid,substring(trackTime,9,2) date,substring(trackTime,12,2) hour from yhd_source;

select id,url,guid,date,hour from yhd_qingxi;

建立分割槽表:根據時間欄位進行分割槽
create table yhd_part(
id string,
url string,
guid string
)partitioned by (date string,hour string)
row format delimited fields terminated by ‘\t’;

insert into table yhd_part partition(date=‘20150828’,hour=‘18’)
select id,url,guid from yhd_qingxi where date=‘28’ and hour=‘18’;

insert into table yhd_part partition(date=‘20150828’,hour=‘19’)
select id,url,guid from yhd_qingxi where date=‘28’ and hour=‘19’;

select id,url,guid from yhd_part where date=‘20150828’ and hour=‘18’;
select id,url,guid from yhd_part where date=‘20150828’ and hour=‘19’;

動態分割槽:
表示是否開啟動態分割槽

hive.exec.dynamic.partition
true
Whether or not to allow dynamic partitions in DML/DDL.

表示動態分割槽最大個數

hive.exec.max.dynamic.partitions
1000
Maximum number of dynamic partitions allowed to be created in total.

每個節點上支援動態分割槽的個數

hive.exec.max.dynamic.partitions.pernode
100
Maximum number of dynamic partitions allowed to be created in each mapper/reducer node.

使用動態分割槽,需要改變模式為非嚴格模式

hive.exec.dynamic.partition.mode
strict
In strict mode, the user must specify at least one static partition in case the user accidentally overwrites all partitions.

set設定:
set hive.exec.dynamic.partition.mode=nonstrict;

create table yhd_part2(
id string,
url string,
guid string
)partitioned by (date string,hour string)
row format delimited fields terminated by ‘\t’;

固定寫死的格式
insert into table yhd_part partition(date=‘20150828’,hour=‘18’)
select id,url,guid from yhd_qingxi where date=‘28’ and hour=‘18’;

動態分割槽(非常靈活)
insert into table yhd_part2 partition (date,hour) select * from yhd_qingxi;

select id,url,guid from yhd_part2 where date=‘20150828’ and hour=‘18’;

3、資料分析
PV:
select date,hour,count(url) pv from yhd_part group by date,hour;
結果:
±----------±------±-------±-+
| date | hour | pv |
±----------±------±-------±-+
| 20150828 | 18 | 64972 |
| 20150828 | 19 | 61162 |
±----------±------±-------±-+

UV
select date,hour,count(distinct guid) uv from yhd_part group by date,hour;
結果:
±----------±------±-------±-+
| date | hour | uv |
±----------±------±-------±-+
| 20150828 | 18 | 23938 |
| 20150828 | 19 | 22330 |
±----------±------±-------±-+

最終結果匯入最終結果表中:
create table result as select date,hour,count(url) pv,count(distinct guid) uv from yhd_part group by date,hour;
結果:
±-------------±-------------±-----------±-----------±-+
| result.date | result.hour | result.pv | result.uv |
±-------------±-------------±-----------±-----------±-+
| 20150828 | 18 | 64972 | 23938 |
| 20150828 | 19 | 61162 | 22330 |
±-------------±-------------±-----------±-----------±-+

4、資料匯出:

將最終的結果儲存在mysql:
在mysql裡建立表:
create table save(
date varchar(30),
hour varchar(30),
pv varchar(30),
uv varchar(30),
primary key(date,hour)
);

sqoop方式:
hive-》mysql

bin/sqoop export
–connect jdbc:mysql://hadoop01.xningge.com:3306/t_data_pv_uv
–username xningge
–password [email protected]
–table save
–export-dir /user/hive/warehouse/track_log.db/result
-m 1
–input-fields-terminated-by ‘\001’
**

二十七、【案列二】hive shell指令碼 自動化載入資料

**
效果:
access_log/20180122/
2018012201.log
2018012202.log
2018012203.log
【案例實現】
建立源表
create database load_hive;
create table load_tb(
id string,
url string,
referer string,
keyword string,
type string,
guid string,
pageId string,
moduleId string,
linkId string,
attachedInfo string,
sessionId string,
trackerU string,
trackerType string,
ip string,
trackerSrc string,
cookie string,
orderCode string,
trackTime string,
endUserId string,
firstLink string,
sessionViewNo string,
productId string,
curMerchantId string,
provinceId string,
cityId string,
fee string,
edmActivity string,
edmEmail string,
edmJobId string,
ieVersion string,
platform string,
internalKeyword string,
resultSum string,
currentPage string,
linkPosition string,
buttonPosition string
)partitioned by(date string,hour string)
row format delimited fields terminated by ‘\t’;

啟動服務:bin/hiveserver2 &
啟動客戶端:bin/beeline -u jdbc:hive2://hadoop01.xningge.com:10000 -n xningge -p 123456

1、通過hive -e 的方式:

建立一個指令碼:load_to_hive.sh
在這裡插入圖片描述
檢視分割槽:
show partitions load_tb;

在linux下,可以debug執行指令碼

sh -x load_to_hive.sh

2、通過hive -f的方式:

1、建立一個檔案:vi load.sql存放sql語句

load data local inpath ‘ h i v e c o n f : l o g d i r / {hiveconf:log_dir}/ {hiveconf:file_path}’ into table load_log.load_tab
partition(dateTime=’ h i v e c o n f : D A Y , h o u r = {hiveconf:DAY}&#x27;,hour=&#x27; {hiveconf:HOUR}’):

重新命名load_to_hive.sh load_to_hive_file.sh
在這裡插入圖片描述
2.建立一個load.sql,把-e後面的複製過來(然後在修改):
針對變數,我們可以用–hiveconf 去傳參
load data local inpath ‘ h i v e c o n f : l o g d i r / {hiveconf:log_dir}/

相關推薦

學習hive權威指南

目錄: ETL介紹 大資料平臺架構概述 系統資料流動 hive概述 hive在hadoop生態系統中 hive體系結構 hive安裝及使用 hive客戶端的基本語句 hive在HDFS檔案系統中的結構 修改hive元資料儲存的資料庫 hive操作命令 hive常用配置 hive常用的Li

學習js權威指南第五站 ---- 數組

參數調用 轉換成 長度 刪除 scrip .so obj -- .... 1.數組方法   ①join()     將數組中的左右元素都轉換成字符串並連接在一起,返回最後生成的字符串。   ②reverse() 改變原數組     將數組中的元素顛倒順序,返回逆序的數組。在

學習javascript權威指南系列

最近感覺以前學的javascript基礎的東西好多都記不太清楚了,想著重新回顧一遍,就重新啃一遍javascript權威指南。領導推薦的書:javascript權威指南第五版,我個人有第六版的,我會以

學習Hadoop權威指南之Hadoop執行MapReduce日誌檢視

修改map配置檔案 mapred-site.xml [[email protected] yar]# vim /opt/hadoop-2.8.3/etc/hadoop/mapred-site.xml <property> <name&

學習JS權威指南記錄

針對IE bug做的補丁 var extend=(function(){ //處理IE bug 即如果o的屬性擁有一個不可列舉的同名屬性,那麼for/in迴圈不會列舉物件o可列舉的屬性         for (var p in {toString:null}){

大資料資料倉庫——hive學習權威指南

學習hive權威指南目錄:ETL介紹大資料平臺架構概述系統資料流動hive概述hive在hadoop生態系統中hive體系結構hive安裝及使用hive客戶端的基本語句hive在HDFS檔案系統中的結構修改hive元資料儲存的資料庫hive操作命令hive常用配置hive常用

Hadoop權威指南學習筆記三

支持 第三方 handle line src factory 模式 多個 重要 HDFS簡單介紹 聲明:本文是本人基於Hadoop權威指南學習的一些個人理解和筆記,僅供學習參考。有什麽不到之處還望指出,一起學習一起進步。 轉載請註明:http://blog.cs

mongodb權威指南之mongodb基礎知識學習記錄

pre lec fin 基礎知識 pda log editor 批量 l數據庫 mongo show dbs查看所有的數據庫 使用use可以切換數據庫,如果沒有數據庫則創建一個新的 use local切換倒local數據庫 增加數據 db.test.insert({name

JavaScript權威指南(第6版)學習筆記一

未定義 顯示 註釋 星期 語句 布爾運算 垃圾 class ron 第2章 詞法結構 一、字符集 *JavaScript程序是用Unicode字符集編寫的。 *JavaScript嚴格區分大小寫。 *JavaScript註釋:(1)“//”用於單行註釋;(2)"/*

JavaScript權威指南(第6版)學習筆記三

設置 ray 每一個 main 需求 創建 per ive customer 第六章對象 對象可以看成其屬性的無序集合,每個屬性都是一個名/值對。JavaScript對象是動態的,可以新增也可以刪除屬性,可以通過引用而非值來操作對象。如果變量x是指向一個對象的引用,那麽執行

cdh版本的hue安裝配置部署以及集成hadoop hbase hive mysql等權威指南

service sources ces 兩個 配置 語句 基金會 pan 創建 hue下載地址:https://github.com/cloudera/hue hue學習文檔地址:http://archive.cloudera.com/cdh5/cdh/5/hue-3.7

《Kubernetes權威指南第2版》學習(二)一個簡單的例子

stop 輸入 rtu gist 用戶名 server 遠程 dock netstat 1: 安裝VirtualBox, 並下載CentOS-7-x86_64-DVD-1708.iso, 安裝centOS7,具體過程可以百度。 2:開啟centOS的SSH, 步驟如下:

Kubernetes權威指南學習筆記(一)

資源利用率 date ace epo yaml policy 下一代 標識 code https://blog.csdn.net/keysilence1/article/details/70239717 概念 Kubernetes是谷歌嚴格保密十幾年的秘密武器——Bo

netty權威指南學習筆記四——TCP粘包/拆包之粘包問題解決

方法 pan 對象 protect row 學習 ddl .get font   發生了粘包,我們需要將其清晰的進行拆包處理,這裏采用LineBasedFrameDecoder來解決 LineBasedFrameDecoder的工作原理是它依次遍歷ByteBuf中的可讀字節

netty權威指南學習筆記六——編解碼技術之MessagePack

ssi add java exception 字節數組 ted evel thrift 發送   編解碼技術主要應用在網絡傳輸中,將對象比如BOJO進行編解碼以利於網絡中進行傳輸。平常我們也會將編解碼說成是序列化/反序列化   定義:當進行遠程跨進程服務調用時,需要把被傳輸

IDA Pro 權威指南學習筆記(二) - IDA 數據庫文件

names 標記 image 一個 輸入 需要 二叉 pro 樹形 把要分析的文件用 IDA 打開後,會生成 3 個數據庫文件 擴展名分別為 .id0,id1,nam .id0 文件是一個二叉樹形式的數據庫 .id1 文件包含描述每個程序字節的標記 .nam 文

IDA Pro 權威指南學習筆記(四) - IDA 用戶界面的基本規則

上下 工具 庫文件 發生 執行 ida 基於 需要 位置 基本規則: IDA 不提供撤銷功能 如果由於不小心按下某個鍵,導致數據庫文件發生意外,這時需要將顯示窗口恢復到以前的狀態 幾乎所有的操作都有其對應的菜單項、熱鍵和工具欄按鈕 IDA 的工具欄高度可配置,就像熱

IDA Pro 權威指南學習筆記(六) - 次要的 IDA 顯示窗口

方便 dump 可能 沒有 匯編 關系 布局 提高 整數 十六進制窗口 IDA 十六進制窗口可以配置為顯示各種格式,並可作為十六進制編輯器使用 默認情況下,十六進制窗口顯示程序內容和列表的標準十六進制代碼,每行顯示 16 個字節,以及其對應的 ASCII 字符 和在反

IDA Pro 權威指南學習筆記(八) - 基本 IDA 導航

當前 跳轉 previous 窗口 移動 http pro open 引用 導航目標 在分析階段,IDA 會通過檢查二進制文件的符號表生成符號名稱,或根據二進制文件引用位置的方式自動生成一個名稱 反匯編窗口中顯示的任何名稱都是導航目標 雙擊任何一個符號,IDA 將跳轉