HBase(八)Region 合并操作

Region的合并不是为了性能, 而是出于便于运维的目的 .

比如删除了大量的数据 ,这个时候每个Region都变得很小 ,存储多个Region就浪费了 ,这个时候可以把Region合并起来,进而可以减少一些Region服务器节点。

下面来看一下如何进行region合并:

通过Merge类冷合并Region

执行冷合并前,需要先关闭hbase集群

创建一张hbase表:

create 'test','info1',SPLITS => ['1000','2000','3000']

查看表region

file

需求:

通过查看UI界面,需要把test表中的前2个region数据进行合并,分别是:

  1. test,,1620148534743.8222cc22ab4acb18b726b3c6be1cb082.
  2. test,1000,1620148534743.b2e07e8922d0ffa6477ef2d7ff368bba.

这里通过org.apache.hadoop.hbase.util.Merge类来实现,不需要进入hbase shell,直接执行(需要先关闭hbase集群):

hbase org.apache.hadoop.hbase.util.Merge test test,,1620148534743.8222cc22ab4acb18b726b3c6be1cb082. test,1000,1620148534743.b2e07e8922d0ffa6477ef2d7ff368bba.

成功后可以界面观察分区变化,但是我这里运行找不到主类org.apache.hadoop.hbase.util.Merge。实际上冷合并不常用,因为需要停止集群损耗巨大,工作中更常使用热合并。

通过online_merge热合并Region

不需要关闭hbase集群==,在线进行合并

与冷合并不同的是,online_merge的传参是Region的hash值,而Region的hash值就是Region名称的最后那段在两个.之间的字符串部分。

需求:需要把test表中的2个region数据进行合并:

  1. test,2000,1620148534743.68216f0389235352165d3b884db24b95.
  2. test,3000,1620148534743.c85c37595f74abb8eb0276c50bf700e6.

需要进入hbase shell:

hbase(main):001:0> merge_region '68216f0389235352165d3b884db24b95','c85c37595f74abb8eb0276c50bf700e6'

Took 11.3953 seconds

成功后观察界面

file

Views: 45

HBase(七)表的预分区

HBase表的预分区

  • 当一个table刚被创建的时候,Hbase默认的分配一个region给table。也就是说这个时候,所有的读写请求都会访问到同一个regionServer的同一个region中,这个时候就达不到负载均衡的效果了,集群中的其他regionServer就可能会处于比较空闲的状态。
  • 解决这个问题可以用pre-splitting,在创建table的时候就配置好,生成多个region。

1 为何要预分区?

  • 增加数据读写效率
  • 负载均衡,防止数据倾斜
  • 方便集群容灾调度region
  • 优化Map数量

2 预分区原理

  • 每一个region维护着startRowKey与endRowKey,如果加入的数据符合某个region维护的rowKey范围,则该数据交给这个region维护。

手动指定预分区

  • 三种方式

  • 方式一

create 'person','info1','info2',SPLITS => ['1000','2000','3000','4000']

可以在UI界面查看这个表的每个分区的起始和结束rowKey。

file

  • 方式二:也可以把分区规则创建于文件中

    cd /opt/data
    
    vim split.txt
    • 文件内容
    aaa
    bbb
    ccc
    ddd
    • hbase shell中,执行命令
    create 'student','info',SPLITS_FILE => '/opt/data/split.txt'
    • 成功后查看web界面

file

  • 方式三: HexStringSplit 算法

    • HexStringSplit会将数据从“00000000”到“FFFFFFFF”之间的数据长度按照n等分之后算出每一段的起始rowkey和结束rowkey,以此作为拆分点。

    • 例如:

    create 'mytable', 'base_info',' extra_info', {NUMREGIONS => 15, SPLITALGO => 'HexStringSplit'}

file

Views: 27

HBase(六)flush、compact机制

Flush 触发条件

memstore 级别限制

  • Region中任意一个MemStore的大小达到了上限(hbase.hregion.memstore.flush.size,默认128MB),会触发Memstore刷新(flush)。
<property>
    <name>hbase.hregion.memstore.flush.size</name>
    <value>134217728</value>
</property>

region 级别限制

  • Region中所有Memstore的大小总和达到了上限(hbase.hregion.memstore.block.multiplier * hbase.hregion.memstore.flush.size,默认 2 * 128M = 256M),会触发memstore刷新。
<property>
    <name>hbase.hregion.memstore.flush.size</name>
    <value>134217728</value>
</property>
<property>
    <name>hbase.hregion.memstore.block.multiplier</name>
    <value>4</value>
</property>

