更新时间:2024-12-10 GMT+08:00

使用HBase二级索引读取数据

功能介绍

在具有HIndexes的用户表中,HBase使用Filter来查询数据。

代码样例

以下代码片段在com.huawei.bigdata.hbase.examples包的“HIndexExample”类的scanDataByHIndex方法中。

样例代码获取方式请参考获取MRS应用开发样例工程

代码样例:

  public void scanDataByHIndex() {
    LOG.info("Entering HIndex-based Query.");
    Table table = null;
    ResultScanner rScanner = null;
    try {
      table = conn.getTable(tableName);
      // Create a filter for indexed column.
      SingleColumnValueFilter filter = new SingleColumnValueFilter(Bytes.toBytes("info"), Bytes.toBytes("age"),
          CompareOp.GREATER_OR_EQUAL, Bytes.toBytes("26"));
      filter.setFilterIfMissing(true);

      Scan scan = new Scan();
      scan.setFilter(filter);
      rScanner = table.getScanner(scan);

      // Scan the data
      LOG.info("Scan data using indices..");
      for (Result result : rScanner) {
        LOG.info("Scanned row is:");
        for (Cell cell : result.rawCells()) {
          LOG.info(Bytes.toString(CellUtil.cloneRow(cell)) + ":" + Bytes.toString(CellUtil.cloneFamily(cell)) + ","
              + Bytes.toString(CellUtil.cloneQualifier(cell)) + "," + Bytes.toString(CellUtil.cloneValue(cell)));
        }
      }
      LOG.info("Successfully scanned data using indices for table " + tableName + ".");
    } catch (IOException e) {
      LOG.error("Failed to scan data using indices for table " + tableName + "." + e);
    } finally {
      if (rScanner != null) {
        rScanner.close();
      }
      if (table != null) {
        try {
          table.close();
        } catch (IOException e) {
          LOG.error("failed to close table, ", e);
        }
      }
    }
    LOG.info("Entering HIndex-based Query.");
  }