集成Hive和HBase

1. MapReduce

用MapReduce将数据从本地文件系统导入到HBase的表中,

比如从HBase中读取一些原始数据后使用MapReduce做数据分析。

结合计算型框架进行计算统计
查看HBase的MapReduce任务的执行,把jar打印出来的就是需要添加到hadoop的CLASSPATH下的jar包

 bin/hbase mapredcp
知识兔

环境变量的导入
(1)执行环境变量的导入(临时生效,在命令行执行下述操作)

hbase
$ export HADOOP_HOME=/opt/module/hadoop-2.7.2
$ export HADOOP_CLASSPATH=`${HBASE_HOME}/bin/hbase mapredcp`
知识兔
2)永久生效
在etc/hadoop下hadoop-env.sh中配置:(注意:在for循环之后配),要重启下才生效
export HADOOP_CLASSPATH=$HADOOP_CLASSPATH:/opt/module/hbase/lib/*
知识兔
运行官方的MapReduce任务
-- 案例一:统计Student表中有多少行数据; 要在hbase中先有student表
$ /opt/module/hadoop-2.7.2/bin/yarn jar lib/hbase-server-1.3.1.jar rowcounter student

-- 案例二:使用MapReduce将hdfs数据导入到HBase
1)在本地创建一个tsv格式的文件:fruit.tsv
1001    Apple    Red
1002    Pear        Yellow
1003    Pineapple    Yellow

2)创建HBase表
hbase(main):001:0> create 'fruit','info'

3)在HDFS中创建input_fruit文件夹并上传fruit.tsv文件
[kris@hadoop101 hadoop-2.7.2]$ hdfs dfs -mkdir /hbase/input_fruit  
[kris@hadoop101 datas]$ hadoop fs -put fruit.tsv /hbase/input_fruit

//把表名写死了;不写死可以通过命令行run(String[] args)传参
[kris@hadoop101 hadoop-2.7.2]$ bin/yarn jar HbaseTest-1.0-SNAPSHOT.jar com.atguigu.mr.ReadFromTableDriver
bin/yarn jar HbaseTest-1.0-SNAPSHOT.jar com.atguigu.mr2.ReadFromHdfsDriver /fruit.tsv fruit_mr //给它传参数

4)执行MapReduce到HBase的fruit表中
[kris@hadoop101 hadoop-2.7.2]$ bin/yarn jar /opt/module/hbase-1.3.1/lib/hbase-server-1.3.1.jar importtsv -Dimporttsv.columns=HBASE_ROW_KEY,info:name,info:color fruit /hbase/input_fruit  //hdfs://hadoop101:9000/这个可省略


5)使用scan命令查看导入后的结果
hbase(main):001:0> scan ‘fruit’
知识兔

① 将fruit表中的一部分数据,通过MR迁入到fruit_mr表中。

  从hbase中读取数据;
  输入的k,v类型已经写好(ImmutableBytesWritable key,Result value),要自定义输出类型k,v

ReadFromTableMapper.java
//把hbase中的fruit表中的一部分数据,通过MR迁入到fruit_mr表, fruit_mr要先在hbase中创建好。
public class ReadFromTableMapper extends TableMapper<ImmutableBytesWritable, Put> {
    @Override
    protected void map(ImmutableBytesWritable key, Result value, Context context) throws IOException, InterruptedException {
        //1.获取rowkey//不可变的字节数组,按rowkey来读;scan扫描的封装到了result(1行里边的所有数据)
        byte[] rowkey = key.get();
        //2.创建put对象
        Put put = new Put(rowkey);  //创建put对象时要指定rowkey
        //3.添加列的信息
        for (Cell cell : value.rawCells()) { //获取这1列的所有cell
            if ("info".equals(Bytes.toString(CellUtil.cloneFamily(cell)))){
                if ("name".equals(Bytes.toString(CellUtil.cloneQualifier(cell)))){
                    put.add(cell);
                }else if ("color".equals(Bytes.toString(CellUtil.cloneQualifier(cell)))){
                    put.add(cell);
                }
            }
        }
        context.write(key, put);
    }
}


ReadFromTableReducer.java
// TableReducer<KEYIN, VALUEIN, KEYOUT> extends Reducer<KEYIN, VALUEIN, KEYOUT, Mutation>
//Mutation,Delete和Put都是它的子类;Hbase中每次操作可看做mutation这个类; Put已经封装了rowkey等所有数据
reducer初始化没有用到nullwritable
public class ReadFromTableReducer extends TableReducer<ImmutableBytesWritable, Put, NullWritable> {

    @Override
    protected void reduce(ImmutableBytesWritable key, Iterable<Put> values, Context context) throws IOException, InterruptedException {
        for (Put put : values) {
            context.write(NullWritable.get(), put);
        }
    }
}


ReadFromTableDriver.jva
//实现Tool接口,执行任务时用ToolRunner调
public class ReadFromTableDriver implements Tool {
    private Configuration configuration = null;

    public int run(String[] strings) throws Exception { //获取任务并设置
        //1.获取job对象
        Job job = Job.getInstance(configuration);
        //2.设置job对象
        job.setJarByClass(ReadFromTableDriver.class);
        Scan scan = new Scan();//在这里传参数StartRow StopRow
        scan.setCacheBlocks(true); //设置缓存
        scan.setCaching(100); //扫100条数据再跟Hbase的server端交互,减少次数
        TableMapReduceUtil.initTableMapperJob("fruit", scan, //mapper去读数据;
                ReadFromTableMapper.class, ImmutableBytesWritable.class,//k v; fruit可通过args[0]传参
                Put.class, job);
        TableMapReduceUtil.initTableReducerJob("fruit_mr", //插入数据的表   //工具类初始化map,reduce
                ReadFromTableReducer.class, job);
        boolean b = job.waitForCompletion(true);
        return b ? 0 : 1; //1表false
    }
    public void setConf(Configuration conf) { //hadoop的8个配置文件封装到Configuration中
        this.configuration = conf;
    }
    public Configuration getConf() {
        return configuration;
    }
    public static void main(String[] args) throws Exception {
        int run = ToolRunner.run(new ReadFromTableDriver(), args); //最终调用的是上边的run方法;tool对象即ReadFromTableDriver的对象
        System.exit(run);//run为0或1
    }
}
知识兔
打包运行任务
$ /opt/module/hadoop-2.7.2/bin/yarn jar hbase-0.0.1-SNAPSHOT.jar com.atguigu.mr.ReadFromTableDriver
知识兔

②实现将HDFS中的数据写入到HBase表中。  

  写入到Hbase;泛型,输入k,value;value已定义好immutaion;需自定义k

public class ReadFromHdfsTableMapper extends Mapper<LongWritable, Text, ImmutableBytesWritable, Put> {
    private ImmutableBytesWritable k = new ImmutableBytesWritable();
    @Override
    protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
        //1.获取1行
        String line = value.toString();
        //2.切割
        String[] fields = line.split("\t");
        //3.获取put对象
        String rowkey = fields[0];
        Put put = new Put(Bytes.toBytes(rowkey));
        //添加列信息| 列族/列名
        put.addColumn(Bytes.toBytes("info"), Bytes.toBytes("name"),
                Bytes.toBytes(fields[1]));
        put.addColumn(Bytes.toBytes("info"), Bytes.toBytes("color"),
                Bytes.toBytes(fields[2]));
        context.write(k, put);
    }
}


public class ReadFromHdfsTableReducer extends TableReducer<ImmutableBytesWritable, Put, NullWritable> {
    @Override
    protected void reduce(ImmutableBytesWritable key, Iterable<Put> values, Context context) throws IOException, InterruptedException {
        for (Put put : values) {
            context.write(NullWritable.get(), put);
        }
    }
}


public class ReadFromHdfsDriver implements Tool {
    private Configuration configuration;
    public int run(String[] args) throws Exception {
        Job job = Job.getInstance();
        job.setJarByClass(ReadFromTableDriver.class);
        job.setMapperClass(ReadFromTableMapper.class);
        job.setMapOutputKeyClass(ImmutableBytesWritable.class);
        job.setMapOutputValueClass(Put.class);
        //设置文件路径
        FileInputFormat.setInputPaths(job, new Path(args[0]));
        TableMapReduceUtil.initTableReducerJob(args[1], ReadFromTableReducer.class, job);
        boolean b = job.waitForCompletion(true);
        return b ? 0 : 1;
    }
    public void setConf(Configuration conf) {
        configuration =conf;
    }
    public Configuration getConf() {
        return configuration;
    }
    public static void main(String[] args) throws Exception {
        int run = ToolRunner.run(new ReadFromTableDriver(), args); //传Tool对象
        System.exit(run);
    }
}
知识兔
打包运行
$ /opt/module/hadoop-2.7.2/bin/yarn jar hbase-0.0.1-SNAPSHOT.jar com.atguigu.mr2.ReadFromHdfsDriver
提示:运行任务前,如果待数据导入的表不存在,则需要提前创建之。
知识兔

hadoop jar
yarn jar
8032rm和yarn的通信端口号

2. 与Hive的集成

Hive和Hbase在大数据架构中处在不同位置,Hive是一个构建在Hadoop基础之上的数据仓库,主要解决分布式存储的大数据处理和计算问题,Hive提供了类SQL语句,叫HiveQL,

通过它可以使用SQL查询存放在HDFS上的数据,sql语句最终被转化为Map/Reduce任务运行,但是Hive不能够进行交互查询——它只能够在Haoop上批量的执行Map/Reduce任务。

Hive适合用来对一段时间内的数据进行分析查询,例如,用来计算趋势或者网站的日志。Hive不应该用来进行实时的查询。因为它需要很长时间才可以返回结果。

Hbase是Hadoop database 的简称,是一种NoSQL数据库,非常适用于海量明细数据(十亿、百亿)的随机实时查询,如交易清单、轨迹行为等。

在大数据架构中,Hive和HBase是协作关系,Hive方便地提供了Hive QL的接口来简化MapReduce的使用, 而HBase提供了低延迟的数据库访问。如果两者结合,可以利用MapReduce的优势针对HBase存储的大量内容进行离线的计算和分析。

Hive和HBase的通信原理

Hive与HBase整合的实现是利用两者本身对外的API接口互相通信来完成的,

这种相互通信是通过$HIVE_HOME/lib/hive-hbase-handler-*.jar工具类实现的。通过HBaseStorageHandler,Hive可以获取到Hive表所对应的HBase表名,列簇和列,InputFormat、OutputFormat类,创建和删除HBase表等。基本通信原理如下:

             

访问

Hive访问HBase中HTable的数据,实质上是通过MR读取HBase的数据,而MR是使用HiveHBaseTableInputFormat完成对表的切分,获取RecordReader对象来读取数据的。

对HBase表的切分原则是一个Region切分成一个Split,即表中有多少个Regions,MR中就有多少个Map;

读取HBase表数据都是通过构建Scanner,对表进行全表扫描,如果有过滤条件,则转化为Filter。当过滤条件为rowkey时,则转化为对rowkey的过滤;Scanner通过RPC调用RegionServer的next()来获取数据。

简单来说,Hive和Hbase的集成就是,打通了Hive和Hbase,使得Hive中的表创建之后,可以同时是一个Hbase的表,并且在Hive端和Hbase端都可以做任何的操作。

使用场景:

(一)将ETL操作的数据通过Hive加载到HBase中,数据源可以是文件也可以是Hive中的表。

             

(二)Hbae作为Hive的数据源,通过整合,让HBase支持JOIN、GROUP等SQL查询语法。

                 

(三)构建低延时的数据仓库

                   

以上原理来自知乎:https://zhuanlan.zhihu.com/p/74041611

HBase与Hive的集成在最新的两个版本中无法兼容。所以,我们只能重新编译:hive-hbase-handler-1.2.2.jar!

将所需要的lib的jar包导入进行编译; apache-hive-1.2.1-src\hbase-handler\src\java

操作Hive的同时对HBase也会产生影响,所以Hive需要持有操作HBase的Jar,那么接下来拷贝Hive所依赖的Jar包(或者使用软连接的形式)。

 对hive添加的jar添加到这个参数,需重启;相当于hbase的客户端-hive,hive和hbase集成所依赖的类

/*
知识兔

同时在hive-site.xml中修改zookeeper的属性,如下:

for read/write locks.</description>
</property>
<property>
  <name>hive.zookeeper.client.port</name>
  <value>2181</value>
  <description>The port of ZooKeeper servers to talk to. This is only needed for read/write locks.</description>
</property>
知识兔

建立Hive表,关联HBase表,插入数据到Hive表的同时能够影响HBase表。

hive表字段映射到hbase中;用stored by指定下格式类型hbase;指定映射关系;serd是序列化和反序列化;列顺序和字段一一对应;:key即rowkey

hive中表删,hbase中就没有了

0: jdbc:hive2://hadoop101:10000> create table hive_hbase_emp_table(empno int, ename string, job string, mgr int, hiredate string, sal double, comm double, deptno int) stored by 'org.apache.hadoop.hive.hbase.HBaseStorageHandler' 
with serdeproperties ("hbase.columns.mapping"=":key,info:ename,info:job,info:mgr,info:hiredate,info:sal,info:comm,info:deptno") 
tblproperties ("hbase.table.name"="hbase_emp_table");

完成之后,可以分别进入Hive和HBase查看,都生成了对应的表
    在Hive中创建临时中间表,用于load文件中的数据; 不能将数据直接load进Hive所关联HBase的那张表中;要经过mapreduce;
向hive_hbase_emp_table表中插入数据:
hive> insert into table hive_hbase_emp_table select * from emp;
查看Hive以及关联的HBase表中是否已经成功的同步插入了数据
Hive:
hive> select * from hive_hbase_emp_table;
HBase:
hbase> scan ‘hbase_emp_table’
知识兔

在HBase中已经存储了某一张表hbase_emp_table,然后在Hive中创建一个外部表来关联HBase中的hbase_emp_table这张表,使之可以借助Hive来分析HBase这张表中的数据。

创建外部表:
create external table relevance_hbase_emp(empno int, ename string, job string, mgr int, hiredate string, sal double, comm double, deptno int) stored by 'org.apache.hadoop.hive.hbase.HBaseStorageHandler' 
with serdeproperties ("hbase.columns.mapping"=":key,info:ename,info:job,info:mgr,info:hiredate,info:sal,info:comm,info:deptno") 
tblproperties ("hbase.table.name"="hbase_emp_table");
关联后就可以使用Hive函数进行一些分析操作了
hive (default)> select * from relevance_hbase_emp;
知识兔

hbase中已有表,去关联它,创建外部表即可;hive中删表,数据在hbase中还是存在的;

计算机