Querying HBase Table Data Based on Global Secondary Indexes
Function
When a user table with a global secondary index is used for query, the query can be converted to a range query of the index table. The query performance is higher than that of a user table without a secondary index.
Code Sample
The following code snippets are in the GlobalSecondaryIndexSample class of the com.huawei.bigdata.hbase.examples package.
In this case, the values of id, age, and name of the specified id are queried, and the idx_id_age index is selected. The query results are completely overwritten. As a result, you do not need to query in the original table to achieve optimal query performance.
/**
* Scan data by secondary index.
*/
public void testScanDataByIndex() {
LOG.info("Entering testScanDataByIndex.");
Scan scan = new Scan();
// Create a filter for indexed column.
SingleColumnValueFilter filter = new SingleColumnValueFilter(Bytes.toBytes("info"), Bytes.toBytes("id"),
CompareOperator.EQUAL, Bytes.toBytes("3"));
filter.setFilterIfMissing(true);
scan.setFilter(filter);
// Specify returned columns
// If returned columns not included in index table, will query back user table,
// it's not the fast way to get data, suggest to cover all needed columns.
// If you want to confirm whether using index for scanning, please set hbase client log level to DEBUG.
scan.addColumn(Bytes.toBytes("info"), Bytes.toBytes("id"));
scan.addColumn(Bytes.toBytes("info"), Bytes.toBytes("age"));
scan.addColumn(Bytes.toBytes("info"), Bytes.toBytes("name"));
LOG.info("Scan indexed data.");
try (Table table = conn.getTable(tableName); ResultScanner scanner = table.getScanner(scan)) {
for (Result result : scanner) {
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("Scan data by index successfully.");
} catch (IOException e) {
LOG.error("Scan data by index failed ", e);
}
LOG.info("Exiting testScanDataByIndex.");
} What is your overall rating for this page?
Thank you very much for your feedback. We will continue working to improve the documentation.See the reply and handling status in My Cloud VOC.
For any further questions, feel free to contact us through the chatbot.
Chatbot