使用HBase Shell读取数据
获取命令和 HTable get()方法> class用于从HBase中的表中读取数据.使用 get 命令,您可以一次获得一行数据.其语法如下:
get'< table name>','row1'
示例
以下示例说明如何使用get命令.让我们扫描 \\ temp 表的第一行.
hbase(main):012:0> get 'emp', '1' COLUMN CELL personal : city timestamp = 1417521848375, value = hyderabadpersonal : name timestamp = 1417521785385, value = ramuprofessional: designation timestamp = 1417521885277, value = managerprofessional: salary timestamp = 1417521903862, value = 500004 row(s) in 0.0270 seconds
读取特定列
以下是使用特定列读取特定列的语法获取方法.
hbase> get 'table name', ‘rowid’, {COLUMN ⇒ ‘column family:column name ’}
示例
下面给出了读取HBase中特定列的示例table.
hbase(main):015:0> get 'emp', 'row1', {COLUMN ⇒ 'personal:name'} COLUMN CELL personal:name timestamp = 1418035791555, value = raju1 row(s) in 0.0080 seconds
使用Java API读取数据
要从HBase表中读取数据,请使用HTable类的 get()方法.此方法需要 Get 类的实例.按照下面给出的步骤从HBase表中检索数据.
步骤1:实例化配置类
配置 class将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 = new Get(toBytes("row1"));
第4步:读取数据
在检索数据时,您可以按ID获取单行,或者获取一组行ID的一组行,或扫描整个表或行的子集.
您可以使用获取中的add方法变体检索HBase表数据类.
要从特定列族获取特定列,请使用以下方法.
get.addFamily(personal)
要获取特定列族的所有列,请使用以下方法.
get.addColumn(personal,name)
第5步:获取结果
通过将获取类实例传递给 HTable 类的get方法来获取结果.此方法返回 Result 类对象,该对象保存请求的结果.下面给出了 get()方法的用法.
Result result = table.get(g);
步骤6:从结果实例中读取值
结果类提供 getValue()方法从其实例中读取值.如下所示使用它来读取结果实例中的值.
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