查詢 HBase 獲取刪除和掃描

在 HBase 中,你可以使用 4 種型別的操作

  • 獲取 :檢索一行
  • Put :插入一行或多行
  • 刪除 :刪除一行
  • 掃描 :檢索多行

如果你只是想檢索一行,給定它的 row_key 你可以使用 Get 物件:

Get get = new Get(Bytes.toBytes("my_row_key"));
Table table = this.connection.getTable(TableName.valueOf("myTable"));
Result r = table.get(get);
byte[] value = r.getValue(Bytes.toBytes(columnFamily), Bytes.toBytes("myColumn"));
String valueStr = Bytes.toString(value);
System.out.println("Get result :" + valueStr);

這裡我們只從我們想要的列中獲取值,如果要檢索所有列,請使用 Get 物件的 rawCell 屬性:

Get get = new Get(Bytes.toBytes(rowKey));
Table table = this.connection.getTable(TableName.valueOf(tableName));
Result r = table.get(get);
System.out.println("GET result :");
    for (Cell c : r.rawCells()) {
        System.out.println("Family : " + new String(CellUtil.cloneFamily(c)));
        System.out.println("Column Qualifier : " + new String(CellUtil.cloneQualifier(c)));
        System.out.println("Value : " + new String(CellUtil.cloneValue(c)));
        System.out.println("----------");
    }

好吧,我們現在可以逐行從表中檢索資料,但是我們如何設定一些呢?你使用 Put 物件:

Put put = new Put("my_row_key");
put.addColumn(Bytes.toBytes("myFamily"), Bytes.toBytes("myColumn"), Bytes.toBytes("awesomeValue");
//Add as many columns as you want

Table table = connection.getTable(TableName.valueOf("myTable");
table.put(put);

注意:Table.put 也可以在引數中輸入一個 put 列表,也就是說,當你想要新增很多行時,比 put 更有效。

好吧,現在,我可以放一些行並從我的 HBase 中檢索一些,但是如果我想得到幾行並且如果我不知道我的 row_keys 怎麼辦?

隊長在這裡! 你可以使用 Scan 物件:

掃描基本上檢視所有行並檢索它們,你可以新增幾個引數,例如過濾器和開始/結束行,但我們將在另一個示例中看到。

如果要掃描表中的所有列值,請在給定列的情況下使用以下行:

Table table = this.connection.getTable(TableName.valueOf("myTable"));
Scan scan = new Scan();
scan.addColumn(Bytes.toBytes("myFamily"), Bytes.toBytes("myColumn"));
ResultScanner rs = table.getScanner(scan);
    try {
        for (Result r = rs.next(); r != null; r = rs.next()) {
            byte[] value = r.getValue(Bytes.toBytes("myFamily"), Bytes.toBytes("myCOlumn"));
            String valueStr = Bytes.toString(value);
            System.out.println("row key "+new String(r.getRow()));
            System.out.println("Scan result :" + valueStr);
        }
    } finally {
        rs.close(); // always close the ResultScanner!
   }

我真的很想堅持你必須總是關閉 ResultScanner (順便說一下,從資料庫中的任何 ResultSet 都是這樣的)

就快完成了 ! 現在讓我們學習如何刪除一行。你有一個 Delete 物件:

Table table = this.connection.getTable(TableName.valueOf("myTable"));
Delete d = new Delete(Bytes.toBytes("my_weird_key"));
table.delete(d);
System.out.prinln("Row " + row_key + " from table " + tableName + " deleted");

最後一件事:在執行任何操作之前,始終檢查表是否存在,否則你將獲得異常。

這就是現在,你可以使用此示例管理 HBase 中的資料。