HBase看完这篇你还有什么不懂?(HBase API-1.2常用类及java代码实现)

一、基本类

1、Admin类

管理可以用于创建、删除、列出、启用和禁用表、添加和删除表列族以及其他管理操作。

2、Connection接口

一个集群连接,封装了与实际服务器的低级别单独连接以及与zookeeper的连接。 连接通过ConnectionFactory类实例化。 连接的生命周期由调用者管理,使用后必须调用close()连接以释放资源。

连接实现是线程安全的,因此客户端可以创建一次连接,并与不同的线程共享它。另一方面,表和管理实例重量轻,不是线程安全的。通常,每个客户端应用程序的单个连接都会被实例化,并且每个线程都将获得自己的Table实例。不建议缓存或共享Table和Admin。

3、Table类

用于与单个HBase表通信。 从Connection获取实例并在之后调用close()。

表可用于从表中Get,Put,Delete或Scan数据。

4、Put类

用于执行单行的Put操作。

要执行Put,请实例化一个Put对象,其中要插入的行和要插入的每个列,如果设置时间戳,请执行add。

5、Get类

用于对单行执行Get操作。

获取行的所有内容,请使用要获取的行实例化Get对象。 要进一步缩小获取内容的范围,请使用以下方法。

1、获取特定系列的所有列,请为要检索的每个系列执行addFamily()

2、获取特定列,请为要检索的每个列执行addColumn()

3、仅检索特定版本时间戳范围内的列,请执行setTimeRange()

4、仅检索具有特定时间戳的列,请执行setTimestamp()

5、限制要返回的每个列的版本数,请执行setMaxVersions()

6、添加过滤器,请调用setFilter()

6、Scan类

用于执行扫描操作。

除实例化外,所有操作都与Get相同。 可以定义可选的startRow和stopRow,而不是指定单个行。 如果未指定行,则扫描程序将遍历所有行。

1、从Table的所有行获取所有列,请创建一个没有约束的实例; 使用Scan()构造函数。 要将扫描约束到特定列族,请为扫描实例上的每个族调用addFamily()

2、获取特定列,请为要检索的每列调用addColumn()

3、仅检索特定版本时间戳范围内的列,请调用setTimeRange()

4、仅检索具有特定时间戳的列,请调用setTimestamp()

5、限制要返回的每列的版本数,请调用setMaxVersions()

6、限制每次调用next()返回的最大值数,请调用setBatch()

以下为后续更新,代码待更新。。。。。

7、ConnectionFactory类

一个不可实例化的类,用于管理Connections的创建。 管理调用者的责任是管理集群连接的生命周期。 在Connection中,使用Connection.getTable(TableName)检索Table实现。

8、FilterList类

Filter的实现,表示将使用指定的布尔运算符FilterList.Operator.MUST_PASS_ALL(AND)或FilterList.Operator.MUST_PASS_ONE(OR)计算的有序Filter列表。 由于您可以将过滤器列表用作过滤器列表的子项,因此可以创建要评估的过滤器层次结构。

FilterList.Operator.MUST_PASS_ALL延迟评估:只要一个过滤器不包含KeyValue,评估就会停止。

FilterList.Operator.MUST_PASS_ONE非延迟评估:始终评估所有过滤器。

默认为FilterList.Operator.MUST_PASS_ALL。

9、Result类

Get或者Scan当前单行查询的结果

This class is NOT THREAD SAFE.

Convenience methods are available that return various Map structures and values directly.

To get a complete mapping of all cells in the Result, which can include multiple families and multiple versions, use getMap().

To get a mapping of each family to its columns (qualifiers and values), including only the latest version of each, use getNoVersionMap(). To get a mapping of qualifiers to latest values for an individual family use getFamilyMap(byte[]).

To get the latest value for a specific family and qualifier use getValue(byte[], byte[]). A Result is backed by an array of Cell objects, each representing an HBase cell defined by the row, family, qualifier, timestamp, and value.

The underlying Cell objects can be accessed through the method listCells(). This will create a List from the internal Cell []. Better is to exploit the fact that a new Result instance is a primed CellScanner; just call advance() and current() to iterate over Cells as you would any CellScanner. Call cellScanner() to reset should you need to iterate the same Result over again (CellScanners are one-shot). If you need to overwrite a Result with another Result instance -- as in the old 'mapred' RecordReader next invocations -- then create an empty Result with the null constructor and in then use copyFrom(Result)

10、SingleColumnValueFilter类

This filter is used to filter cells based on value. It takes a CompareFilter.CompareOp operator (equal, greater, not equal, etc), and either a byte [] value or a ByteArrayComparable.

If we have a byte [] value then we just do a lexicographic compare. For example, if passed value is 'b' and cell has 'a' and the compare operator is LESS, then we will filter out this cell (return true). If this is not sufficient (eg you want to deserialize a long and then compare it to a fixed long value), then you can pass in your own comparator instead.

