大數據

Hive如何實現自增序列

在利用數據倉庫進行數據處理時,通常有這樣一個業務場景,為一個Hive表新增一列自增字段(比如事實表和維度表之間的"代理主鍵")。雖然Hive不像RDBMS如mysql一樣本身提供自增主鍵的功能,但它本身可以通過函數來實現自增序列功能:利用row_number()窗口函數或者使用UDFRowSequence。

示例:table_src是我們經過業務需求處理的到的中間表數據,現在我們需要為table_src新增一列自增序列字段auto_increment_id,並將最終數據保存到table_dest中。

1. 利用row_number函數

場景1:table_dest中目前沒有數據

insert into table table_dest
select row_number() over(order by 1) as auto_increment_id, table_src.* from table_src;

場景2: table_dest中有數據,並且已經經過新增自增字段處理

insert into table table_dest
select (row_number() over(order by 1) + dest.max_id) auto_increment_id, src.* from table_src src cross join (select max(auto_increment_id) max_id from table_dest) dest;

2. 利用UDFRowSequence

首先Hive環境要有hive-contrib相關jar包,然後執行

create temporary function row_sequence as 'org.apache.hadoop.hive.contrib.udf.UDFRowSequence';

針對上述場景一,可通過以下語句實現:

insert into table table_dest
select row_sequence() auto_increment_id, table_src.* from table_src;

場景2實現起來也很簡單,這裡不在贅述。

但是,需要注意二者的區別:

row_number函數是對整個數據集做處理,自增序列在當次排序中是連續的唯一的。

UDFRowSequence是按照任務排序,但是一個SQL可能併發執行的job不止一個,而每個job都會從1開始各自排序,所以不能保證序號全局唯一。可以考慮將UDFRowSequence擴展到一個第三方存儲系統中,進行序號邏輯管理,來最終實現全局的連續自增唯一序號。

Leave a Reply

Your email address will not be published. Required fields are marked *