安装库happybase
thrift 是facebook开发并提交给Apache的开源二进制通讯中间件。
通过thrift,我们可以用Python来操作Hbase。
happybase是Python通过Thrift访问HBase的库。
pip install thrift pip install happybase
使用
启动thrift
hbase-daemon.sh start thrift
连接测试
import happybase conn = happybase.Connection("192.168.92.145", 9090) print (conn.tables())
表操作
# 创建表---> zhy为表名,info为指定行列为空 conn.create_table('test_table', {"info":{}}) # 删除表--> disable默认为False,删除表的手要修改为True conn.delete_table("test_table", True) # xxx 表示表名,在连接之前要先创建表 table = conn.table("test_table")
Demo
import happybase hostname = '192.168.19.188' table_name = 'users' column_family = 'cf' row_key = 'row_1' conn = happybase.Connection(hostname) def show_tables(): print('show all tables now') tables = conn.tables() for t in tables: print t def create_table(table_name, column_family): print('create table %s' % table_name) conn.create_table(table_name, {column_family:dict()}) def show_rows(table, row_keys=None): if row_keys: print('show value of row named %s' % row_keys) if len(row_keys) == 1: print table.row(row_keys[0]) else: print table.rows(row_keys) else: print('show all row values of table named %s' % table.name) for key, value in table.scan(): print key, value def put_row(table, column_family, row_key, value): print('insert one row to hbase') # column_family:qualifier:value # column_qualifier = name table.put(row_key, {'%s:name' % column_family:'name_%s' % value}) def put_rows(table, column_family, row_lines=30): print('insert rows to hbase now') for i in range(row_lines): put_row(table, column_family, 'row_%s' % i, i) def delete_row(table, row_key, column_family=None, keys=None): if keys: print('delete keys:%s from row_key:%s' % (keys, row_key)) key_list = ['%s:%s' % (column_family, key) for key in keys] table.delete(row_key, key_list) else: print('delete row(column_family:) from hbase') table.delete(row_key) def delete_table(table_name): pretty_print('delete table %s now.' % table_name) conn.delete_table(table_name, True) def main(): table = conn.table(table_name) show_rows(table) put_rows(table, column_family) show_rows(table) # 更新操作 # put_row(table, column_family, row_key, 'xiaoh.me') # show_rows(table, [row_key]) # 删除数据 # delete_row(table, row_key) # show_rows(table, [row_key]) # delete_row(table, row_key, column_family, ['name']) # show_rows(table, [row_key]) # delete_table(table_name) if __name__ == "__main__": main()
停止
如果使用完毕要退出,则依次输入以下命令: ./hbase-daemon.sh stop thrift stop-hbase.sh