HBase初入门

1. hbase简介

1.1 什么是hbase

HBASE是一个高可靠性、高性能、面向列、可伸缩的分布式存储系统,利用HBASE技术可在廉价PC Server上搭建起大规模结构化存储集群。
HBASE的目标是存储并处理大型的数据,更具体来说是仅需使用普通的硬件配置,就能够处理由成千上万的行和列所组成的大型数据。
HBASE是Google Bigtable的开源实现,但是也有很多不同之处。比如:Google Bigtable利用GFS作为其文件存储系统,HBASE利用Hadoop HDFS作为其文件存储系统;Google运行MAPREDUCE来处理Bigtable中的海量数据,HBASE同样利用Hadoop MapReduce来处理HBASE中的海量数据;Google Bigtable利用Chubby作为协同服务,HBASE利用Zookeeper作为对应。

1.2. 与传统数据库的对比

1、传统数据库遇到的问题:
1)数据量很大的时候无法存储
2)没有很好的备份机制
3)数据达到一定数量开始缓慢,很大的话基本无法支撑
2、HBASE优势:
1)线性扩展,随着数据量增多可以通过节点扩展进行支撑
2)数据存储在hdfs上,备份机制健全
3)通过zookeeper协调查找数据,访问速度块。

1.3. hbase集群中的角色

1、一个或者多个主节点,Hmaster
2、多个从节点,HregionServer

2 hbase中的数据模型

HBase初入门_第1张图片

  • RowKey : 与nosql数据库们一样,row key是用来检索记录的主键。访问HBASE table中的行,只有三种方式:
    • 1.通过单个row key访问
    • 2.通过row key的range(正则)
    • 3.全表扫描

Row key行键 (Row key)可以是任意字符串(最大长度 是 64KB,实际应用中长度一般为 10-100bytes),在HBASE内部,row key保存为字节数组。存储时,数据按照Row key的字典序(byte order)排序存储。设计key时,要充分排序存储这个特性,将经常一起读取的行存储放到一起。(位置相关性)

  • Columns Family : 列簇 :HBASE表中的每个列,都归属于某个列族。列族是表的schema的一部 分(而列不是),必须在使用表之前定义。列名都以列族作为前缀。例如 courses:history,courses:math都属于courses 这个列族。
  • Cell 由{row key, columnFamily, version} 唯一确定的单元。cell中 的数据是没有类型的,全部是字节码形式存贮。
    关键字:无类型、字节码
  • Time Stamp

HBASE 中通过rowkey和columns确定的为一个存贮单元称为cell。每个 cell都保存 着同一份数据的多个版本。版本通过时间戳来索引。时间戳的类型是 64位整型。时间戳可以由HBASE(在数据写入时自动 )赋值,此时时间戳是精确到毫秒 的当前系统时间。时间戳也可以由客户显式赋值。如果应用程序要避免数据版 本冲突,就必须自己生成具有唯一性的时间戳。每个 cell中,不同版本的数据按照时间倒序排序,即最新的数据排在最前面。
为了避免数据存在过多版本造成的的管理 (包括存贮和索引)负担,HBASE提供 了两种数据版本回收方式。一是保存数据的最后n个版本,二是保存最近一段 时间内的版本(比如最近七天)。用户可以针对每个列族进行设置。

3 、hbase shell的基本命令

  • 启动HBase的shell命令行,退出命令行
// 启动
#$HBASE_HOME/bin/hbase shell
// 退出
quit
  • 创建表,创建表时不需要指明列,在HBase中列族是表的schema的一部 分而列不是
create '表名', '列族名1','列族名2'......'列族名N'
如:
create 'user123','info1','info2','info3'
  • 查看所有表
list
  • 查看表结构
describe  ‘表名’  如 : describe 'user123'
  • 判断表是否存在
exists  '表名'  如:exists 'user123'
  • 是否禁用启用表
is_enabled '表名'
is_disabled ‘表名’
  • 向表中添加记录
put  ‘表名’, ‘rowKey’, ‘列族 : 列‘  ,  '值'
如:
put 'user123','123','info1:name','zhangsan'
  • 查看记录rowkey下的所有数据
get  '表名' , 'rowKey'
如 : get 'user123','123'
  • 查看表中总的记录数
count  '表名'
  • 获取某个列族的某个列的值
get '表名','rowkey','列族:列’   如: get 'user123','123','info1:name'
  • 删除某个列族的某个列
delete  ‘表名’ ,‘行名’ , ‘列族:列'  如: delete 'user123','123','info1:name'
  • 删除整个记录
