1. 程式人生 > >用Hive、Impala查詢Hbase資料

用Hive、Impala查詢Hbase資料

近期有專案需要向Hbase寫入資料,為了測試資料寫入是否正常,常用Hbase shell查詢資料,但是用起來比較麻煩,看到Clouder官網有關於使用Impala查詢Hbase的操作說明,做了簡單的嘗試,記錄如下,供大家參考。

環境:

CDH 5.10.2、Impala 2.7.0、Hive 1.1.0、Hbase 1.2.0

原理:

Hive建立外部表,建立與Hbase表的對映關係,從而實現通過Hive查詢Hbase的功能。而Impala與Hive公用元資料資訊,因此用Impala也可以查詢Hbase.

步驟:

1、修改Cloudera叢集中 Impala和Hive配置。

2、新建Hbase表,並插入資料。

新建Hbase表有多種方法,如Java API、Python API、Hbase Shell等,以下是通過Hbase Shell新建Hbase表的命令。

create 'examuser_info_tag',{NAME => 'user_info', COMPRESSION => 'SNAPPY' },{NAME => 'tag_info', COMPRESSION => 'SNAPPY' },{NAME => 'ill_tag', COMPRESSION => 'SNAPPY' },{ NUMREGIONS => 10 , SPLITALGO => 'UniformSplit'}

這裡不再對插入資料進行說明。

3、建立Hive外部表,建立與Hbase的關聯關係。

以下SQL需要在Hive Shell中執行。如果使用Hue,注意選擇Hive shell,不要使用Impala Shell。

Hive表中的列第一列對應Hbase表中的rowkey,其他列分別對應Hbase表中的列。

CREATE EXTERNAL TABLE hbase.user_info ( 
    idcard STRING,
    checkcount INT, 
    username STRING, 
    useraddr STRING, 
    userbirth STRING, 
    usermarried TINYINT, 
    usersex TINYINT, 
    mincheckdate STRING, 
    mobile STRING
) 
STORED BY "org.apache.hadoop.hive.hbase.HBaseStorageHandler" 
WITH SERDEPROPERTIES (
"hbase.columns.mapping"="
    :key,
    user_info:checkCount,
    user_info:userName,
    user_info:userAddr,
    user_info:userBirth,
    user_info:userMarried,
    user_info:userSex,
    user_info:minCheckDate,
    user_info:mobile
") 
TBLPROPERTIES ("hbase.table.name"="user_info")

4、Impala同步Hive元資料資訊。

在Impala Shell中執行 INVALIDATE METADATA hbase.user_info;

5、使用測試

插入資料:

insert into hbase.user_info(idcard,checkcount,username,useraddr,usersex,mobile)
values('12345678777',2,'測試','北京朝陽',1,'1234567890' );

查詢:

-- 主鍵rowkey查詢,效率較高
select * from  hbase.user_info  where idcard = '12345678777';

-- 非主鍵查詢,效率很低
select * from  hbase.user_info  where mobile = '1234567890';

刪除和修改:

Impala或Hive不支援修改和刪除Hbase資料,不過可以使用新插入資料代替Update。

-- 不支援Upate操作
update hbase.user_info set checkcount =3 where idcard = '12345678777';

-- 可以使用如下操作代替Update,
insert into hbase.user_info(idcard,checkcount) values ('12345678777', 3);


批量匯入資料:

insert into hbase.user_info( useridcard,checkcount,user,useraddr,userbirth,usermarried,usersex,mincheckdate,mobile)
select useridcard,check_count,user,useraddr,userbirth,usermarried,usersex,min_check_date,mobile 
from test.user_info

上述操作可能會有如下錯誤資訊:

RetriesExhaustedWithDetailsException: Failed 1024 actions: RegionTooBusyException: 1024 times,

這個問題是由於hbase在載入資料過程中產生了region split操作,會阻塞寫入操作。可以嘗試在建立hbase表時進行優化,如:預建分割槽。