HBASE & Java: Search for Data

(Last Updated On: )

This tutorial will give you a quick overview of how to search for data using HBASE. If you have not done so yet. Follow the following two tutorials on HBASE: Connecting and HBASE: Create a Table.

Search for Data:

Basically we have to scan the table for data. So we must first setup a scan object then search for the data.

  1. import org.apache.hadoop.hbase.client.Result;
  2. import org.apache.hadoop.hbase.client.ResultScanner;
  3. import org.apache.hadoop.hbase.client.Scan;
  4. import org.apache.hadoop.hbase.Cell;
  5. import org.apache.hadoop.hbase.client.Table;
  6. import org.apache.hadoop.hbase.TableName;
  7. import org.apache.hadoop.hbase.util.Bytes;
  8.  
  9. //Lets setup our scan object.
  10. final Scan scan = new Scan();
  11. //Search a particular column
  12. scan.addColumn(Bytes.toBytes("columnFamily"), Bytes.toBytes("columnName"));
  13. //Check the row key prefix
  14. scan.setRowPrefixFilter(Bytes.toBytes("rowkey"));
  15.  
  16. final TableName table = TableName.valueOf(yourTableName);
  17.  
  18. //Get the table you want to work with. using the connection from the tutorial above.
  19. final Table table = conn.getTable(table);
  20. //Create our scanner based on the scan object above.
  21. final ResultScanner scanner = table.getScanner(scan);
  22.  
  23. //Now we will loop through our results
  24. for (Result result = scanner.next(); result != null; result = scanner.next()) {
  25. //Lets get our row key
  26. final String rowIdentifier = Bytes.toString(result.getRow());
  27.  
  28. //Now based on each record found we will loop through the available cells for that record.
  29. for (final Cell cell : result.listCells()) {
  30. //now we can do whatever we need to with the data.
  31. log.info("column {} value {}", Bytes.toString(cell.getQualifierArray(), cell.getQualifierOffset(), cell.getQualifierLength()), Bytes.toString(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength()));
  32. }
  33. }
  34.  

One thought on “HBASE & Java: Search for Data”

Comments are closed.