说明:

  • 上限值 = 134217728 x 4*

Region Server级别限制

  • 当一个Region Server中所有Memstore的大小总和超过低水位阈值hbase.regionserver.global.memstore.size.lower.limit * hbase.regionserver.global.memstore.size(前者默认值0.95),RegionServer开始强制flush
  • Flush Memstore最大的Region,再执行次大的,依次执行;
  • 如写入速度大于flush写出的速度,导致总MemStore大小超过高水位阈值hbase.regionserver.global.memstore.size(默认为JVM内存的40%),此时RegionServer会阻塞更新并强制执行flush,直到总MemStore大小低于低水位阈值
<property>
    <name>hbase.regionserver.global.memstore.size.lower.limit</name>
    <value>0.95</value>
</property>
<property>
    <name>hbase.regionserver.global.memstore.size</name>
    <value>0.4</value>
</property>

file

file

HLog数量上限

  • 当一个Region ServerHLog数量达到上限(可通过参数hbase.regionserver.maxlogs配置)时,系统会选取最早的一个HLog对应的一个或多个Region进行flush

定期刷新 Memstore

  • 默认周期为1小时,确保Memstore不会长时间没有持久化。为避免所有的MemStore在同一时间都进行flush导致的问题,定期的flush操作有20000左右的随机延时。

file

手动 flush

  • 用户可以通过shell命令flush <tablename>或者flush <region name>分别对一个表或者一个Region进行flush

flush的流程

为了减少flush过程对读写的影响,将整个flush过程分为三个阶段:

  1. prepare阶段:遍历当前Region中所有的Memstore,将Memstore中当前数据集CellSkipListSet做一个快照snapshot;然后再新建一个CellSkipListSet。后期写入的数据都会写入新的CellSkipListSet中。prepare阶段需要加一把updateLock写请求阻塞,结束之后会释放该锁。因为此阶段没有任何费时操作,因此持锁时间很短。

  2. flush阶段:遍历所有Memstore,将prepare阶段生成的snapshot持久化为临时文件,临时文件会统一放到目录.tmp下。这个过程因为涉及到磁盘IO操作,因此相对比较耗时。

  3. commit阶段:遍历所有Memstore,将flush阶段生成的临时文件移到指定的ColumnFamily目录下,针对HFile生成对应的storefileReader,把storefile添加到HStorestorefiles列表中,最后再清空prepare阶段生成的snapshot

file

Compact合并机制

hbase为了防止小文件过多,以保证查询效率,hbase需要在必要的时候将这些小的store file合并成相对较大的store file,这个过程就称之为compaction。

在hbase中主要存在两种类型的compaction合并

  1. minor compaction 小合并
  2. major compaction 大合并

HBase 2.x 还可以基于内存合并

minor compaction 小合并

  • 在将Store中多个HFile合并为一个HFile

    在这个过程中会选取一些小的、相邻的StoreFile将他们合并成一个更大的StoreFile,这种合并的触发频率很高。

  • minor compaction触发条件由以下几个参数共同决定:

<!--默认值3;表示一个store中至少有4个store file时,会触发minor compaction-->
<property>

<name>hbase.hstore.compactionThreshold</name>
    <value>3</value>
</property>

<!--默认值10;表示一次minor compaction中最多合并10个store file-->
<property>

<name>hbase.hstore.compaction.max</name>
    <value>10</value>
</property>

<!--默认值为128m;表示store file文件大小小于该值时,一定会加入到minor compaction的-->
<property>
    <name>hbase.hstore.compaction.min.size</name>
    <value>134217728</value>
</property>

<!--默认值为LONG.MAX_VALUE;表示store file文件大小大于该值时,一定会被minor compaction排除-->
<property>
    <name>hbase.hstore.compaction.max.size</name>
    <value>9223372036854775807</value>
</property>

major compaction 大合并

  • 合并Store中所有的HFile为一个HFile

    将所有的StoreFile合并成一个StoreFile,这个过程还会清理三类无意义数据:被删除的数据、TTL过期数据、版本号超过设定版本号的数据。合并频率比较低,默认7天执行一次,并且性能消耗非常大,建议生产关闭(设置为0),在应用空闲时间手动触发。一般可以是手动控制进行合并,防止出现在业务高峰期。

  • major compaction触发时间条件

    <!--默认值为7天进行一次大合并,-->
    <property>
    <name>hbase.hregion.majorcompaction</name>
    <value>604800000</value>
    </property>
  • 手动触发

    ##使用major_compact命令
    major_compact tableName

Views: 38

