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、传统数据库遇到的问题:
1)数据量很大的时候无法存储
2)没有很好的备份机制
3)数据达到一定数量开始缓慢,很大的话基本无法支撑
2、HBASE优势:
1)线性扩展,随着数据量增多可以通过节点扩展进行支撑
2)数据存储在hdfs上,备份机制健全
3)通过zookeeper协调查找数据,访问速度块。
1、一个或者多个主节点,Hmaster
2、多个从节点,HregionServer
Row key行键 (Row key)可以是任意字符串(最大长度 是 64KB,实际应用中长度一般为 10-100bytes),在HBASE内部,row key保存为字节数组。存储时,数据按照Row key的字典序(byte order)排序存储。设计key时,要充分排序存储这个特性,将经常一起读取的行存储放到一起。(位置相关性)
HBASE 中通过rowkey和columns确定的为一个存贮单元称为cell。每个 cell都保存 着同一份数据的多个版本。版本通过时间戳来索引。时间戳的类型是 64位整型。时间戳可以由HBASE(在数据写入时自动 )赋值,此时时间戳是精确到毫秒 的当前系统时间。时间戳也可以由客户显式赋值。如果应用程序要避免数据版 本冲突,就必须自己生成具有唯一性的时间戳。每个 cell中,不同版本的数据按照时间倒序排序,即最新的数据排在最前面。
为了避免数据存在过多版本造成的的管理 (包括存贮和索引)负担,HBASE提供 了两种数据版本回收方式。一是保存数据的最后n个版本,二是保存最近一段 时间内的版本(比如最近七天)。用户可以针对每个列族进行设置。
// 启动
#$HBASE_HOME/bin/hbase shell
// 退出
quit
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'
get '表名' , 'rowKey'
如 : get 'user123','123'
count '表名'
get '表名','rowkey','列族:列’ 如: get 'user123','123','info1:name'
delete ‘表名’ ,‘行名’ , ‘列族:列' 如: delete 'user123','123','info1:name'
deleteall '表名','rowkey'
先要屏蔽该表,才能对该表进行删除
第一步 disable ‘表名’ ,第二步 drop '表名'
truncate '表名'
scan "表名"
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();
}
@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);
}
@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);
}
@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);
}
@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);
}
@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);
}
@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));
}
}
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));
}
}
需求 :
1、建立数据来源表‘word’,包含一个列族‘content’向表中添加数据,在列族中放入列‘info’,并将短文数据放入该列中,如此插入多行,行键为不同的数据即可
2、建立输出表‘stat’,包含一个列族‘content’
3、通过Mr操作Hbase的‘word’表,对‘content:info’中的短文做词频统计,并将统计结果写入‘stat’表的‘content:info中’,行键为单词
Hbase对MapReduce提供支持,它实现了TableMapper类和TableReducer类,我们只需要继承这两个类即可。
/**
* 创建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();
}
}
}
/**
* 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);
}
}
}
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);
}
}
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 );
}