
# 创建HBase全局二级索引
#### 功能简介
通过调用"org.apache.hadoop.hbase.hindex.global.GlobalIndexAdmin"中的方法进行HBase全局二级索引的管理，该类中**addIndices**用于创建全局二级索引。
全局二级索引的创建需要指定索引列、覆盖列（可选）、索引表预分区（可选，建议指定）。
![](https://support.huaweicloud.com/devg-lts-mrs/public_sys-resources/note_3.0-zh-cn.png)
在已有存量数据的表上创建全局二级索引，需要创建索引预分区，防止索引表出现热点，索引表数据的rowkey由索引列构成，并且包含分隔符，格式为"**\\x01** *索引值* **\\x00** "，因此预分区需要指定成对应格式，例如，当使用**id** 列和**age** 列作为索引列时，两个列均为整数，使用**id**列完成预分区，可以指定索引表预分区点为：
**\\x010,\\x011,\\x012....**
#### 代码样例
以下代码片段在com.huawei.bigdata.hbase.examples包的"GlobalSecondaryIndexSample"类的**addIndices**方法中。
本样例为数据表**user_table** 创建一个名为**index_id_age** 的索引，使用数据中的**id** 和**age** 两个列作为索引列，同时覆盖**name**列（查询条件不会用到，但是查询结果需要返回该列）。
```
/**
    * createIndex
    */
public void testCreateIndex() {
    LOG.info("Entering createIndex.");
    // Create index instance
    TableIndices tableIndices = new TableIndices();
    // Create index spec
    // idx_id_age covered info:name
    HIndexSpecification indexSpec = new HIndexSpecification("idx_id_age");
    // Set index column
    indexSpec.addIndexColumn(Bytes.toBytes("info"), Bytes.toBytes("id"), ValueType.STRING);
    indexSpec.addIndexColumn(Bytes.toBytes("info"), Bytes.toBytes("age"), ValueType.STRING);
    // Set covered column
    // If you want cover one column, use addCoveredColumn
    // If you want cover all column in one column family, use addCoveredFamilies
    // If you want cover all column of all column family, use setCoveredAllColumns
    indexSpec.addCoveredColumn(Bytes.toBytes("info"), Bytes.toBytes("name"));
    // Need specify index table split keys, it should specify by index column.
    // Note: index data's row key has a same prefix "\x01"
    // For example:
    // Our index column include "id" and "age", "id" is a number, we
    // could specify split key like \x010 \x011 \x012...
    byte[][] splitKeys = new byte[10][];
    for (int i = 0; i < 10; i++) {
        splitKeys[i] = Bytes.toBytesBinary("\\x01" + i);
    }
    indexSpec.setSplitKeys(splitKeys);
    tableIndices.addIndex(indexSpec);
    // iAdmin will close the inner admin instance
    try (GlobalIndexAdmin iAdmin = GlobalIndexClient.newIndexAdmin(conn.getAdmin())) {
        // add index to the table
        iAdmin.addIndices(tableName, tableIndices);
        LOG.info("Create index successfully.");
    } catch (IOException e) {
        LOG.error("Create index failed.", e);
    }
    LOG.info("Exiting createIndex.");
}
```