HBase(五)数据存储原理

  1. 一个HRegionServer会负责管理很多个region
  2. 一个region包含很多个store
    • 一个列族就划分成一个store
    • 如果一个表中只有1个列族,那么这个表的每一个region中只有一个store
    • 如果一个表中有N个列族,那么这个表的每一个region中有Nstore
  3. 一个store里面只有一个memstore
    • memstore是一块内存区域,写入的数据会先写入memstore进行缓冲,然后再把数据刷到磁盘
  4. 一个store里面有很多个StoreFile, 最后数据是以很多个HFile这种数据结构的文件保存在HDFS上
    • StoreFileHFile的抽象对象,如果说到StoreFile就等于HFile
    • 每次memstore刷写数据到磁盘,就生成对应的一个新的HFile文件出来

HBase读数据流程

说明:HBase集群,只有一张meta表,此表只有一个region,该region数据保存在一个HRegionServer

  1. 客户端首先与zookeeper进行连接;

    • zk找到meta表的region位置,即meta表的数据 一HRegionServer上;
    • 客户端与此HRegionServer建立连接,然后读取meta表中的数据;meta表中存储了所有用户表的region信息,我们可以通过scan 'hbase:meta'来查看meta表信息
  2. 根据要查询的namespace、表名和rowkey信息。找到写入数据对应的region信息

  3. 找到这个region对应的regionServer,然后发送请求

  4. 查找并定位到对应的region

  5. 先从memstore查找数据,如果没有,再从BlockCache上读取

    • HBaseRegionserver的内存分为两个部分
    • 一部分作为Memstore,主要用来写;
    • 另外一部分作为BlockCache,主要用于读数据;
  6. 如果BlockCache中也没有找到,再到StoreFile上进行读取

    • storeFile中读取到数据之后,不是直接把结果数据返回给客户端,而是把数据先写入到BlockCache中,目的是为了加快后续的查询;然后再返回结果给客户端。

file

HBase写数据流程

  1. 客户端首先从zk找到meta表的region位置,然后读取meta表中的数据,meta表中存储了用户表的region信息

  2. 根据namespace、表名和rowkey信息。找到写入数据对应的region信息

  3. 找到这个region对应的regionServer,然后发送请求

  4. 把数据分别写到HLog(write ahead log)和memstore各一份

  5. memstore达到阈值后把数据刷到磁盘,生成storeFile文件

file

补充:

HLog(write ahead log):
也称为WAL意为Write ahead log,类似mysql中的binlog,用来做灾难恢复时用,HLog记录数据的所有变更,一旦数据修改,就可以从log中进行恢复。

Views: 31

HBase(四)JavaAPI操作 和 过滤器查询

HBase的JavaAPI操作

  • HBase是一个分布式的NoSql数据库,在实际工作当中,我们一般都可以通过JavaAPI来进行各种数据的操作,包括创建表,以及数据的增删改查等等

创建maven工程

  • 讲如下内容作为maven工程中pom.xml的repositories的内容
  • 自动导包
 <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>XZK</artifactId>
        <groupId>org.example</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>HbaseApi1</artifactId>
    <dependencies>
        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-client</artifactId>
            <version>3.1.4</version>
        </dependency>
        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-auth</artifactId>
            <version>3.1.4</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.hbase/hbase-client -->
        <dependency>
            <groupId>org.apache.hbase</groupId>
            <artifactId>hbase-client</artifactId>
            <version>2.2.6</version>
        </dependency>
        <dependency>
            <groupId>org.apache.hbase</groupId>
            <artifactId>hbase-server</artifactId>
            <version>2.2.6</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>6.14.3</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>6.14.3</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.0</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>2.2</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <filters>
                                <filter>
                                    <artifact>*:*</artifact>
                                    <excludes>
                                        <exclude>META-INF/*.SF</exclude>
                                        <exclude>META-INF/*.DSA</exclude>
                                        <exclude>META-INF/*/RSA</exclude>
                                    </excludes>
                                </filter>
                            </filters>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

