1. HBase shell
具体语法在shell中有提示
命令 | 功能 |
---|---|
list | 查看表,命名空间,命名空间下的表 |
scan | 全表扫描 |
put | 插入单行数据 |
get | 读取数据 |
create | 创建表,命名空间 |
disable | 使表失效,之后才能删除 |
drop | 删除表,命名空间 |
2. HBase Java
初始化和关闭
Connection con;
HBaseAdmin admin;
@Before
public void init() throws IOException {
//1 创建配置对象Configuration
Configuration conf=HBaseConfiguration.create();
//2 添加hdfs根路径和zookeeper集群节点名
conf.set("hbase.rootdir", "hdfs://ghym:9000/hbase");
conf.set("hbase.zookeeper.quorum", "ghym,ghys1,ghys2");
//3 创建连接对象Connection和管理对象HBaseAdmin
con = ConnectionFactory.createConnection(conf);
admin=(HBaseAdmin) con.getAdmin();
}
@After
public void close() throws IOException {
//7 关闭连接
con.close();
admin.close();
}
插入单行数据
@Test
public void putRow() throws IOException {
//表名对象
TableName tname=TableName.valueOf("dept");
//4 通过连接对象得到表对象
Table tab = con.getTable(tname);
//5 创建行对象
Put row=new Put("row8".getBytes());//rowid的字节数组
//6 向行添加数据
//row.addColumn(列族,列名,列值)
row.addColumn("d".getBytes(),"doc".getBytes(),"word".getBytes());
tab.put(row);
}
读取单行数据
@Test
public void getRow() throws IOException {
//1 获取表
TableName tname=TableName.valueOf("dept");
Table tab = con.getTable(tname);
//2 get获得行
Get row=new Get("row8".getBytes());
Result res = tab.get(row);
List<Cell> cells = res.listCells();
for (Cell cell : cells) {
byte[] rb = CellUtil.cloneRow (cell);
String rbs = new String(rb);
byte[] fb = CellUtil.cloneFamily(cell);
String fbs = new String(fb);
byte[] qb = CellUtil.cloneQualifier (cell);
String qbs = new String(qb);
byte[] vb = CellUtil.cloneValue (cell);
String vbs = new String(vb);
System.out.println("行id:"+rbs+",列族:"+fbs+",列名:"+qbs+",列值:"+vbs);
}
}
删除单行数据
@Test
public void delRow() throws IOException {
//1 创建删除对象
Delete del=new Delete("row8".getBytes());
//2 指定删除对象列族下的列
del.addColumn("d".getBytes(),"doc".getBytes());
TableName tname=TableName.valueOf("dept");
Table tab = con.getTable(tname);
tab.delete(del);
}
全表扫描
@Test
public void scan() throws IOException {
//1 定义自定义的扫描对象
Scan scan=new Scan();
//2 设置扫描对象的范围
scan.setStartRow("row1".getBytes());
scan.setStopRow("row9".getBytes());
//3 获取表
TableName tname=TableName.valueOf("dept");
Table tab = con.getTable(tname);
//4 设置扫描对象,返回结果集
ResultScanner res = tab.getScanner(scan);
//5 遍历结果集
Result next = null;
while ((next=res.next())!=null){
//6 得到拆分后的信息
List<Cell> cells = next.listCells();
for (Cell cell : cells) {
byte[] rb = CellUtil.cloneRow (cell);
String rbs = new String(rb);
byte[] fb = CellUtil.cloneFamily(cell);
String fbs = new String(fb);
byte[] qb = CellUtil.cloneQualifier (cell);
String qbs = new String(qb);
byte[] vb = CellUtil.cloneValue (cell);
String vbs = new String(vb);
System.out.println("行id:"+rbs+",列族:"+fbs+",列名:"+qbs+",列值:"+vbs);
}
}
}
删除表
@Test
public void drop() throws IOException {
//使删除的表失效后删除
TableName tname=TableName.valueOf("demo");
admin.disableTable(tname);
admin.deleteTable(tname);
}