MAPREDUCE服务 MRS-使用HBase二级索引读取数据:代码样例

时间:2024-06-19 16:04:41

代码样例

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

  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.");
  }
support.huaweicloud.com/devg-mrs/mrs_06_0331.html