创建myuser表

  • 创建myuser表,此表有两个列族f1和f2
    //操作数据库  第一步:获取连接  第二步:获取客户端对象   第三步:操作数据库  第四步:关闭
    /**
     * 创建一张表  myuser  两个列族  f1   f2
     */
    @Test
    public void createTable() throws IOException {
        Configuration configuration = HBaseConfiguration.create();
        //连接HBase集群不需要指定HBase主节点的ip地址和端口号
        configuration.set("hbase.zookeeper.quorum","hadoop100:2181,hadoop101:2181,hadoop102:2181");
        //创建连接对象
        Connection connection = ConnectionFactory.createConnection(configuration);
        //获取连接对象,创建一张表
        //获取管理员对象,来对手数据库进行DDL的操作
        Admin admin = connection.getAdmin();
        //指定我们的表名
        TableName myuser = TableName.valueOf("myuser");
        HTableDescriptor hTableDescriptor = new HTableDescriptor(myuser);
        //指定两个列族
        HColumnDescriptor f1 = new HColumnDescriptor("f1");
        HColumnDescriptor f2 = new HColumnDescriptor("f2");
        hTableDescriptor.addFamily(f1);
        hTableDescriptor.addFamily(f2);

        admin.createTable(hTableDescriptor);
        admin.close();
        connection.close();
    }

向表中添加数据

    private Connection connection ;
    private final String TABLE_NAME = "myuser";
    private Table table ;

    @Before
    public void initTable () throws IOException {
        Configuration configuration = HBaseConfiguration.create();
        configuration.set("hbase.zookeeper.quorum","hadoop100:2181,hadoop101:2181");
        connection = ConnectionFactory.createConnection(configuration);
        table = connection.getTable(TableName.valueOf(TABLE_NAME));
    }

    @After
    public void close() throws IOException {
        table.close();
        connection.close();
    }

    /**
     *  向myuser表当中添加数据
     */
    @Test
    public void addData() throws IOException {
        //获取表
        //Table table = connection.getTable(TableName.valueOf(TABLE_NAME));
        Put put = new Put("0001".getBytes());//创建put对象,并指定rowkey值
        put.addColumn("f1".getBytes(),"name".getBytes(),"zhangsan".getBytes());
        put.addColumn("f1".getBytes(),"age".getBytes(), Bytes.toBytes(18));
        put.addColumn("f1".getBytes(),"id".getBytes(), Bytes.toBytes(25));
        put.addColumn("f1".getBytes(),"address".getBytes(), Bytes.toBytes("地球人"));
        table.put(put);
        table.close();
    } 

