HBase 读取数据
使用 HBase Shell 读取数据
HTable 类的
get 命令和
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 表中检索数据。
第一步:实例化配置类
Configuration 类将 HBase 配置文件添加到其对象中。您可以使用
HbaseConfiguration 类的
create() 方法创建配置对象,如下所示。
Configuration conf = HbaseConfiguration.create();
第 2 步:实例化 HTable 类
您有一个名为
HTable 的类,它是 HBase 中 Table 的实现。此类用于与单个 HBase 表进行通信。在实例化这个类时,它接受配置对象和表名作为参数。您可以实例化 HTable 类,如下所示。
HTable hTable = new HTable(conf, tableName);
第 3 步:实例化 Get 类
您可以使用
HTable 类的
get() 方法从 HBase 表中检索数据。此方法从给定行中提取单元格。它需要一个
Get 类对象作为参数。如下图创建。
Get get = new Get(toBytes("row1"));
第 4 步:读取数据
在检索数据时,您可以通过 id 获取单行,或者通过一组行 id 获取一组行,或者扫描整个表或行的子集。
您可以使用
Get 类中的 add 方法变体来检索 HBase 表数据。
要从特定列族中获取特定列,请使用以下方法。
要获取特定列族中的所有列,请使用以下方法。
get.addColumn(personal, name)
步骤 5:获取结果
通过将您的
Get 类实例传递给
HTable 类的 get 方法来获取结果。此方法返回
Result 类对象,该对象保存请求的结果。下面给出了
get() 方法的用法。
Result result = table.get(g);
步骤 6:从结果实例中读取值
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
以下应该是输出: