python鏈接hbase

python經過thrift鏈接hbasepython

安裝thrift

pip install thrift

編譯thrift hbase idl文件

thrift提供了兩個版本的idl文件:https://github.com/apache/hbase/tree/master/hbase-thrift/src/main/resources/org/apache/hadoop/hbasegit

首先,thrift2 模仿了 HBase Java API 的數據類型和方法定義,調用方式更人性化一些。好比,構建一個 Get 操做的 Java 代碼是:github

Get get = new Get(Bytes.toBytes("rowkey"));
get.addColumn(Bytes.toBytes("cf"), Bytes.toBytes("col1"));
get.addColumn(Bytes.toBytes("cf"), Bytes.toBytes("col2"));

在 thrift2 中有對應的 TGet 類型:web

tget = TGet(
    row='rowkey',
    columns=[
        TColumn(family='cf', qualifier='col1'),
        TColumn(family='cf', qualifier='col2'),
    ]
)

若是使用舊版的 thrift,咱們就須要直接調用其衆多的 get 方法之一了:apache

client.getRowWithColumns(
    tableName='tbl',
    row='rowkey',
    columns=['cf:col1', 'cf:col2'],
    attributes=None
)

第二個不一樣點在於 thrift2 目前尚缺乏 HBase 管理相關的接口,如 createTable、majorCompact 等。這些 API 仍在開發過程當中,所以若是你須要經過 Thrift 來建表或維護 HBase,就只能使用舊版的 thrift 了。api

決定了使用哪一個版本的描述文件後,咱們就能夠將 hbase.thrift 下載到本地,經過它來生成 Python 代碼。python2.7

thrift -gen py hbase.thrift

生產結果文件夾gen-py,內容以下:oop

gen-py/hbase/__init__.py
gen-py/hbase/constants.py
gen-py/hbase/THBaseService.py
gen-py/hbase/ttypes.py

cp裏面文件到指定python安裝目錄site-packages裏spa

cp -R hbase /usr/lib/python2.7/site-packages/

查詢數據

thrift.net

from thrift import Thrift
from thrift.transport import TSocket, TTransport
from thrift.protocol import TBinaryProtocol
from hbase import Hbase
 
#server端地址和端口,web是HMaster也就是thriftServer主機名,9090是thriftServer默認端口
transport = TSocket.TSocket('web', 9090)
#能夠設置超時
transport.setTimeout(5000)
#設置傳輸方式(TFramedTransport或TBufferedTransport)
trans = TTransport.TBufferedTransport(transport)
#設置傳輸協議
protocol = TBinaryProtocol.TBinaryProtocol(trans)
#肯定客戶端
client = Hbase.Client(protocol)
#打開鏈接
transport.open()
 
from hbase.ttypes import ColumnDescriptor, Mutation, BatchMutation, TRegionInfo
from hbase.ttypes import IOError, AlreadyExists
 
#獲取表名
client.getTableNames()

#api說明https://blog.csdn.net/y472360651/article/details/79055875

thrift2

from thrift.transport import TSocket
from thrift.protocol import TBinaryProtocol
from thrift.transport import TTransport
from hbase import THBaseService

transport = TTransport.TBufferedTransport(TSocket.TSocket('127.0.0.1', 9090))
protocol = TBinaryProtocol.TBinaryProtocolAccelerated(transport)
client = THBaseService.Client(protocol)
transport.open()
# 使用 client 實例進行操做
from hbase.ttypes import TPut, TColumnValue, TGet
tput = TPut(
    row='sys.cpu.user:20180421:192.168.1.1',
    columnValues=[
        TColumnValue(family='cf', qualifier='1015', value='0.28'),
    ]
)
client.put('tsdata', tput)

tget = TGet(row='sys.cpu.user:20180421:192.168.1.1')
tresult = client.get('tsdata', tget)
for col in tresult.columnValues:
    print(col.qualifier, '=', col.value)
transport.close()

#api說明https://blog.csdn.net/zjerryj/article/details/80045657
相關文章
相關標籤/搜索