查询数据

  • 初始化一批数据到HBase表当中,用于查询

    /**
     * hbase的批量插入数据
     */
    @Test
    public void batchInsert() throws IOException {
        // 创建put对象,并指定rowkey
        Put put = new Put("0002".getBytes());

        put.addColumn("f1".getBytes(),"id".getBytes(),Bytes.toBytes(1));
        put.addColumn("f1".getBytes(),"name".getBytes(),Bytes.toBytes("曹操"));
        put.addColumn("f1".getBytes(),"age".getBytes(),Bytes.toBytes(30));
        put.addColumn("f2".getBytes(),"sex".getBytes(),Bytes.toBytes("1"));
        put.addColumn("f2".getBytes(),"address".getBytes(),Bytes.toBytes("沛国谯县"));
        put.addColumn("f2".getBytes(),"phone".getBytes(),Bytes.toBytes("16888888888"));
        put.addColumn("f2".getBytes(),"say".getBytes(),Bytes.toBytes("helloworld"));

        Put put2 = new Put("0003".getBytes());
        put2.addColumn("f1".getBytes(),"id".getBytes(),Bytes.toBytes(2));
        put2.addColumn("f1".getBytes(),"name".getBytes(),Bytes.toBytes("刘备"));
        put2.addColumn("f1".getBytes(),"age".getBytes(),Bytes.toBytes(32));
        put2.addColumn("f2".getBytes(),"sex".getBytes(),Bytes.toBytes("1"));
        put2.addColumn("f2".getBytes(),"address".getBytes(),Bytes.toBytes("幽州涿郡涿县"));
        put2.addColumn("f2".getBytes(),"phone".getBytes(),Bytes.toBytes("17888888888"));
        put2.addColumn("f2".getBytes(),"say".getBytes(),Bytes.toBytes("talk is cheap , show me the code"));

        Put put3 = new Put("0004".getBytes());
        put3.addColumn("f1".getBytes(),"id".getBytes(),Bytes.toBytes(3));
        put3.addColumn("f1".getBytes(),"name".getBytes(),Bytes.toBytes("孙权"));
        put3.addColumn("f1".getBytes(),"age".getBytes(),Bytes.toBytes(35));
        put3.addColumn("f2".getBytes(),"sex".getBytes(),Bytes.toBytes("1"));
        put3.addColumn("f2".getBytes(),"address".getBytes(),Bytes.toBytes("下邳"));
        put3.addColumn("f2".getBytes(),"phone".getBytes(),Bytes.toBytes("12888888888"));
        put3.addColumn("f2".getBytes(),"say".getBytes(),Bytes.toBytes("what are you 弄啥嘞!"));

        Put put4 = new Put("0005".getBytes());
        put4.addColumn("f1".getBytes(),"id".getBytes(),Bytes.toBytes(4));
        put4.addColumn("f1".getBytes(),"name".getBytes(),Bytes.toBytes("诸葛亮"));
        put4.addColumn("f1".getBytes(),"age".getBytes(),Bytes.toBytes(28));
        put4.addColumn("f2".getBytes(),"sex".getBytes(),Bytes.toBytes("1"));
        put4.addColumn("f2".getBytes(),"address".getBytes(),Bytes.toBytes("四川隆中"));
        put4.addColumn("f2".getBytes(),"phone".getBytes(),Bytes.toBytes("14888888888"));
        put4.addColumn("f2".getBytes(),"say".getBytes(),Bytes.toBytes("出师表你背了嘛"));

        Put put5 = new Put("0006".getBytes());
        put5.addColumn("f1".getBytes(),"id".getBytes(),Bytes.toBytes(5));
        put5.addColumn("f1".getBytes(),"name".getBytes(),Bytes.toBytes("司马懿"));
        put5.addColumn("f1".getBytes(),"age".getBytes(),Bytes.toBytes(27));
        put5.addColumn("f2".getBytes(),"sex".getBytes(),Bytes.toBytes("1"));
        put5.addColumn("f2".getBytes(),"address".getBytes(),Bytes.toBytes("哪里人有待考究"));
        put5.addColumn("f2".getBytes(),"phone".getBytes(),Bytes.toBytes("15888888888"));
        put5.addColumn("f2".getBytes(),"say".getBytes(),Bytes.toBytes("跟诸葛亮死掐"));

        Put put6 = new Put("0007".getBytes());
        put6.addColumn("f1".getBytes(),"id".getBytes(),Bytes.toBytes(5));
        put6.addColumn("f1".getBytes(),"name".getBytes(),Bytes.toBytes("xiaobubu—吕布"));
        put6.addColumn("f1".getBytes(),"age".getBytes(),Bytes.toBytes(28));
        put6.addColumn("f2".getBytes(),"sex".getBytes(),Bytes.toBytes("1"));
        put6.addColumn("f2".getBytes(),"address".getBytes(),Bytes.toBytes("内蒙人"));
        put6.addColumn("f2".getBytes(),"phone".getBytes(),Bytes.toBytes("15788888888"));
        put6.addColumn("f2".getBytes(),"say".getBytes(),Bytes.toBytes("貂蝉去哪了"));

        List<Put> listPut = new ArrayList<Put>();
        listPut.add(put);
        listPut.add(put2);
        listPut.add(put3);
        listPut.add(put4);
        listPut.add(put5);
        listPut.add(put6);

        table.put(listPut);
    }

Get查询

  • 按照rowkey进行查询,获取所有列的所有值
  • 查询主键rowkey为0003的人
/**
     * 查询rowkey为0003的人
     * get -> Result
     */
    @Test
    public void getData() throws IOException {
        // Table table = connection.getTable(TableName.valueOf(TABLE_NAME));
        // 通过get对象,指定rowkey
        Get get = new Get(Bytes.toBytes("0001"));
        get.addFamily("f1".getBytes());//限制只查询f1列族下面所有列的值
        // 查询f2  列族 phone  这个字段
        get.addColumn("f2".getBytes(), "phone".getBytes());
        // 通过get查询,返回一个result对象,所有的字段的数据都是封装在result里面了
        Result result = table.get(get);
        List<Cell> cells = result.listCells();  //获取一条数据所有的cell,所有数据值都是在cell里面 的

        if (cells != null) {
            for (Cell cell : cells) {
                // 获取列族名
                byte[] familyName = CellUtil.cloneFamily(cell);
                // 获取列名
                byte[] columnName = CellUtil.cloneQualifier(cell);
                // 获取rowKey
                byte[] rowKey = CellUtil.cloneRow(cell);
                // 获取cell值
                byte[] cellValue = CellUtil.cloneValue(cell);
                // 需要判断字段的数据类型,使用对应的转换的方法,才能够获取到值
                if ("age".equals(Bytes.toString(columnName)) || "id".equals(Bytes.toString(columnName))) {
                    System.out.println(Bytes.toString(familyName));
                    System.out.println(Bytes.toString(columnName));
                    System.out.println(Bytes.toString(rowKey));
                    System.out.println(Bytes.toInt(cellValue));
                } else {
                    System.out.println(Bytes.toString(familyName));
                    System.out.println(Bytes.toString(columnName));
                    System.out.println(Bytes.toString(rowKey));
                    System.out.println(Bytes.toString(cellValue));
                }
            }
            table.close();
        }
    }

