HBase应用(2.4)表扫描

通过扫描访问数据

HBase中没有query命令,但是可以通过Scan来扫描并返回记录。

清空users表,向users表中插入jack, jerry, tom3条记录,扫描名字以j开头的数据

  • HBase Shell:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    hbase(main):002:0> truncate 'users'
    Truncating 'users' table (it may take a while):
    - Disabling table...
    - Truncating table...
    0 row(s) in 4.4880 seconds

    hbase(main):003:0> put 'users', 'jack', 'info:gender', 'male'
    0 row(s) in 0.2230 seconds

    hbase(main):004:0> put 'users', 'jerry', 'info:gender', 'male'
    0 row(s) in 0.0080 seconds

    hbase(main):005:0> put 'users', 'tom', 'info:gender', 'male'
    0 row(s) in 0.0090 seconds

    hbase(main):006:0> put 'users', 'jack', 'info:age', 18
    0 row(s) in 0.0160 seconds

    hbase(main):007:0> put 'users', 'jerry', 'info:age', 21
    0 row(s) in 0.0200 seconds

    hbase(main):008:0> put 'users', 'tom', 'info:age', 15
    0 row(s) in 0.0210 seconds

    hbase(main):019:0> scan 'users', {COLUMNS => ['info:age'], STARTROW => 'j', ENDROW => 'k'}
    ROW COLUMN+CELL
    jack column=info:age, timestamp=1523933630580, value=18
    jerry column=info:age, timestamp=1523933639584, value=21
    2 row(s) in 0.0240 seconds
  • Java Client:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    package info.aviraer.demo.bigdata.core.hbase.chapter2;

    import java.io.IOException;

    import org.apache.hadoop.conf.Configuration;
    import org.apache.hadoop.hbase.HBaseConfiguration;
    import org.apache.hadoop.hbase.TableName;
    import org.apache.hadoop.hbase.client.Connection;
    import org.apache.hadoop.hbase.client.ConnectionFactory;
    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;

    public class ScanData {

    public static void main(String[] args) throws IOException {
    Configuration config = HBaseConfiguration.create();
    //配置zookeeper集群
    config.set("hbase.zookeeper.quorum", "centos0,centos1,centos2");
    Connection connection = ConnectionFactory.createConnection(config);

    Table table = connection.getTable(TableName.valueOf("users"));

    Scan scan = new Scan("j".getBytes(), "k".getBytes());
    ResultScanner resultScanner = table.getScanner(scan);
    for (Result result : resultScanner) {
    System.out.println(new String(result.getRow()) + new String(result.getValue("info".getBytes(), "age".getBytes())));
    }

    table.close();
    connection.close();
    }

    }