HBase实战(3)HBase 数据操作,
存储数据
必须使用一个独一无二的用户名作为行键
Put p = new Put(Bytes.toBytes("TheRealMT"));
p.add(Bytes.toBytes("info"),
Bytes.toBytes("name"),
Bytes.toBytes("MarkTwain"));
p.add(Bytes.toBytes("info"),
Bytes.toBytes("email"),
Bytes.toBytes("aa@qq.com"));
p.add(Bytes.toBytes("info"),
Bytes.toBytes("password"),
Bytes.toBytes("123456");
usersTable.put(p);
/**
HBase使用坐标来定位表中的数据:行键是第一个屮标,下一个是列族。
列 族用做数据坐标时,表示一组列。再—个坐标是列限定符(columnqualifier),
表中确定一个单元的 坐标是[rowkey,columnfamily, columnqualifier]
**/
修改数据
HBase中修改数据,在正确的坐标上给出数据,提交到表。
Put p = new Put(Bytes.toBytes("TheRealMT"));
p.add(ByteB.toBytes("info"),
Bytes.toBytes("password"),
Bytes.toBytes("bcl23");
usersTable.put(p);
工作机制:HBase写路径
默认情况下,执行写人时会写到两个地方:HLog和MemStore。
只冇当这两个地方的变化信息都写入并确认后,才认为写动作完成。
memStore是内存里的写人缓冲区,HBase中数据在永久写人硬盘之前在这里积累。 当MemStore填满后,其中的数据会刷到硬盘,生成一个HFile。HFile是HBase使用 的底层存储格式。HFile对应于列族.一个列族可以有多个HFile,何一个HFile不能存 储多个列族的数据,在集群的每个节点上,每个列族有一个MemStore。
如果HBase眼务器宕机,没冇从MemStore里写到HFile的数据将可以通过回放 WAL来恢复。
如采你想测试一下,如下代码可以禁用HLog:
PuC p = new Put ();
p.setWriteToWAL(false);
读数据
创建一个GET实例,指定单元,提交到表:
Get g = new Get(Bytea.toBytes<"TheRealMT"));
Result r = usersTable.get(g);
为了返列password,可以执行命令addColumn()。
对于列族同样可以执行命令addFamily(),下面的例子可以返问指定列族的所有列:
Get g = new Get(Bytes.toBytes("TheRealMT"));
g.addColumn(
Bytes.toBytes("info"),
Bytes.toBytes1"password"));
Result r = usersTable.get(g);
检索特定值,从字节转换回宇符串,如下所示:
Get g = new Get(Bytes.toBytes("TheRealMT"))j
g.addFamily(Bytes.toByte8("info"));
byte[] b = r.getValue(
Bytes.toBytes("info"),
Bytes.toBytes("email"));
String email = Bytes .toString(b) ; //
工作机制:HBase读路径
HBase在读操作上使用了 LRU (距离最近最少使用算法)缓存技术:这种缓存也叫做BlockCache,和MemStorce存放在JVM堆里; BlockCache设计用来保存从HHIe里读人内存的频繁访问的数据,避免硬盘读.,每个列 族都冇自己的BlockCache
删除数据
从HBase中刪除数据,基于一个行键创達一个Delete 命令实例:
Delete d = new Delete(Bytes.toBycea("TheRealMT");
usersTable.delete(d);
//也可以指定更多坐标刪除行的一郎分:
Delete d = new Delete(Byte*.toBytes{"TheRealMT"));
d.deleteColumns(
Bytes.toBytes("info"),
Bytes.toBytes("email"));
usersTable.delete(d);
deleteColumns()方法从行中删除一个单元格
deleteColumn()方法删除单元的内容。
合并:HBase的后台工作
Delete命令并不立即删除内容^«实际匕它只是给记录打卜.刪除的标记
直到执行一次大合并(major compaction ),这些标记才会被处理,被删除id录占用的空间才会释放
合并分为两种:小合并(major compaction )和小合并(minorco mpaction )
小合并把多个小HFile合并生成一个大HFile.
大合并将处理给定region的一个列族的所有HFile大合并完成后,这个列族的所有HFile合并成一个文件。
2.2.8有时间版本的数据
List<KeyV«lu«> passwords > r.g«tColumn<
ByteB.toBytes("info"),
Bytes.toBytes("password"));
b « passwords.get (0> .gecValueO ;
String currentPasswd > Bytes.toString(b); // M*bcl23"
b = passwords .get (1) .getValueO ;
String prevPasswd = Byte9.toString<b); // "Langhorne"
long version =
passwords.get(0).getTimestamp(); // 1329088818321
2.2.9数据模型概括