Scan查询

    /**
     * 不知道rowkey的具体值,我想查询rowkey范围值是0003  到0006
     * select * from myuser  where age > 30  and id < 8  and name like 'zhangsan'
     *
     */
    @Test
    public void scanData() throws IOException {
        // 获取table
        // Table table = connection.getTable(TableName.valueOf(TABLE_NAME));
        Scan scan = new Scan();// 没有指定startRow以及stopRow  全表扫描
        // 只扫描f1列族
        scan.addFamily("f1".getBytes());
        // 只扫描f2列族: phone  这个字段
        scan.addColumn("f2".getBytes(), "phone".getBytes());
        scan.withStartRow("0003".getBytes());
        scan.withStopRow("0007".getBytes());  // 前闭后开
        // 通过getScanner查询获取到了表里面所有的数据,是多条数据
        ResultScanner scanner = table.getScanner(scan);
        // 遍历ResultScanner 得到每一条数据,每一条数据都是封装在result对象里面了
        for (Result result : scanner) {
            List<Cell> cells = result.listCells();
            for (Cell cell : cells) {
                byte[] family_name = CellUtil.cloneFamily(cell);
                byte[] qualifier_name = CellUtil.cloneQualifier(cell);
                byte[] rowkey = CellUtil.cloneRow(cell);
                byte[] value = CellUtil.cloneValue(cell);
                //判断id和age字段,这两个字段是整形值
                if ("age".equals(Bytes.toString(qualifier_name)) || "id".equals(Bytes.toString(qualifier_name))) {
                    System.out.println("数据的rowkey为" + Bytes.toString(rowkey) + "======数据的列族为" + Bytes.toString(family_name) + "======数据的列名为" + Bytes.toString(qualifier_name) + "==========数据的值为" + Bytes.toInt(value));
                } else {
                    System.out.println("数据的rowkey为" + Bytes.toString(rowkey) + "======数据的列族为" + Bytes.toString(family_name) + "======数据的列名为" + Bytes.toString(qualifier_name) + "==========数据的值为" + Bytes.toString(value));
                }
            }
        }
        table.close();
    }

HBase过滤器查询

过滤器

  • 过滤器的作用是在服务端判断数据是否满足条件,然后只将满足条件的数据返回给客户端

  • 过滤器的类型很多,但是可以分为两大类

    • ==比较过滤器==
    • ==专用过滤器==

比较过滤器使用

  • HBase过滤器的比较运算符
LESS  <
LESS_OR_EQUAL <=
EQUAL =
NOT_EQUAL <>   不等于
GREATER_OR_EQUAL >=
GREATER >
NO_OP 排除所有
  • HBase比较过滤器的比较器(指定比较机制):
BinaryComparator  按字节索引顺序比较指定字节数组,采用Bytes.compareTo(byte[])
BinaryPrefixComparator 跟前面相同,只是比较左端前缀的数据是否相同
NullComparator 判断给定的是否为空
BitComparator 按位比较
RegexStringComparator 提供一个正则的比较器,仅支持 EQUAL 和非EQUAL
SubstringComparator 判断提供的子串是否出现在中

  • 比较过滤器

1、rowKey过滤器RowFilter

  • 通过RowFilter过滤比rowKey 0003小的所有值出来
    /**
     * 查询所有的rowkey比0003小的所有的数据
     */
    @Test
    public void rowFilter() throws IOException {
        // Table table = connection.getTable(TableName.valueOf(TABLE_NAME));
        Scan scan = new Scan();
        // 获取我们比较对象
        BinaryComparator binaryComparator = new BinaryComparator("0003".getBytes());
        /*
         * rowFilter需要加上两个参数
         * 第一个参数就是我们的比较规则
         * 第二个参数就是我们的比较对象
         */
        RowFilter rowFilter = new RowFilter(CompareFilter.CompareOp.LESS, binaryComparator);
        // 为我们的scan对象设置过滤器
        scan.setFilter(rowFilter);
        ResultScanner scanner = table.getScanner(scan);
        for (Result result : scanner) {
            List<Cell> cells = result.listCells();
            for (Cell cell : cells) {
                byte[] family_name = CellUtil.cloneFamily(cell);
                byte[] qualifier_name = CellUtil.cloneQualifier(cell);
                byte[] rowkey = CellUtil.cloneRow(cell);
                byte[] value = CellUtil.cloneValue(cell);
                // 判断id和age字段,这两个字段是整形值
                if ("age".equals(Bytes.toString(qualifier_name)) || "id".equals(Bytes.toString(qualifier_name))) {
                    System.out.println("数据的rowkey为" + Bytes.toString(rowkey) + "======数据的列族为" + Bytes.toString(family_name) + "======数据的列名为" + Bytes.toString(qualifier_name) + "==========数据的值为" + Bytes.toInt(value));
                } else {
                    System.out.println("数据的rowkey为" + Bytes.toString(rowkey) + "======数据的列族为" + Bytes.toString(family_name) + "======数据的列名为" + Bytes.toString(qualifier_name) + "==========数据的值为" + Bytes.toString(value));
                }
            }
        }
    }

