0%

HBase客户端API

HBase客户端API

简单一点,先假定只操作table表,创建table对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 使用Admin对象来操作DDL
private static Admin admin;
// 使用Table对象来操作DML
private static Table table;

static {
try {
// 获取连接
Connection conn = ConnectionFactory.createConnection();
admin = conn.getAdmin();
table = conn.getTable(TableName.valueOf("test"));
} catch (IOException e) {
e.printStackTrace();
}
}

插入数据

先插入一条数据,来方便后续的查找操作

1
2
3
4
5
6
7

public static void testPut(String rowKey,String family,String q,String value) throws IOException {
Put put = new Put(Bytes.toBytes(rowKey));

put.addColumn(Bytes.toBytes(family),Bytes.toBytes(q),Bytes.toBytes(value));
table.put(put);
}
1
testPut("123456","info","name","zs");

获取数据

使用获取数据来验证一下上面是否成功插入了

1
2
3
4
5
6
7
8
public static void testGet(String rowKey,String family,String q) throws IOException {
Get get = new Get(Bytes.toBytes(rowKey));

get.addColumn(Bytes.toBytes(family),Bytes.toBytes(q));
Result result = table.get(get);
byte[] value = result.getValue(Bytes.toBytes(family), Bytes.toBytes(q));
System.out.println(Bytes.toString(value));
}
1
testGet("123456","info","name");

删除数据

1
2
3
4
5
6
public static void testDelete(String rowKey,String family,String q) throws IOException {
Delete delete = new Delete(Bytes.toBytes(rowKey));

delete.addColumn(Bytes.toBytes(family),Bytes.toBytes(q));
table.delete(delete);
}
1
testDelete("123456","info","name");

过滤器

在使用get和scan查询数据时,可以添加过滤器来减少查询的数据量

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public static void testScanWithFilter(String rowKey,String family,String q) throws IOException {
Scan scan = new Scan();
scan.addColumn(Bytes.toBytes(family),Bytes.toBytes(q));
// 分页过滤器,只取一行数据
Filter filter = new PageFilter(1);
scan.setFilter(filter);

ResultScanner scanner = table.getScanner(scan);
for(Result result : scanner){
byte[] value = result.getValue(Bytes.toBytes(family), Bytes.toBytes(q));
System.out.println(Bytes.toString(value));
}

}
1
testScanWithFilter("123456","info","name");

计数器

1
2
3
4
5
6
7
8
9
public static void testIncr(String rowKey, String family, String q) throws IOException {
// 计数器,自增1
tableIncr.incrementColumnValue(Bytes.toBytes(rowKey),
Bytes.toBytes(family), Bytes.toBytes(q), 1);
// 获取计数器当前值,不做自增
long value = tableIncr.incrementColumnValue(Bytes.toBytes(rowKey),
Bytes.toBytes(family), Bytes.toBytes(q), 0);
System.out.println(value);
}
1
testIncr("did222", "camp", "501");

欢迎关注我的其它发布渠道