deleteall '表名','rowkey'
  • 删除表(drop)
先要屏蔽该表,才能对该表进行删除
第一步 disable ‘表名’ ,第二步  drop '表名'
  • 清空表
truncate '表名'
  • 查询所有记录
scan "表名"  

4 、Java操作hbase的基本API

  • 配置HBase
static Configuration config = null;
	private Connection connection = null;
	private Table table = null;
	
	@Before
	public void init() throws Exception{
		config = HBaseConfiguration.create();
		//配置zookeeper地址
		config.set("hbase.zookeeper.quorum", "mini5,mini6,mini7");
		//zookeeper端口
		config.set("hbase.zookeeper.property.clientPort", "2181");
		connection = ConnectionFactory.createConnection(config);
		table = connection.getTable(TableName.valueOf("user"));
	}
	
	.....................
	@After
	public void close() throws IOException{
		table.close();
		connection.close();
	}
  • 创建HBase表
@Test
	public void createTable() throws Exception{
		//创建表管理类
		HBaseAdmin admin = new HBaseAdmin(config);
		//创建表描述类 表的名称
		TableName tableName = TableName.valueOf("test2");
		HTableDescriptor desc = new HTableDescriptor(tableName);
		//创建列族的描述类 列族
		HColumnDescriptor family = new HColumnDescriptor("info");
		//将列族添加到表中
		desc.addFamily(family);
		//列族描述类
		HColumnDescriptor family2 = new HColumnDescriptor("info2");
		//将列族添加到表中
		desc.addFamily(family2);
		//创建表
		admin.createTable(desc);
	}
  • 删除HBase表(相当于drop)
 @Test
	public void deleteDate() throws IOException{
		//创建要删除的rowkey
		Delete delete = new Delete(Bytes.toBytes("Potter Zha1"));
		//设置要删除的列族
		//delete.addFamily(Bytes.toBytes("info2"));
		//设置要删除的具体列
		delete.addColumn(Bytes.toBytes("info1"), Bytes.toBytes("age"));
		//删除操作
		table.delete(delete);
	}
  • 向HBase表中插入数据
 @Test
	public void insertDate() throws IOException{
	//创建数据封装类
	Put put = new Put(Bytes.toBytes("Potter Zha1"));
	put.add(Bytes.toBytes("info1"),Bytes.toBytes("name"),Bytes.toBytes("zhangsan"));
	put.add(Bytes.toBytes("info1"),Bytes.toBytes("age"),Bytes.toBytes(23));
	put.add(Bytes.toBytes("info1"), Bytes.toBytes("sex"), Bytes.toBytes(0));
	put.add(Bytes.toBytes("info1"), Bytes.toBytes("address"), Bytes.toBytes("NewYork"));
	put.add(Bytes.toBytes("info2"),Bytes.toBytes("occupation"),Bytes.toBytes("software engineer"));
	put.add(Bytes.toBytes("info2"),Bytes.toBytes("hobbit"),Bytes.toBytes("money"));
	//添加数据
	table.put(put);
	}
  • 修改HBase表中数据
	@Test
	public void updateDate() throws IOException{
		//HBase表中通过rowkey判别是是否为同一条记录,同一条记录再次插入即为修改
		//创建数据封装类
		Put put = new Put(Bytes.toBytes("Potter Zha"));
		put.add(Bytes.toBytes("info1"),Bytes.toBytes("name"),Bytes.toBytes("lisi"));
		put.add(Bytes.toBytes("info1"),Bytes.toBytes("age"),Bytes.toBytes("30"));
		put.add(Bytes.toBytes("info1"), Bytes.toBytes("sex"), Bytes.toBytes("1"));
		put.add(Bytes.toBytes("info1"), Bytes.toBytes("address"), Bytes.toBytes("Japan"));
		//添加数据
		table.put(put);
	}
  • 删除HBase表中的数据
    @Test
	public void deleteDate() throws IOException{
		//创建要删除的rowkey
		Delete delete = new Delete(Bytes.toBytes("Potter Zha1"));
		//设置要删除的列族
		//delete.addFamily(Bytes.toBytes("info2"));
		//设置要删除的具体列
		delete.addColumn(Bytes.toBytes("info1"), Bytes.toBytes("age"));
		//删除操作
		table.delete(delete);
	}
  • 查询单条HBase表的记录
