7.python 查詢hbase2 (一)

thrift環境準備

hbase是接口API是java的,如果需要通過python來操作的話,可以使用thrift服務。使用thrift需要部署thrift接口服務和thrift客戶端環境,thrift負責將操作請求翻譯後調用Java API操作,客戶端thrift負責序列化請求後傳輸。示意如下:

thrift結構

客戶端和接口可以裝在同一臺機器上,也可以接口單獨部署成接口服務集羣,需要訪問時客戶機上安裝個thrift客戶端即可,常用的兩種架構如下(參考文章):

集羣模式——性能和可靠性好,線上服務最好這樣部署

thrift集羣部署

本地模式——比較靈活,數據分析自行開啓thrift服務可採用這種方式

thrift本地部署

默認hbase thrift接口服務端口號9090,可在配置文件conf/hbase-site.xml中查看和修改thrift 接口服務的 IP 地址和端口號,如下

<property>
        <name>hbase.master.hostname</name>
        <value>$thriftIP</value>
</property>
<property>
        <name>hbase.regionserver.thrift.port</name>
        <value>$port</value>
</property>

開啓接口服務很簡單,直接運行如下指令

hbase/bin/hbase-daemon.sh start thrift1

客戶端環境準備如下:

  • 安裝thrift,mac和windows可直接安裝,linux下需要編譯,[參考]
  • 安裝python操作thrift庫,如下
pip install thrift
  • 安裝python操作hbase庫

注意這個很重要,網上教程很多要求如下安裝

pip install hbase-thrift

這個雖然能操作,但是這個庫還是2010更新的,很多新特性都不支持,最好方法是找到當前安裝hbase2.0的環境,找到如下文件hbase/lib/hbase-thrift-2.*.jar,解壓後,如下目錄,取出thrift/Hbase.thrift文件,這是thrift的IDL定義文件,如下生成python hbase操作庫

thrift -gen py ./Hbase.thrift

當前目錄下gen-py中hbase目錄拷貝出來即爲python連接hbase庫。這個方法能保證python hbase庫始終是和當前版本最匹配的。

如果不想這麼麻煩,直接使用附件代碼中已經編譯好的hbase庫也可,只是如果要使用最新的hbase python接口還是需要自己生成的。

thrift定義目錄

連接

遵循python thrift標準連接方法如下:

from thrift.transport import TSocket,TTransport
from thrift.protocol import TBinaryProtocol

from hbase import Hbase
from hbase.ttypes import TScan

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

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

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

# do something

transport.close()

查詢

最新python 支持多行和當行查詢,滿足大多數需求,如下:

# 獲取表名列表
print client.getTableNames()

# 獲取指定rowkey指定列族信息
ts = client.get('table1', 'row_key1', 'c1', None)
for t in ts:
    print t.value

# 獲取指定rowkey全部信息    
rows = client.getRow('table1', 'row_key1', None)
for row in rows:
    for k,v in row.columns.items():
        print "%s=>%s" %(k.split(':')[1], v.value)
        
rows = client.getRows('table1', ['row_key1', 'row_key2'], None)
for row in rows:
    for k,v in row.columns.items():
        print "%s=>%s" %(k.split(':')[1], v.value)

掃描

對於複雜查詢或分頁等需求需要通過掃描實現,如下

# 指定開始和結束row_key掃描     
sid = client.scannerOpenWithStop('table1', b'000', b'002', ['c1'], None)
res = client.scannerGetList(sid, 10)
print res
client.scannerClose(sid)

# 指定filter掃描
s = TScan()
s.filterString = "(PrefixFilter ('000') AND (QualifierFilter (=, 'binary:m')))"
sid = client.scannerOpenWithScan('table1', s, None)
res = client.scannerGetList(sid, 10)
print res
client.scannerClose(sid)

第一個指定開始和結束row_key掃描,第二個指定filter來掃描,python hbase庫沒有對應函數實現傳入filter參數的功能,必須通過這種迂迴的方式。sid對應的scanner標記通過scannerGet獲取全部結構,scannerGetList獲取指定條記錄。

源碼下載

演示源碼下載鏈接

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

原創,轉載請註明來自

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