Hive——join的使用


Hive——join的使用

hive中常用的join有:inner join、left join 、right join 、full join、left semi join、cross join、mulitiple

在hive中建立兩張表,用於測試:

hive> select * from rdb_a;
OK
1       lucy
2       jack
3       tony
 
hive> select * from rdb_b;
OK
1       12
2       22
4       32

一、基本join使用

1、內關聯([inner] join):只返回關聯上的結果

 

select a.id,a.name,b.age from rdb_a a inner join rdb_b b on a.id=b.id;
 
Total MapReduce CPU Time Spent: 2 seconds 560 msec
OK
1       lucy    12
2       jack    22
Time taken: 47.419 seconds, Fetched: 2 row(s)

 

2、左關聯(left [outer] join):以左表為主

select a.id,a.name,b.age from rdb_a a left join rdb_b b on a.id=b.id;
 
Total MapReduce CPU Time Spent: 1 seconds 240 msec
OK
1       lucy    12
2       jack    22
3       tony    NULL
Time taken: 33.42 seconds, Fetched: 3 row(s)

 

3、右關聯(right [outer] join):以右表為主

select a.id,a.name,b.age from rdb_a a right join rdb_b b on a.id=b.id;
 
Total MapReduce CPU Time Spent: 2 seconds 130 msec
OK
1       lucy    12
2       jack    22
NULL    NULL    32
Time taken: 32.7 seconds, Fetched: 3 row(s)

 

4、全關聯(full [outer] join):以兩個表的記錄為基准,返回兩個表的記錄去重之和,關聯不上的字段為NULL。

select a.id,a.name,b.age from rdb_a a full join rdb_b b on a.id=b.id;
 
Total MapReduce CPU Time Spent: 5 seconds 540 msec
OK
1       lucy    12
2       jack    22
3       tony    NULL
NULL    NULL    32
Time taken: 42.938 seconds, Fetched: 4 row(s)

 

 

5、left semi join:以LEFT SEMI JOIN關鍵字前面的表為主表,返回主表的KEY也在副表中的記錄。

select a.id,a.name from rdb_a a left semi join rdb_b b on a.id=b.id;
 
Total MapReduce CPU Time Spent: 3 seconds 300 msec
OK
1       lucy
2       jack
Time taken: 31.105 seconds, Fetched: 2 row(s)
 
其實就相當於:select a.id,a.name from rdb_a a where a.id in(select b.id from  rdb_b b );

 

 

6、笛卡爾積關聯(cross join):返回兩個表的笛卡爾積結果,不需要指定關聯鍵

select a.id,a.name,b.age from rdb_a a cross join rdb_b b;
 
Total MapReduce CPU Time Spent: 1 seconds 260 msec
OK
1       lucy    12
1       lucy    22
1       lucy    32
2       jack    12
2       jack    22
2       jack    32
3       tony    12
3       tony    22
3       tony    32
Time taken: 24.727 seconds, Fetched: 9 row(s)

 

二、Common Join與Map Join

利用hive進行join連接操作,相較於MR有兩種執行方案,一種為common join,另一種為map join ,map join是相對於common join的一種優化,省去shullfe和reduce的過程,大大的降低的作業運行的時間。

 

Common Join(也稱之為shufflejoiin/reducejoin) 

20170921190446385.jpg

過程:

1>首先會啟動一個Task,Mapper會去讀表HDFS上兩張X/Y表中的數據 
2>Mapper處理過數據再經過shuffle處理 
3>最后由reduce輸出join結果

缺點 :
1>存在shuffle過程,效率低 
2>每張表都要去磁盤讀取,磁盤IO大

 

Map Join 

20170921190126354.jpg

過程:

1>mapjoin首先會通過本地MapReduce Task將要join的小表轉成Hash Table Files,然后加載到分布式緩存中 
2>Mapperh會去緩存中讀取小表數據來和Big Table數據進行join 
3>Map直接給出結果

優點: 沒有shuffle/Reduce過程,效率提高

缺點 :由於小表都加載到內存當中,讀內存的要求提高了

hive中專門有個參數來設置是否自動將commmon join 轉化為map join:hive.auto.convert.join。

當hive.auto.convert.join=true hive會為我們自動轉換。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM