Updated on 2024-04-02 GMT+08:00

Filtering Data

Function

HBase Filter is used to filter data during Scan and Get. You can specify the filter criteria, such as filtering by RowKey, column name, or column value.

Example Code

The following code snippet belongs to thetestSingleColumnValueFilter method in the HBaseSample class of the com.huawei.bigdata.hbase.examples package.

public void testSingleColumnValueFilter() {
    LOG.info("Entering testSingleColumnValueFilter.");
    Table table = null;

    ResultScanner rScanner = null;

    try {

      table = conn.getTable(tableName);

      Scan scan = new Scan();
      scan.addColumn(Bytes.toBytes("info"), Bytes.toBytes("name"));
      // Set the filter criteria.
      SingleColumnValueFilter filter = new SingleColumnValueFilter(
          Bytes.toBytes("info"), Bytes.toBytes("name"), CompareOperator.EQUAL,
          Bytes.toBytes("Xu Bing"));
      scan.setFilter(filter);
      // Submit a scan request.
      rScanner = table.getScanner(scan);
      // Print query results.
       for (Result r = rScanner.next(); r != null; r = rScanner.next()) {
         for (Cell cell : r.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("Single column value filter successfully.");
    } catch (IOException e) {
      LOG.error("Single column value filter failed " ,e);
    } finally {
        if (rScanner != null) {
            // Close the scanner object.
            rScanner.close();
          }
      if (table != null) {
        try {
          // Close the HTable object.
          table.close();
        } catch (IOException e) {
          LOG.error("Close table failed " ,e);
        }
      }
    }
    LOG.info("Exiting testSingleColumnValueFilter.");
  }

Precautions

Currently, secondary indexes do not support the comparators that use objects of the SubstringComparator class as filters.

For example, the following sample code is not supported:

Scan scan = new Scan();
filterList = new FilterList(FilterList.Operator.MUST_PASS_ALL);
filterList.addFilter(new SingleColumnValueFilter(Bytes
.toBytes(columnFamily), Bytes.toBytes(qualifier),
CompareOperator.EQUAL, new SubstringComparator(substring)));
scan.setFilter(filterList);