之前做項目都是使用java連接操作 hbase 的,或者偶爾用 python 寫幾個一些簡單的 put、get 操作。最近在使用mysql庫批量向 hbase 導入數據,想使用python試一下。HBase是Apache的Hadoop項目的子項,HBase不同於一般的關係數據庫,它是一個適合於非結構化數據存儲的數據庫,適合於非結構化數據存儲,另一個不同的是HBase基於列的而不是基於行的開源數據庫。HappyBase 是 FaceBook 員工開發的操作 HBase 的 Python 庫,其基於 Python Thrift,但使用方式比 Thrift 簡單、簡潔許多,已被廣泛應用。Python調用happybase庫或hbase-thrift庫使用thrift操作Hbase,thrift 是facebook開發並開源的一個二進制通訊中間件。
啟動hbase thriftserver服務
hbase本身已經集成了thrift,可與第三方應用通信。使用以下命令開啟hbase thrift的服務器端,默認情況下rpc監聽9090端口. hbase-daemon.sh start thrift2
查看webui:
http://ip:9095/
方法一 使用happybase 連接hbase
使用pip安裝依賴:
pip install thrift
pip install happybase
happybase.Connection(host='localhost', port=9090, timeout=None, autoconnect=True, table_prefix=None, table_prefix_separator=b'_', compat='0.98', transport='buffered', protocol='binary')
其中host:主機名,port:端口,timeout:超時時間,autoconnect:連接是否直接打開,table_prefix:用於構造表名的前綴,table_prefix_separator:用於table_prefix的分隔符,compat:兼容模式,transport:運輸模式,protocol:協議。
連接示例代碼:
import happybase
connection = happybase.Connection('localhost', compat='0.90')
connection.open()
print connection.tables()
table = connection.table('test_table')
row = table.row('row1', columns=['data:1'])
print row['data:1']
for key, data in table.scan():
print key, data
connection.close()
方法二使用hbase-thrift 連接hbase
sudo pip install thrift
sudo pip install hbase-thrift
連接示例代碼:
from thrift.transport import TSocket, TTransport
from thrift.protocol import TBinaryProtocol
from hbase import Hbase
from thrift import Thrift
from hbase.ttypes import ColumnDescriptor, Mutation, BatchMutation, TRegionInfo
from hbase.ttypes import IOError, AlreadyExists
transport = TSocket.TSocket('localhost', 9090)
transport.setTimeout(5000)
trans = TTransport.TBufferedTransport(transport)
protocol = TBinaryProtocol.TBinaryProtocol(trans)
client = Hbase.Client(protocol)
transport.open()
client.getTableNames()
閱讀更多 不是急客是極客 的文章