@Test
	public void queryData() throws IOException{
		//创建封装查询条件的类
		Get get = new Get(Bytes.toBytes("Potter Zha1"));
		//设置具体查询某列
		//get.addColumn(Bytes.toBytes("info1"),Bytes.toBytes("name"));
		Result result = table.get(get);
		byte[] name  = result.getValue(Bytes.toBytes("info1"), Bytes.toBytes("name"));
		byte[] sex = result.getValue(Bytes.toBytes("info1"), Bytes.toBytes("sex"));
		byte[] address = result.getValue(Bytes.toBytes("info1"), Bytes.toBytes("address"));
		byte[] age = result.getValue(Bytes.toBytes("info1"), Bytes.toBytes("age"));
		System.out.println(Bytes.toString(name));
		System.out.println(Bytes.toInt(sex));
		System.out.println(Bytes.toInt(age));
		System.out.println(Bytes.toString(address));
	}
  • 全表扫描查询
@Test
	public void scanData() throws IOException{
	    //设置全表扫描封装类
		Scan scan  = new Scan();
		//设置查询起始的rowkey
		scan.setStartRow(Bytes.toBytes("B"));
		scan.setStopRow(Bytes.toBytes("Potter Zha3"));
		//设置单独查询某一行
	//	scan.addColumn(Bytes.toBytes("info1"), Bytes.toBytes("name"));
		//扫描
		ResultScanner scanner = table.getScanner(scan);
		for(Result result:scanner){
			byte[] rowkey = result.getRow();
			byte[] name  = result.getValue(Bytes.toBytes("info1"), Bytes.toBytes("name"));
			byte[] sex = result.getValue(Bytes.toBytes("info1"), Bytes.toBytes("sex"));
			byte[] address = result.getValue(Bytes.toBytes("info1"), Bytes.toBytes("address"));
			byte[] age = result.getValue(Bytes.toBytes("info1"), Bytes.toBytes("age"));
			System.out.println(Bytes.toString(rowkey)+":"+Bytes.toString(name)+":"+Bytes.toInt(sex)+":"+Bytes.toString(address)+":"+Bytes.toInt(age));
		}
	}
  • 带有全表扫描列值过滤器的查询
//在info1列族中查询name列值为“wangxiaoer”的记录
@Test
	public void scanDataByFilter1() throws IOException{
		//创建全表扫描scan
		Scan scan = new Scan();
		//列值过滤器
		SingleColumnValueFilter filter = new SingleColumnValueFilter(Bytes.toBytes("info1"),
				Bytes.toBytes("name"), CompareOp.EQUAL, Bytes.toBytes("wangxiaoer"));
		//设置过滤器
		scan.setFilter(filter);
		//全表扫描
		ResultScanner scanner = table.getScanner(scan);
		for(Result result:scanner){
			byte[] rowkey = result.getRow();
			byte[] name  = result.getValue(Bytes.toBytes("info1"), Bytes.toBytes("name"));
			byte[] sex = result.getValue(Bytes.toBytes("info1"), Bytes.toBytes("sex"));
			byte[] address = result.getValue(Bytes.toBytes("info1"), Bytes.toBytes("address"));
			byte[] age = result.getValue(Bytes.toBytes("info1"), Bytes.toBytes("age"));
			System.out.println(Bytes.toString(rowkey)+":"+Bytes.toString(name)+":"+Bytes.toInt(sex)+":"+Bytes.toString(address)+":"+Bytes.toInt(age));
		}
	}
  • 带有列名前缀过滤器的查询
//查找列名以name_a开头的记录
public void scanDataByFilter2() throws IOException{
		//创建过滤器
		ColumnPrefixFilter columnPrefixFilter = new ColumnPrefixFilter(Bytes.toBytes("name_a"));
		Scan scan = new Scan();
		scan.setFilter(columnPrefixFilter);
		//全表扫描
	  ResultScanner scanner = table.getScanner(scan);
				for(Result result:scanner){
					byte[] rowkey = result.getRow();
					byte[] name  = result.getValue(Bytes.toBytes("info1"), Bytes.toBytes("name_a"));
					byte[] sex = result.getValue(Bytes.toBytes("info1"), Bytes.toBytes("sex"));
					byte[] address = result.getValue(Bytes.toBytes("info1"), Bytes.toBytes("address"));
					byte[] age = result.getValue(Bytes.toBytes("info1"), Bytes.toBytes("age"));
					System.out.println(Bytes.toString(rowkey)+":"+Bytes.toString(name)+Bytes.toString(address));
				}
	}

  • 带有rowkey过滤器的查询
