Python访问HBase全攻略(完整版,看这个)

以下是一些使用 HappyBase(一个 Python 客户端库,用于与 HBase 交互)的示例代码,展示了如何连接到 HBase、创建表、插入数据、查询数据和删除数据的基本操作:


1. 安装 HappyBase

(1)确保HDFS、Hbase、Zookeeper服务正常运行:

1.启动hdfs
  start-dfs.sh

2.启动Hbase
  start-hbase.sh

3.开启ThriftServer
  hbase-daemon.sh start thrift
  
4.启动hbase shell
   hbase shell

2. 查看进程

确保具有 ThriftServer

[root@localhost~]# jps
1556 HRegionServer
485 SecondaryNameNode
230 NameNode
1400 HMaster
1993 ThriftServer
1114 HQuorumPeer
2111 Jps
3514 DataNode

3. 连接到 HBase

(1)Windows下安装happybase库:

pip install happybase -i https://pypi.tuna.tsinghua.edu.cn/simple


查看happybase是否安装成功(进入python进行导包):

(2)使用pycharm新建一个python项目(很简单,线下也会讲)

4. 连接到 HBase

import happybase

# 连接到 HBase Thrift 服务
connection = happybase.Connection(host='localhost', port=9090)
print("已连接到 HBase")


# 通过conn对象,调用tables方法,获取hbase中的表格
print(connection .tables())

5 创建表

# 在默认命名空间下创建名为 'test_table' 的表,并定义列族 'cf1'、'cf2'、'cf3'
connection.create_table(
    'table_name',
    {
    	'cf1': dict(max_versions=5),   # 列族1,列族名为 'cf1'
		'cf2': dict(max_versions=3),   # 列族2,列族名为 'cf2'
		'cf3': dict()                  # 列族3,列族名为 'cf3',默认属性
	}  
)
print("表已创建成功!")

#在命名空间bigdata下,创建新表student,包含列族info,属性为默认;包含列族score,属性设置最大版本号为5
conn.create_table("bigdata:student",{"info":dict(),"score":dict(max_versions=5)})
# 以下代码编写得更优美,更好
# 创建名为 'test_table' 的表,并定义列族 'cf'(如果表已存在,可跳过此步骤)
table_name = 'test_table'
if table_name.encode() not in connection.tables():
	connection.create_table(
		table_name,
    	{
    		'cf1': dict()
    	}  
)
print(f"表 {table_name} 已创建成功!")

6.查看表格的列族信息

# 1.获取某个表格对象
table = conn.table("ns:table_name")

# 2.查询表格的列族信息
print(table.families())

7. 插入数据

# 获取表对象
table = connection.table('ns:table_name')
# 表不存在也不会报错,本步骤不会真的链接到HBase,只是在代码内创建一个table对象

# 插入数据
# table.put()接收行键和要存储的数据。数据应该是一个字典,包含多个单元格值,将列名映射到一个值:
table.put(b'row1', {b'cf:col1': b'value1', b'cf:col2': b'value2'})
table.put(b'row2', {b'cf:col1': b'value3', b'cf:col2': b'value4'})


for examples:

stu_table = conn.table('bigdata:student')
stu_tab.put(b"1001",{b"info:name":b"zhangsan",b"info:age":b"20"})
stu_tab.put(b"1002",{b"info:name":b"lisi",b"info:age":b"22"})
stu_tab.put(b"1003",{b"info:name":b"wangwu",b"info:age":b"21"})
stu_tab.put(b"1004",{b"info:name":b"zhaoliu",b"info:age":b"25"})

print("数据已成功插入!")

5. 查询数据

查询单行数据
row = table.row(b'row1')
print(f"Retrieved row:", {row})

#通过行键、列族:列限定符查询某个单元格值
row_name = student_tab.row("row_key1",["cf1:c1"])
print(row_name)
查询多行数据
#通过行键查询多行数据(返回值是字典列表)
row_1_2 = table.rows(["1001","1002"])
print(row_1_2)
查询所有数据
for key, data in table.scan():
    print(f"Row key: {key}, Data: {data}")

6. 删除数据

删除单个单元格
table.delete(b'row1', columns=[b'cf:col1'])
print("Column 'cf:col1' in 'row1' deleted")
删除整行数据
table.delete(b'row2')
print("Row 'row2' deleted")

# 要删除一列或多列而不是整行,还需指定 columns 参数:
table = conn.table('bogdata:student')
#删除某一个单元格数据(所有版本的数据都会删除)
table.delete("1001",columns=["score:nosql"])

7. 删除表

# 先禁用表
connection.disable_table('test_table')

# 然后删除表
connection.delete_table('test_table')
print("表已被删除!")

8. 关闭连接

connection.close()
print("连接已关闭!")

示例流程的完整代码

以下代码整合了上述步骤:

import happybase

def main():
    connection = happybase.Connection(host='localhost', port=9090)
    print("Connected to HBase")
    
    # 创建表
    try:
        connection.create_table('test_table', {'cf': dict()})
        print("Table 'test_table' created")
    except Exception as e:
        print("Table might already exist:", e)
    
    table = connection.table('test_table')

    # 插入数据
    table.put(b'row1', {b'cf:col1': b'value1', b'cf:col2': b'value2'})
    table.put(b'row2', {b'cf:col1': b'value3', b'cf:col2': b'value4'})
    print("Data inserted")
    
    # 查询数据
    print("Row1 data:", table.row(b'row1'))
    for key, data in table.scan():
        print(f"Row key: {key}, Data: {data}")

    # 删除数据
    table.delete(b'row1', columns=[b'cf:col1'])
    print("Column 'cf:col1' in 'row1' deleted")

    # 删除表
    connection.disable_table('test_table')
    connection.delete_table('test_table')
    print("Table 'test_table' deleted")

    # 关闭连接
    connection.close()
    print("Connection closed")

if __name__ == '__main__':
    main()

注意事项

  1. 确保 HBase 的 Thrift 服务已启动,通常可以通过以下命令启动:
    hbase thrift start
    
  2. 替换 localhost9090 为实际的 HBase Thrift 服务主机名和端口。

作者:TheMountainGhost

物联沃分享整理
物联沃-IOTWORD物联网 » Python访问HBase全攻略(完整版,看这个)

发表回复