版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wenzhou1219/article/details/88380513
上篇文章讲述了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)
源码下载
演示源码下载链接
本文只演示了查询,其他操作可参考文章
原创,转载请注明来自