HBase 是列式非关系型数据库 ,核心操作基于 行键 (RowKey) 、列族 (ColumnFamily) 、列 (Column) 、版本 (Version) 展开。我会用 HBase Shell 命令 (最常用)和 Java API 两种方式,完整演示增、删、改、查操作。
一、前置准备
先创建测试表(所有操作基于此表):
shell
# 进入 HBase Shell
hbase shell
# 创建表:表名 test,列族 info、score
create 'test', 'info', 'score'
二、增(插入数据)
HBase 没有专门的 update 操作 ,插入和修改共用 put 命令:
- RowKey 不存在 = 新增数据
- RowKey 已存在 = 覆盖数据(修改)
1. Shell 方式
shell
# 语法:put '表名', '行键', '列族:列', '值'
# 插入 3 条学生数据
put 'test', 'student_001', 'info:name', '张三'
put 'test', 'student_001', 'info:age', '20'
put 'test', 'student_001', 'score:math', '95'
put 'test', 'student_002', 'info:name', '李四'
put 'test', 'student_002', 'score:english', '88'
2. Java API 方式
java
运行
// 核心:Put 对象插入数据
Put put = new Put(Bytes.toBytes("student_003"));
// 添加列族:列:值
put.addColumn(Bytes.toBytes("info"), Bytes.toBytes("name"), Bytes.toBytes("王五"));
put.addColumn(Bytes.toBytes("score"), Bytes.toBytes("math"), Bytes.toBytes("90"));
// 执行插入
table.put(put);
三、改(更新数据)
直接用 put 覆盖原有数据即可,HBase 会自动保留多版本(默认保留 1 个版本)。
1. Shell 方式
shell
# 修改 student_001 的年龄为 21
put 'test', 'student_001', 'info:age', '21'
# 修改 math 成绩为 98
put 'test', 'student_001', 'score:math', '98'
2. Java API 方式
java
运行
Put put = new Put(Bytes.toBytes("student_001"));
// 覆盖原有 age 值
put.addColumn(Bytes.toBytes("info"), Bytes.toBytes("age"), Bytes.toBytes("21"));
table.put(put);
四、删(删除数据)
HBase 支持三级删除:删除列 → 删除列族 → 删除整行。
1. Shell 方式
shell
# 1. 删除指定列(最常用)
delete 'test', 'student_001', 'info:age'
# 2. 删除整行
deleteall 'test', 'student_002'
# 3. 清空整张表(保留表结构)
truncate 'test'
2. Java API 方式
java
运行
// 1. 删除指定列
Delete delete = new Delete(Bytes.toBytes("student_001"));
delete.addColumn(Bytes.toBytes("info"), Bytes.toBytes("age"));
table.delete(delete);
// 2. 删除整行
Delete deleteAll = new Delete(Bytes.toBytes("student_002"));
table.delete(deleteAll);
五、查(查询数据)
配合增删改使用,验证结果。
1. Shell 方式
shell
# 1. 查询单行数据(最常用)
get 'test', 'student_001'
# 2. 查询全表数据
scan 'test'
# 3. 查询指定列族/列
get 'test', 'student_001', 'info'
get 'test', 'student_001', 'score:math'
六、完整操作示例(Shell 一键复制执行)
shell
# 1. 创建表
create 'test', 'info', 'score'
# 2. 新增数据
put 'test', 's001', 'info:name', '张三'
put 'test', 's001', 'info:age', '20'
put 'test', 's001', 'score:math', '95'
# 3. 修改数据
put 'test', 's001', 'info:age', '21'
# 4. 查询验证
get 'test', 's001'
# 5. 删除列
delete 'test', 's001', 'info:age'
# 6. 再次查询
get 'test', 's001'
# 7. 删除整行
deleteall 'test', 's001'
总结
- 增 / 改 :统一用
put,RowKey 不存在 = 新增,存在 = 修改 - 删 :
delete删列,deleteall删行,truncate清空表 - 查 :
get查单行,scan查全表 - 核心定位:表名 + RowKey + 列族:列