HBase 技术
HBase 是一个分布式、可扩展的列式数据库,适用于实时随机读写大规模数据。
HBase 架构
概述
HBase 采用主从架构,具有高可用性和强一致性的特点。
架构组成
- HMaster: 管理集群的元数据和 RegionServer
- RegionServer: 管理多个 Region,处理数据读写请求
- ZooKeeper: 协调集群状态,选举主节点
数据模型
Table
├── Row Key (行键)
│ ├── Column Family 1
│ │ ├── Qualifier 1: Value 1 (Timestamp)
│ │ └── Qualifier 2: Value 2 (Timestamp)
│ └── Column Family 2
│ └── Qualifier 3: Value 3 (Timestamp)HBase Shell
基本命令
bash
# 创建表
create 'user_profile', 'info', 'address'
# 插入数据
put 'user_profile', 'user001', 'info:name', 'Alice'
put 'user_profile', 'user001', 'info:age', '25'
put 'user_profile', 'user001', 'address:city', 'Beijing'
# 查询数据
get 'user_profile', 'user001'
get 'user_profile', 'user001', 'info'
# 扫描表
scan 'user_profile'
scan 'user_profile', {STARTROW => 'user001', ENDROW => 'user010'}
# 删除数据
delete 'user_profile', 'user001', 'info:age'
# 删除表
disable 'user_profile'
drop 'user_profile'Phoenix
概述
Phoenix 是 HBase 的 SQL 查询引擎,允许使用 SQL 语句查询 HBase 数据。
SQL 操作
sql
-- 创建表
CREATE TABLE IF NOT EXISTS user_profile (
user_id VARCHAR PRIMARY KEY,
name VARCHAR,
age INTEGER,
city VARCHAR
);
-- 插入数据
UPSERT INTO user_profile VALUES ('user001', 'Alice', 25, 'Beijing');
UPSERT INTO user_profile VALUES ('user002', 'Bob', 30, 'Shanghai');
-- 查询数据
SELECT * FROM user_profile WHERE age > 25;
-- 更新数据
UPSERT INTO user_profile SET city = 'Guangzhou' WHERE user_id = 'user001';
-- 删除数据
DELETE FROM user_profile WHERE user_id = 'user002';
-- 创建索引
CREATE INDEX idx_city ON user_profile(city);Java API
java
Configuration config = HBaseConfiguration.create();
try (Connection conn = ConnectionFactory.createConnection(config);
Table table = conn.getTable(TableName.valueOf("user_profile"))) {
// 插入数据
Put put = new Put(Bytes.toBytes("user001"));
put.addColumn(Bytes.toBytes("info"), Bytes.toBytes("name"), Bytes.toBytes("Alice"));
table.put(put);
// 查询数据
Get get = new Get(Bytes.toBytes("user001"));
Result result = table.get(get);
byte[] value = result.getValue(Bytes.toBytes("info"), Bytes.toBytes("name"));
System.out.println(Bytes.toString(value));
}