ToB企服应用市场:ToB评测及商务社交产业平台
标题:
Python访问HBase全攻略(完备版,看这个)
[打印本页]
作者:
徐锦洪
时间:
2024-11-26 03:34
标题:
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()
复制代码
留意事项
确保 HBase 的 Thrift 服务已启动,通常可以通过以下命令启动:
hbase thrift start
复制代码
更换 localhost 和 9090 为实际的 HBase Thrift 服务主机名和端口。
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/)
Powered by Discuz! X3.4