创建hbase表:
from thrift import Thrift from thrift.transport import TSocket from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol from hbase import Hbase from hbase.ttypes import * transport = TSocket.TSocket('localhost', 9090); transport = TTransport.TBufferedTransport(transport) protocol = TBinaryProtocol.TBinaryProtocol(transport); client = Hbase.Client(protocol) transport.open() contents = ColumnDescriptor(name='cf:', maxVersions=1) client.createTable('test', [contents]) print client.getTableNames()
执行代码,成功后,进入hbase的shell,用命令list可以看到刚刚的test表已经创建成功。
插入数据:
from thrift import Thrift from thrift.transport import TSocket from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol from hbase import Hbase from hbase.ttypes import * transport = TSocket.TSocket('localhost', 9090) transport = TTransport.TBufferedTransport(transport) protocol = TBinaryProtocol.TBinaryProtocol(transport) client = Hbase.Client(protocol) transport.open() row = 'row-key1' mutations = [Mutation(column="cf:a", value="1")] client.mutateRow('test', row, mutations, None)
获取一行数据:
from thrift import Thrift from thrift.transport import TSocket from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol from hbase import Hbase from hbase.ttypes import * transport = TSocket.TSocket('localhost', 9090) transport = TTransport.TBufferedTransport(transport) protocol = TBinaryProtocol.TBinaryProtocol(transport) client = Hbase.Client(protocol) transport.open() tableName = 'test' rowKey = 'row-key1' result = client.getRow(tableName, rowKey, None) print result for r in result: print 'the row is ' , r.row print 'the values is ' , r.columns.get('cf:a').value
返回多行则需要使用scan:
from thrift import Thrift from thrift.transport import TSocket from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol from hbase import Hbase from hbase.ttypes import * transport = TSocket.TSocket('localhost', 9090) transport = TTransport.TBufferedTransport(transport) protocol = TBinaryProtocol.TBinaryProtocol(transport) client = Hbase.Client(protocol) transport.open() scan = TScan() tableName = 'test' id = client.scannerOpenWithScan(tableName, scan, None) result2 = client.scannerGetList(id, 10) print result2
scannerGet则是每次只取一行数据:
from thrift import Thrift from thrift.transport import TSocket from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol from hbase import Hbase from hbase.ttypes import * transport = TSocket.TSocket('localhost', 9090) transport = TTransport.TBufferedTransport(transport) protocol = TBinaryProtocol.TBinaryProtocol(transport) client = Hbase.Client(protocol) transport.open() scan = TScan() tableName = 'test' id = client.scannerOpenWithScan(tableName, scan, None) result = client.scannerGet(id) while result: print result result = client.scannerGet(id)
查看更多关于python通过thrift操作hbase实例的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://www.haodehen.cn/did86831