HBase讀取數據

get命令和HTable類的get()方法用於從HBase表中讀取數據。使用 get 命令,可以同時獲取一行數據。它的語法如下:

get ’<table name>’,’row1’

下面的例子說明如何使用get命令。掃描emp表的第一行。

hbase(main):012:0> get 'emp', '1' COLUMN CELL

personal : city timestamp=1417521848375, value=hyderabad

personal : name timestamp=1417521785385, value=ramu

professional: designation timestamp=1417521885277, value=manager

professional: salary timestamp=1417521903862, value=50000 4 row(s) in 0.0270 seconds

讀取指定列

下面給出的是語法,使用get方法讀取指定列。

hbase>get 'table name', ‘rowid’, {COLUMN => ‘column family:column name ’}

下面給出的示例,是用於讀取HBase表中的特定列。

hbase(main):015:0> get 'emp', 'row1', {COLUMN=>'personal:name'} COLUMN CELL

personal:name timestamp=1418035791555, value=raju 1 row(s) in 0.0080 seconds

使用Java API讀取數據

從一個HBase表中讀取數據,要使用HTable類的get()方法。這種方法需要Get類的一個實例。按照下面從HBase表中檢索數據給出的步驟。

第1步:實例化Configuration類

Configuration類增加了HBase的配置文件到它的對象。使用HbaseConfiguration類的create()方法,如下圖所示的配置對象。

Configuration conf = HbaseConfiguration.create();

第2步:實例化HTable類

有一類叫HTable,實現在HBase中的Table類。此類用於單個HBase的表進行通信。在這個類實例,它接受配置對象和表名作爲參數。實例化HTable類,如下圖所示。

HTable hTable = new HTable(conf, tableName);

第3步:實例化獲得類

可以從HBase表使用HTable類的get()方法檢索數據。此方法提取從一個給定的行的單元格。它需要一個 Get 類對象作爲參數。創建如下圖所示。

Get get = new Get(toBytes("row1"));

第4步:讀取數據

當檢索數據,可以通過ID得到一個單列,或得到一組行一組行ID,或者掃描整個表或行的子集。

可以使用Get類的add方法變種檢索HBase表中的數據。

從特定的列族獲取指定的列,使用下面的方法。

get.addFamily(personal)

要得到一個特定的列族的所有列,使用下面的方法。

get.addColumn(personal, name)

第5步:獲取結果

獲取結果通過Get類實例的HTable類的get方法。此方法返回Result類對象,其中保存所請求的結果。下面給出的是get()方法的使用。

Result result = table.get(g);

第6步:從Result實例讀值

Result 類提供getValue()方法從它的實例讀出值。如下圖所示,使用它從Result 實例讀出值。

byte [] value = result.getValue(Bytes.toBytes("personal"),Bytes.toBytes("name")); byte [] value1 = result.getValue(Bytes.toBytes("personal"),Bytes.toBytes("city"));

下面給出的是從一個HBase表中讀取值的完整程序

import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.client.Get; import org.apache.hadoop.hbase.client.HTable; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.util.Bytes; public class RetriveData{ public static void main(String[] args) throws IOException, Exception{ // Instantiating Configuration class Configuration config = HBaseConfiguration.create(); // Instantiating HTable class HTable table = new HTable(config, "emp"); // Instantiating Get class Get g = new Get(Bytes.toBytes("row1")); // Reading the data Result result = table.get(g); // Reading values from Result class object byte [] value = result.getValue(Bytes.toBytes("personal"),Bytes.toBytes("name")); byte [] value1 = result.getValue(Bytes.toBytes("personal"),Bytes.toBytes("city")); // Printing the values String name = Bytes.toString(value); String city = Bytes.toString(value1); System.out.println("name: " + name + " city: " + city); } }

編譯和執行上述程序如下所示。

$javac RetriveData.java
$java RetriveData

下面列出的是輸出:

name: Raju city: Delhi