2、列族过滤器FamilyFilter

  • 查询列族名包含f2的所有列族下面的数据
    /**
     * 通过familyFilter来实现列族的过滤
     * 需要过滤,列族名包含f2
     * f1  f2   hello   world
     */
    @Test
    public void familyFilter() throws IOException {
         // Table table = connection.getTable(TableName.valueOf(TABLE_NAME));
        Scan scan = new Scan();
        SubstringComparator substringComparator = new SubstringComparator("f2");
        // 通过familyfilter来设置列族的过滤器
        FamilyFilter familyFilter = new FamilyFilter(CompareFilter.CompareOp.EQUAL, substringComparator);
        scan.setFilter(familyFilter);
        ResultScanner scanner = table.getScanner(scan);
        for (Result result : scanner) {
            List<Cell> cells = result.listCells();
            for (Cell cell : cells) {
                byte[] familyName = CellUtil.cloneFamily(cell);
                byte[] qualifierName = CellUtil.cloneQualifier(cell);
                byte[] rowKey = CellUtil.cloneRow(cell);
                byte[] value = CellUtil.cloneValue(cell);
                // 判断id和age字段,这两个字段是整形值
                if ("age".equals(Bytes.toString(qualifierName)) || "id".equals(Bytes.toString(qualifierName))) {
                    System.out.println("数据的rowkey为" + Bytes.toString(rowKey) + "======数据的列族为" + Bytes.toString(familyName) + "======数据的列名为" + Bytes.toString(qualifierName) + "==========数据的值为" + Bytes.toInt(value));
                } else {
                    System.out.println("数据的rowkey为" + Bytes.toString(rowKey) + "======数据的列族为" + Bytes.toString(familyName) + "======数据的列名为" + Bytes.toString(qualifierName) + "==========数据的值为" + Bytes.toString(value));
                }
            }
        }
    }

3、列过滤器QualifierFilter

  • 只查询列名包含name的列的值
/**
     * 列名过滤器 只查询包含name列的值
     */
    @Test
    public void  qualifierFilter() throws IOException {
        Scan scan = new Scan();
        SubstringComparator substringComparator = new SubstringComparator("name");
        // 定义列名过滤器,只查询列名包含name的列
        QualifierFilter qualifierFilter = new QualifierFilter(CompareFilter.CompareOp.EQUAL, substringComparator);
        scan.setFilter(qualifierFilter);
        ResultScanner scanner = table.getScanner(scan);
        printResult(scanner);
    }
  public void printResult(ResultScanner scanner) {
      for (Result result : scanner) {
         List<Cell> cells = result.listCells();
         for (Cell cell : cells) {
            byte[] family_name = CellUtil.cloneFamily(cell);
            byte[] qualifier_name = CellUtil.cloneQualifier(cell);
            byte[] rowkey = CellUtil.cloneRow(cell);
            byte[] value = CellUtil.cloneValue(cell);
            //判断id和age字段,这两个字段是数值
            if("age".equals(Bytes.toString(qualifier_name))  || "id".equals(Bytes.toString(qualifier_name))){
               System.out.println("rowkey: " + Bytes.toString(rowkey) + ";列族: " + Bytes.toString(family_name) + ";列名: " + Bytes.toString(qualifier_name) + ";数据: " + Bytes.toInt(value));
            }else{
               System.out.println("rowkey: " + Bytes.toString(rowkey) + ";列族: " + Bytes.toString(family_name) + ";列名: " + Bytes.toString(qualifier_name) + ";数据: " + Bytes.toString(value));
            }
         }
      }
   }

4、列值过滤器ValueFilter

  • 查询所有列当中包含8的数据
    /**
     * 查询哪些字段值  包含数字8
     */
    @Test
    public void contains8() throws IOException {
        Scan scan = new Scan();
        SubstringComparator substringComparator = new SubstringComparator("8");
        // 列值过滤器,过滤列值当中包含数字8的所有的列
        ValueFilter valueFilter = new ValueFilter(CompareFilter.CompareOp.EQUAL, substringComparator);
        scan.setFilter(valueFilter);
        ResultScanner scanner = table.getScanner(scan);
        printResult(scanner);
    }

