---
title: 创建索引
description: "addIndices API和addIndicesWithData API用于创建索引表，前者可创建无数据的空索引表，后者可创建拥有数据填充的索引表。"
url: https://www.hikunpeng.com/document/detail/zh/kunpengboostkithistory/2400/bds/kunpengbds_omniruntime_20_0619.html
sourcePath: /source/zh/kunpengboostkithistory/2400/bds/kunpengbds_omniruntime_20_0619.html
indexId: 544d93aac479ad086248ce03ebad397f3626fc46af75c87d936744e554f4894778
---
# 创建索引

addIndices API和addIndicesWithData API用于创建索引表，前者可创建无数据的空索引表，后者可创建拥有数据填充的索引表。

#### addIndices API

- API

```
void addIndices(TableName tableName, TableIndices tableIndices)
```


- 功能描述
  客户端调用接口创建索引表，创建成功后索引表为空，无数据填充。

- API描述

  1. 包名：package com.huawei.boostkit.hindex
  2. 类名：GlobalIndexAdmin
  3. 方法名：addIndices
  4. 参数详情：| 参数名称 | 取值类型 | 描述 |
| --- | --- | --- |
| tableName | TableName | 用户数据表 |
| tableIndices | TableIndices | 将要添加的索引表 |


- 使用样例

```
//创建用户表myuser，并添加数据
Admin admin = connection.getAdmin();
TableName myuser = TableName.valueOf("myuser");
HTableDescriptor hTableDescriptor = new HTableDescriptor(myuser);
HColumnDescriptor f1 = new HColumnDescriptor("f1");
hTableDescriptor.addFamily(f1);
admin.createTable(hTableDescriptor);
//创建索引表myindex
TableIndices myindex = new TableIndices();
HIndexSpecification spec = new HIndexSpecification("myindex");
//对数据表f1列族的q1创建索引，数据类型是STRING
spec.addIndexColumn(Bytes.toBytes("f1"), Bytes.toBytes("q1"), ValueType.STRING);
myindex.addIndex(spec);
GlobalIndexAdmin globalIndexAdmin = GlobalIndexClient.newIndexAdmin(admin);
globalIndexAdmin.addIndices(myuser, myindex);
```


- 样例结果
  对myuser数据表创建出myindex索引表，索引表中无数据。


#### addIndicesWithData API

- API

```
void addIndicesWithData(TableName tableName, TableIndices tableIndices)
```


- 功能描述
  客户端创建索引请求接口，调用接口创建索引表并填充数据，创建成功后得到完整数据的索引表。

- API描述

  1. 包名：package com.huawei.boostkit.hindex
  2. 类名：GlobalIndexAdmin
  3. 方法名：addIndicesWithData
  4. 参数详情：| 参数名称 | 取值类型 | 描述 |
| --- | --- | --- |
| tableName | TableName | 用户数据表 |
| tableIndices | TableIndices | 将要添加的索引表 |


- 使用样例

```
//创建用户表myuser，并添加数据
Admin admin = connection.getAdmin();
TableName myuser = TableName.valueOf("myuser");
HTableDescriptor hTableDescriptor = new HTableDescriptor(myuser);
HColumnDescriptor f1 = new HColumnDescriptor("f1");
hTableDescriptor.addFamily(f1);
admin.createTable(hTableDescriptor);
try (Table table = conn.getTable(myuser)) {
Put put0 = new Put(Bytes.toBytes("001"));
put0.addColumn(Bytes.toBytes("f1"), Bytes.toBytes("q1"), Bytes.toBytes("test"));
table.put(ImmutableList.of(put0));
}
//创建索引表myindex
TableIndices myindex = new TableIndices();
HIndexSpecification spec = new HIndexSpecification("myindex");
//对数据表f1列族的q1创建索引，数据类型是STRING
spec.addIndexColumn(Bytes.toBytes("f1"), Bytes.toBytes("q1"), ValueType.STRING);
myindex.addIndex(spec);
GlobalIndexAdmin globalIndexAdmin = GlobalIndexClient.newIndexAdmin(admin);
globalIndexAdmin.addIndicesWithData(myuser, myindex);
```


- 样例结果
  对myuser数据表创建出myindex索引表，索引表中有完整的索引数据。