public void scanDataByFilter3() throws IOException{
		//设置rowkey过滤器 匹配以  Potter开头的rowkey
		Filter f = new RowFilter(CompareOp.EQUAL,new RegexStringComparator("^Potter"));
		Scan scan = new Scan();
		scan.setFilter(f);
		//全表扫描
	     ResultScanner scanner = table.getScanner(scan);
				for(Result result:scanner){
					byte[] rowkey = result.getRow();
					byte[] name  = result.getValue(Bytes.toBytes("info1"), Bytes.toBytes("name_a"));
					byte[] sex = result.getValue(Bytes.toBytes("info1"), Bytes.toBytes("sex"));
					byte[] address = result.getValue(Bytes.toBytes("info1"), Bytes.toBytes("address"));
					byte[] age = result.getValue(Bytes.toBytes("info1"), Bytes.toBytes("age"));
					System.out.println(Bytes.toString(rowkey)+":"+Bytes.toString(name)+":"+Bytes.toString(address));
		}
	}

  • 带有多值过滤器的查询
//查询以Potter开头的rowkey中info1列族中name列值为zhangsan的记录
public void scanByDataFilter4() throws IOException{
		FilterList filterList = new FilterList(FilterList.Operator.MUST_PASS_ALL);
		Filter f = new RowFilter(CompareOp.EQUAL,new RegexStringComparator("^Potter"));
		SingleColumnValueFilter filter = new SingleColumnValueFilter(Bytes.toBytes("info1"),
				Bytes.toBytes("name"), CompareOp.EQUAL, Bytes.toBytes("zhangsan"));
		filterList.addFilter(filter);
		filterList.addFilter(f);
		Scan scan = new Scan();
		scan.setFilter(filterList);
		//全表扫描
	    ResultScanner scanner = table.getScanner(scan);
	 	for(Result result:scanner){
			byte[] rowkey = result.getRow();
			byte[] name  = result.getValue(Bytes.toBytes("info1"), Bytes.toBytes("name_a"));
			byte[] sex = result.getValue(Bytes.toBytes("info1"), Bytes.toBytes("sex"));
			byte[] address = result.getValue(Bytes.toBytes("info1"), Bytes.toBytes("address"));
			byte[] age = result.getValue(Bytes.toBytes("info1"), Bytes.toBytes("age"));
			System.out.println(Bytes.toString(rowkey)+":"+Bytes.toString(name)+":"+Bytes.toString(address));
		}
	}

5、MapReduce操作Hbase

需求 :
1、建立数据来源表‘word’,包含一个列族‘content’向表中添加数据,在列族中放入列‘info’,并将短文数据放入该列中,如此插入多行,行键为不同的数据即可
2、建立输出表‘stat’,包含一个列族‘content’
3、通过Mr操作Hbase的‘word’表,对‘content:info’中的短文做词频统计,并将统计结果写入‘stat’表的‘content:info中’,行键为单词

5.1实现方法

Hbase对MapReduce提供支持,它实现了TableMapper类和TableReducer类,我们只需要继承这两个类即可。

  • 1、写个mapper继承TableMapper
    参数:Text:mapper的输出key类型; IntWritable:mapper的输出value类型。
    其中的map方法如下:
    map(ImmutableBytesWritable key, Result value,Context context)
    参数:key:rowKey;value: Result ,一行数据; context上下文
  • 2、写个reduce继承TableReducer
    参数:Text:reducer的输入key; IntWritable:reduce的输入value;
    ImmutableBytesWritable:reduce输出到hbase中的rowKey类型。
    其中的reduce方法如下:
    reduce(Text key, Iterable values,Context context)
    参数: key:reduce的输入key;values:reduce的输入value;

5.2 具体实现

  • 配置hbase
/**
	 * 创建HBase配置
	 */
	static Configuration config = null;
	static {
		config = HBaseConfiguration.create();
		config.set("hbase.zookeeper.quorum", "mini5,mini6,mini7");
		config.set("hbase.zookeeper.property.clientPort", "2181");
	}
	public static final String tableName = "word";//表名1
	public static final String colf = "content";//列族
	public static final String col = "info";//列
	public static final String tableName2 = "stat";//表名2
  • 初始化表的结构及其数据
