9.python 查詢hbase2 (三)

前文有說thrift連接操作hbase略顯麻煩,happybase完美解決這些問題,操作接口很類似hbase shell,性能和異常處理相對官方版本也做了諸多優化,可謂真的相當的happy了。唯一的問題是這是個第三方庫(Github地址),目前作者還在維護,除非你要完全跟上最新Hbase 接口或者希望多個語言接口儘可能保證一致,強烈推薦此庫。

環境準備

不需要自己thrift生成python庫代碼,直接安裝最新的庫即可。如下:

pip install thrift
pip install happybase

連接

默認Connection創建時自動打開到hbase的socket連接,可以創建時關閉自動連接,然後手動開啓,另外對於老版本的hbase(0.94、0.98)需要指定compat參數,詳細連接可以參看API文檔

import happybase
 
connection = happybase.Connection('10.202.209.72', autoconnect=False)
connection.open()
 
#print所有的表名
print('All tables: ',connection.tables(), '\n')

查詢

注意,happybase庫操作在每個table對象上進行,返回值可直接按照map形式操作。

#這個操作是一個提前聲明-我要用到這個表了-但不會提交給thrift server做操作
table = connection.table(b'table1')
 
#檢索某一行
row = table.row(b'row_key1')
print('a row:', row, '\n')
 
# 返回結果直接按照map形式操作
print(row[b'b:t1'])
print(row[b'b:t2'])

row = table.row(b'row_key1', columns=[b'b:t1'])
print(row)

#同時檢索多行
print('print two rows:')
rows = table.rows([b'row_key1', b'row_key2'])
for key, data in rows:
    print(key, data)
 
#同時檢索多行輸出字典
print('\n', 'print two dict rows')
rows_as_dict = dict(table.rows([b'row_key1', b'row_key2']))
print(rows_as_dict)

掃描

# 指定開始和結束,最多10行,注意最好指定開始結束範圍和行數
for key, data in table.scan(row_start=b'000', row_stop=b'002', limit=10):
    print(key, data)
    
# 指定開始和結束,最多10行,指定過濾條件,注意最好指定開始結束範圍和行數
f = "(PrefixFilter ('001') AND (QualifierFilter (=, 'binary:m')))"
for key, data in table.scan(row_start=b'000', row_stop=b'002', limit=10, filter=f):
    print(key, data)

可以看到接口非常簡潔易用。

源碼下載

演示源碼下載鏈接

happybase的文檔寫的非常完善,本文只演示了查詢,其他操作可參考文檔

原創,轉載請註明來自

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章