8.python 查詢hbase2 (二)

上篇文章講述了python如何通過thrift連接操作hbase,是官方最常用方法,但是略顯麻煩。下面介紹兩種更易用的場合,在指定的場景中可以考慮使用,本節介紹thrift2,下節介紹happybase方式。

環境準備

thrift2是當時爲了適應新的Java API提出來的。它的操作和接口與Java API接口很像,但是目前沒有完全支持所有thrift1的操作,比如HBase 管理相關的接口,如 createTable、majorCompact 等,如果只想查詢或創建等簡單操作,可以考慮使用此種方法。

要求服務端必須開啓thrift2服務,如下

hbase/bin/hbase-daemon.sh start thrift2

客戶端生成連接庫,方法和上節類似,但是需要使用壓縮包中的thrift2/hbase.thrift IDL文件。同樣,如果不想這麼麻煩,直接使用附件代碼中已經編譯好的hbase庫也可,只是如果要使用最新的hbase python接口還是需要自己生成的。

連接

from thrift.transport import TSocket,TTransport
from thrift.protocol import TBinaryProtocol
from hbase import THBaseService
from hbase.ttypes import *

# thrift默認端口是9090
socket = TSocket.TSocket('10.202.253.8',9090)
socket.setTimeout(5000)

transport = TTransport.TBufferedTransport(socket)
protocol = TBinaryProtocol.TBinaryProtocolAccelerated(transport)

client = THBaseService.Client(protocol)
transport.open()

# do something

transport.close()

查詢

可以看到thrift2使用方式和Java API很像,需要使用TGet包裹查詢信息,如下:

# 獲取指定rowkey指定列族信息
tget = TGet(row='row_key1')
tresult = client.get('table1', tget)
for col in tresult.columnValues:
    print(col.qualifier, '=', col.value)
    
# 獲取指定多行rowkey列族信息
tgets = [TGet(row='row_key1'), TGet(row='row_key2')]
tresults = client.getMultiple('table1', tgets)
for tresult in tresults:
    for col in tresult.columnValues:
        print(col.qualifier, '=', col.value)

掃描

使用TScan包裹查詢信息,如下:

# 指定開始、結束、filter等信息掃描       
scanner_id = client.openScanner(
    table='table1',
    tscan=TScan(
        startRow='000',
        stopRow='002',
        columns=[TColumn('c1')],
        filterString = "(PrefixFilter ('001') AND (QualifierFilter (=, 'binary:m')))"
    )
)

try:
    num_rows = 10
    
    tresults = client.getScannerRows(scanner_id, num_rows)
    for tresult in tresults:
        print(tresult)
finally:
    client.closeScanner(scanner_id)

源碼下載

演示源碼下載鏈接

本文只演示了查詢,其他操作可參考文章

原創,轉載請註明來自

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