You must also specify a family and qualifier. Only the value of this column will be tested. When using this filter on a CellScanner with specified inputs, the column to be tested should also be added as input (otherwise the filter will regard the column as missing).

To prevent the entire row from being emitted if the column is not found on a row, use setFilterIfMissing(boolean). Otherwise, if the column is found, the entire row will be emitted only if the value passes. If the value fails, the row will be filtered out.

In order to test values of previous versions (timestamps), set setLatestVersionOnly(boolean) to false. The default is true, meaning that only the latest version's value is tested and all previous versions are ignored.

 

To filter based on the value of all scanned columns, use ValueFilter.

 

 

 

 

二、java代码实现

package com.dashujuxiansheng.hbase;
//更多大数据知识请点击大数据先生的博客了解:https://blog.csdn.net/weixin_42312342
import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class HBaseDemo {

	Admin admin = null;
	Connection conn = null;
	TableName tn = TableName.valueOf("phone");
	Table table = null;

	@Before
	public void init() throws Exception {
		// 创建配置文件对象
		Configuration conf = new Configuration();
		// 添加连接zookeeper的属性
		conf.set("hbase.zookeeper.quorum", "node001,node002,node003");
		// 通过工厂类创建连接
		conn = ConnectionFactory.createConnection(conf);
		// 获取表的操作对象
		admin = conn.getAdmin();
		table = conn.getTable(tn);
	}

	/**
	 * 创建表
	 * 
	 * @throws Exception
	 */
	@Test
	public void createTable() throws Exception {
		// 表描述对象
		HTableDescriptor desc = new HTableDescriptor(tn);
		// 列族描述对象
		HColumnDescriptor family = new HColumnDescriptor("cf".getBytes());
		desc.addFamily(family);
		// 创建
		if (admin.tableExists(tn)) {
                  //禁用表,再删除
			admin.disableTable(tn);
			admin.deleteTable(tn);
		}
		admin.createTable(desc);
	}

	/**
	 * 插入数据
	 * 
	 * @throws Exception
	 */
	@Test
	public void insertDB() throws Exception {
		Put put = new Put("2222".getBytes());
		put.addColumn("cf".getBytes(), "name".getBytes(), "lisi".getBytes());
		put.addColumn("cf".getBytes(), "age".getBytes(), "124".getBytes());
		put.addColumn("cf".getBytes(), "gender".getBytes(), "women".getBytes());
		table.put(put);
	}

	/**
	 * 获取数据
	 * 
	 * @throws Exception
	 */
	@Test
	public void get() throws Exception {
		Get get = new Get("1111".getBytes());
		get.addColumn("cf".getBytes(), "name".getBytes());
		get.addColumn("cf".getBytes(), "age".getBytes());
		get.addColumn("cf".getBytes(), "gender".getBytes());
		Result rs = table.get(get);
		// System.out.println(Bytes.toString((rs.getValue("cf".getBytes(),
		// "name".getBytes()))));
		// System.out.println(Bytes.toString((rs.getValue("cf".getBytes(),
		// "age".getBytes()))));
		// System.out.println(Bytes.toString((rs.getValue("cf".getBytes(),
		// "gender".getBytes()))));
		Cell cell1 = rs.getColumnLatestCell("cf".getBytes(), "name".getBytes());
		Cell cell2 = rs.getColumnLatestCell("cf".getBytes(), "age".getBytes());
		Cell cell3 = rs.getColumnLatestCell("cf".getBytes(), "gender".getBytes());
		String name = Bytes.toString(CellUtil.cloneValue(cell1));
		String age = Bytes.toString(CellUtil.cloneValue(cell2));
		String gender = Bytes.toString(CellUtil.cloneValue(cell3));
		System.out.println(name + "--" + age + "--" + gender);
	}
	
	/**
	 * 查询全部数据
	 * @throws Exception 
	 */
	@Test
	public void scan() throws Exception{
		Scan scan = new Scan();
//		scan.setStartRow(startRow);
//		scan.setStopRow(stopRow);
		ResultScanner rss = table.getScanner(scan);
		for (Result rs : rss) {
			Cell cell1 = rs.getColumnLatestCell("cf".getBytes(), "name".getBytes());
			Cell cell2 = rs.getColumnLatestCell("cf".getBytes(), "age".getBytes());
			Cell cell3 = rs.getColumnLatestCell("cf".getBytes(), "gender".getBytes());
			String name = Bytes.toString(CellUtil.cloneValue(cell1));
			String age = Bytes.toString(CellUtil.cloneValue(cell2));
			String gender = Bytes.toString(CellUtil.cloneValue(cell3));
			System.out.println(name + "--" + age + "--" + gender);
		}
		rss.close();
	}
	
	@After
	public void destory() throws Exception {
		admin.close();
		conn.close();
	}
}

 

 

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值