hbase2.1.x 批量删除数据(delete)

说明

执行 delete 删除,可以传入 多个 rowkey

相当于 SQL 的:delete from ... where id in ('1','2','3')

底层实现

hbase java api,批量操作的底层,都是调用 batch 方法

批量 delete() 方法在 HTable 类中,声明如下:

@Override
public Result[] get(List<Get> gets) throws IOException {
    if (gets.size() == 1) {
      return new Result[]{get(gets.get(0))};
    }
    try {
      Object[] r1 = new Object[gets.size()];
      batch((List<? extends Row>)gets, r1, readRpcTimeoutMs);
      // Translate.
      Result [] results = new Result[r1.length];
      int i = 0;
      for (Object obj: r1) {
        // Batch ensures if there is a failure we get an exception instead
        results[i++] = (Result)obj;
      }
      return results;
    } catch (InterruptedException e) {
      throw (InterruptedIOException)new InterruptedIOException().initCause(e);
    }
}

解释: 将 多个 Get 对象放入 List 中,然后将 list 传入 get 方法,返回 Result[]

案例

删除 rowkey 是 1001、1002 的数据

相当于 SQL :delete from book where id in ('1001','1002')

添加测试数据

清空表:

truncate 'book'

添加测试数据:

put 'book','1001','c1:title','htlm从入门到放弃'
put 'book','1001','c1:author','lucy'
put 'book','1001','c1:price','097.50'

put 'book','1002','c1:title','css从入门到放弃'
put 'book','1002','c1:author','lili'
put 'book','1002','c1:price','099.90'

put 'book','1003','c1:title','hadoop从入门到放弃'
put 'book','1003','c1:author','韩梅梅'
put 'book','1003','c1:price','190.00'

关键代码

public void delete(String tableName,String[] rowkeys) throws IOException {
    TableName tn=TableName.valueOf(tableName);
    //admin封装对表的操作,创建表、删除表、禁用表、启用表
    Table table = conn.getTable(tn);
    //封装Put对象
    List<Delete> list = new ArrayList<Delete>();

    //遍历 rowkeys数组,创建 Delete对象,并将 rowkey 传入
    for(String item:rowkeys) {
        Delete delete = new Delete(Bytes.toBytes(item));
        list.add(delete);
    }

    //调用delete方法进行删除
    table.delete(list);
    table.close();
}

测试

HbaseBatchUtils hbu = new HbaseBatchUtils();
hbu.connect();
//        hbu.putBatch();
String[] rowkeys = {"1001", "1002"};
//hbu.get("book", rowkeys);
hbu.delete("book",rowkeys);
hbu.close();