/**
	 * 初始化表的结构及其数据
	 */
	public static void initTB(){
		HTable table = null;
		HBaseAdmin admin = null;
		try{
			admin = new HBaseAdmin(config);//创建表的管理
			//如果表存在则删除
			if(admin.tableExists(tableName) || admin.tableExists(tableName2)){
				System.out.println("table is already exists!");
				admin.disableTable(tableName);
				admin.disableTable(tableName2);
				admin.deleteTable(tableName);
				admin.deleteTable(tableName2);
			}
			//创建表
			HTableDescriptor desc = new HTableDescriptor(tableName);
			HColumnDescriptor family = new HColumnDescriptor(colf);
			desc.addFamily(family);
			admin.createTable(desc);
			HTableDescriptor desc2 = new HTableDescriptor(tableName2);
			HColumnDescriptor family2 = new HColumnDescriptor(colf);
			desc2.addFamily(family2);
			admin.createTable(desc2);
			table = new HTable(config,tableName);
			table.setAutoFlush(false);
			table.setWriteBufferSize(500);
			List lp = new ArrayList();
			Put p1  = new Put(Bytes.toBytes("1"));
			p1.add(colf.getBytes(), col.getBytes(), ("The Apache Hadoop software library is a framework").getBytes());
			lp.add(p1);
			Put p2 =  new Put(Bytes.toBytes("2"));
			p2.add(colf.getBytes(), col.getBytes(), ("The common utilities that support the other Hadoop modules").getBytes());
			lp.add(p2);
			Put p3 = new Put("3".getBytes());
			p3.add(colf.getBytes(),col.getBytes(),("Hadoop by reading the documentation").getBytes());
			lp.add(p3);
			Put put4 = new Put("4".getBytes());
			put4.add(colf.getBytes(),col.getBytes(),("Hadoop from the release page").getBytes());
			lp.add(put4);
			Put put5 = new Put("5".getBytes());
			put5.add(colf.getBytes(),col.getBytes(),("Hadoop on the mailing list").getBytes());
			lp.add(put5);
			table.put(lp);
			table.flushCommits();
			lp.clear();
		}catch(Exception e){
			e.printStackTrace();
		}finally{
					try{
							if(table != null ){
								table.close();
							}
						}catch(Exception e ){
							e.printStackTrace();
						}
					}
		}
  • Mapper类
/**
	 * MyMapper继承TableMapper
	 * TableMapper
	 * Text:输出的key类型
	 * IntWritable:输出的value类型
	 * @author potter
	 *
	 */
	public static class MyMapper extends TableMapper{
		private static IntWritable one = new IntWritable(1);
		private static Text word = new Text();
		//输出入的类型为key:rowkey;value:一行数据的结果集Result
		protected void map(ImmutableBytesWritable key ,Result value,Context context) throws IOException, InterruptedException{
			//一行只有一个列族可以从result中直接取值
			String words = Bytes.toString(value.getValue(Bytes.toBytes(colf), Bytes.toBytes(col)));
			String inr[] = words.toString().split(" ");
			//循环输出word和1
			for(int i = 0 ; i < inr.length ; i ++ ){
				word.set(inr[i]);
				context.write(word, one);
			}
			
		}
	}
  • Reducer类
public static class MyReducer extends TableReducer{
		protected void reduce(Text key , Iterable values , Context context) throws IOException, InterruptedException{
			int sum = 0 ;
			for(IntWritable val : values ){
				sum += val.get();
			}
		   //创建put,设置rowkey为单词
			Put put = new Put(Bytes.toBytes(key.toString()));
		    //封装数据
			put.add(Bytes.toBytes(colf),Bytes.toBytes(col),Bytes.toBytes(String.valueOf(sum)));
			//写到hbase,需要指定rowkey,put
			context.write(new ImmutableBytesWritable(Bytes.toBytes(key.toString())), put);
		}
	}
  • 提交任务的main方法
public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException{
        //初始化表
        initTB();
        //创建job
        Job job = new Job(config,"HBaseMr");//job
        job.setJarByClass(HBaseMR.class);
        Scan scan = new Scan();
        scan.addColumn(Bytes.toBytes(colf), Bytes.toBytes(col));
        //创建查询hbase的mapper,设置表名、scan、mapper类,mapper的输出key、mapper的输出value
        TableMapReduceUtil.initTableMapperJob(tableName, scan, MyMapper.class, Text.class, IntWritable.class, job);
        TableMapReduceUtil.initTableReducerJob(tableName2, MyReducer.class, job);
        System.exit(job.waitForCompletion(true) ? 0 : 1 );
    }
  • 通过 hbase shell的scan命令查看统计结果如下:
    HBase初入门_第2张图片

你可能感兴趣的:(Hbase)