插入数据
HTable通过put方法来插入数据。
public void put(final Put put) throws IOException
public void put(final List puts) throws IOException
可以传递单个批Put对象或者List put对象来分别实现单条插入和批量插入。
Put提供了3种构造方式:
public Put(byte [] row)
public Put(byte [] row, RowLock rowLock)
public Put(Put putToCopy)
Put常用的方法有:
add:增加一个Cell
setTimeStamp:指定所有cell默认的timestamp,如果一个Cell没有指定timestamp,就会用到这个值。如果没有调用,HBase会将当前时间作为未指定timestamp的cell的timestamp.
setWriteToWAL: WAL是Write Ahead Log的缩写,指的是HBase在插入操作前是否写Log。默认是打开,关掉会提高性能,但是如果系统出现故障(负责插入的Region Server挂掉),数据可能会丢失。
另外HTable也有两个方法也会影响插入的性能
setAutoFlash: AutoFlush指的是在每次调用HBase的Put操作,是否提交到HBase Server。默认是true,每次会提交。如果此时是单条插入,就会有更多的IO,从而降低性能.
setWriteBufferSize: Write Buffer Size在AutoFlush为false的时候起作用,默认是2MB,也就是当插入数据超过2MB,就会自动提交到Server
Example:
HTable table = new HTable(hbaseConfig, tableName);
table.setAutoFlush(autoFlush);
List lp = new ArrayList();
int count = 10000;
byte[] buffer = new byte[1024];
Random r = new Random();
for (int i = 1; i <= count; ++i) {
Put p = new Put(String.format(“row%09d”,i).getBytes());
r.nextBytes(buffer);
p.add(“f1″.getBytes(), null, buffer);
p.add(“f2″.getBytes(), null, buffer);
p.add(“f3″.getBytes(), null, buffer);
p.add(“f4″.getBytes(), null, buffer);
p.setWriteToWAL(wal);
lp.add(p);
if(i%1000==0){
table.put(lp);
lp.clear();
}
}
删除数据
HTable 通过delete方法来删除数据。
public void delete(final Delete delete)
Delete构造方法有:
public Delete(byte [] row)
public Delete(byte [] row, long timestamp, RowLock rowLock)
public Delete(final Delete d)
Delete常用方法有
deleteFamily/deleteColumns:指定要删除的family或者column的数据。如果不调用任何这样的方法,将会删除整行。
注意:如果某个Cell的timestamp高于当前时间,这个Cell将不会被删除,仍然可以查出来。
Example:
HTable table = new HTable(hbaseConfig, “mytest”);
Delete d = new Delete(“row1″.getBytes());
table.delete(d)
切分表
HBaseAdmin提供split方法来将table 进行split.
public void split(final String tableNameOrRegionName)
如果提供的tableName,那么会将table所有region进行split ;如果提供的region Name,那么只会split这个region.
由于split是一个异步操作,我们并不能确切的控制region的个数。
Example:
public void split(String tableName,int number,int timeout) throws Exception {
Configuration HBASE_CONFIG = new Configuration();
HBASE_CONFIG.set(“hbase.zookeeper.quorum”, GlobalConf.ZOOKEEPER_QUORUM);
HBASE_CONFIG.set(“hbase.zookeeper.property.clientPort”, GlobalConf.ZOOKEEPER_PORT);
HBaseConfiguration cfg = new HBaseConfiguration(HBASE_CONFIG);
HBaseAdmin hAdmin = new HBaseAdmin(cfg);
HTable hTable = new HTable(cfg,tableName);
int oldsize = 0;
t = System.currentTimeMillis();
while(true){
int size = hTable.getRegionsInfo().size();
logger.info(“the region number=”+size);
if(size>=number ) break;
if(size!=oldsize){
hAdmin.split(hTable.getTableName());
oldsize = size;
} else if(System.currentTimeMillis()-t>timeout){
break;
}
Thread.sleep(1000*10);
}
}