专用过滤器使用

1、单列值过滤器 SingleColumnValueFilter

  • SingleColumnValueFilter会返回满足条件的cell。所在行的所有cell的值

  • 查询f1 列族 name 列 值为刘备的数据

    /**
     */
    @Test
    public void singleColumnValueFilter() throws IOException {
        // 查询 f1  列族 name  列  值为刘备的数据
        Scan scan = new Scan();
        // 单列值过滤器,过滤  f1 列族  name  列  值为刘备的数据
        SingleColumnValueFilter singleColumnValueFilter = new SingleColumnValueFilter("f1".getBytes(), "name".getBytes(), CompareFilter.CompareOp.EQUAL, "刘备".getBytes());
        scan.setFilter(singleColumnValueFilter);
        ResultScanner scanner = table.getScanner(scan);
        printResult(scanner);
    }

2、列值排除过滤器SingleColumnValueExcludeFilter

  • 与SingleColumnValueFilter相反
    • 如果指定列的值符合filter条件,则会排除掉row中指定的列,其他的列全部返回
    • 如果列不存在或不符合filter条件,则不返回row中的列

3、rowkey前缀过滤器PrefixFilter

  • 查询以00开头的所有前缀的rowkey
    /**
     * 查询rowkey前缀以  00开头的所有的数据
     */
    @Test
    public  void  prefixFilter() throws IOException {
        Scan scan = new Scan();
        //过滤rowkey以  00开头的数据
        PrefixFilter prefixFilter = new PrefixFilter("00".getBytes());
        scan.setFilter(prefixFilter);
        ResultScanner scanner = table.getScanner(scan);
        printResult(scanner);
    }

4、分页过滤器PageFilter

  • 通过pageFilter实现分页过滤器
/**
     * HBase当中的分页
     */
    @Test
    public void hbasePageFilter() throws IOException {
               int pageNum = 3;
        int pageSize = 2;
        Scan scan = new Scan();
        String startRow = "";
        // 扫描数据的调试 扫描五条数据
        int scanDatas = (pageNum - 1) * pageSize + 1;
        scan.setMaxResultSize(scanDatas);//设置一步往前扫描多少条数据
        PageFilter filter = new PageFilter(scanDatas);
        scan.setFilter(filter);
        ResultScanner scanner = table.getScanner(scan);
        for (Result result : scanner) {
            // 获取rowkey
            byte[] row = result.getRow();
            // 最后一次startRow的值就是0005
            startRow = Bytes.toString(row);// 循环遍历我们所有获取到的数据的rowkey
            // 最后一条数据的rowkey就是我们需要的起始的rowkey
        }
        // 获取第三页的数据
        scan.withStartRow(startRow.getBytes());
        scan.setMaxResultSize(pageSize);//设置我们扫描多少条数据
        PageFilter filter1 = new PageFilter(pageSize);
        scan.setFilter(filter1);
        ResultScanner scanner1 = table.getScanner(scan);
        printResult(scanner1);
    }

说明:

  • pageSize = 2设置每页展示2条数据
  • pageNum = 3设置查询第3页数据
  • 计算查询首条记录的索引(pageNum - 1) * pageSize + 1

file

5、多过滤器综合查询FilterList

  • 需求:使用SingleColumnValueFilter查询f1列族,name为刘备的数据,并且同时满足rowkey的前缀以00开头的数据(PrefixFilter
    /**
     * 查询  f1 列族  name  为刘备数据值
     * 并且rowkey 前缀以  00开头数据
     */
    @Test
    public  void filterList() throws IOException {
        Scan scan = new Scan();
        SingleColumnValueFilter singleColumnValueFilter = new SingleColumnValueFilter("f1".getBytes(), "name".getBytes(), CompareFilter.CompareOp.EQUAL, "刘备".getBytes());
        PrefixFilter prefixFilter = new PrefixFilter("00".getBytes());
        FilterList filterList = new FilterList();
        filterList.addFilter(singleColumnValueFilter);
        filterList.addFilter(prefixFilter);
        scan.setFilter(filterList);
        ResultScanner scanner = table.getScanner(scan);
         printResult(scanner);
    }

说明:

  • SingleColumnValueFilter单列过滤器, 比较列值是否等于刘备
  • prefixFilter前缀过滤器用于匹配rowKey是否以00开头

Views: 26

Index