创建索引

最近更新时间:2026-04-13 16:58:42

我的收藏

简介

本文档介绍如何使用对象存储 COS 的 Go SDK 在指定的向量存储桶中创建一个新的向量索引。

功能说明

CreateIndex 方法用于在向量存储桶中新建一个向量索引。创建时必须指定向量的维度、距离度量方式(支持欧氏距离和余弦距离)以及数据类型,您还可以选择性地配置不允许用于过滤的元数据字段列表。

方法原型

func (s *VectorService) CreateIndex(ctx context.Context, opt *CreateIndexOptions) (*CreateIndexResult, *Response, error)

请求参数说明

CreateIndexOptions 结构体字段说明:
参数
描述
类型
是否必填
VectorBucketName
向量桶名称,格式为 <BucketName-APPID>,例如 examplebucket-1250000000
string
IndexName
需要创建的索引名称。
string
DataType
向量数据类型,当前仅支持 float32
string
Dimension
向量维度,整数类型,范围为 [1, 4096]
int
DistanceMetric
距离度量方式,支持 euclidean(欧氏距离)和 cosine(余弦距离)。
string
MetadataConfiguration
元数据配置,用于设置不参与过滤的元数据字段列表以优化性能。
*MetadataConfiguration
其中 MetadataConfiguration 包含:
参数
描述
类型
是否必填
NonFilterableMetadataKeys
不可用于过滤的元数据键列表,最少 1 个,最多 10 个。
[]string
当 MetadataConfiguration 存在时,此字段必填

返回结果说明

调用成功后,将返回 (*CreateIndexResult, *Response, error) 三个值。
CreateIndexResult 结构体字段说明:
参数
描述
类型
IndexQcs
创建成功后返回的向量索引资源名称(QCS)。
string
其他返回值说明:
返回值
描述
类型
resp
响应头信息,包含 HTTP 响应的详细对象等。
*cos.Response
err
错误信息。如果请求成功,返回 nil
error
如果请求失败,将返回非 nilerror。向量检索相关的业务错误会封装为 *cos.VectorErrorResponse 结构,您可以通过 cos.IsVectorError() 辅助函数判断并获取详细错误信息。详细的错误处理方式、VectorErrorResponse 结构体说明及服务端错误码列表请参见 异常处理 文档。

使用案例

package main

import (
"context"
"fmt"
"net/http"
"os"

cos "github.com/tencentyun/cos-go-sdk-v5"
)

func main() {
// 生成 Vector 基础 URL,第二个参数控制是否使用 HTTPS,建议为 true
vectorURL, _ := cos.NewVectorURL("ap-guangzhou", true)
// 初始化 Client,设置 VectorURL 及鉴权
client := cos.NewClient(&cos.BaseURL{VectorURL: vectorURL}, &http.Client{
Transport: &cos.AuthorizationTransport{
SecretID: os.Getenv("COS_VECTORS_SECRET_ID"),
SecretKey: os.Getenv("COS_VECTORS_SECRET_KEY"),
},
})

// 向量桶名称格式必须为:BucketName-APPID
bucketName := "examplebucket-1250000000"
indexName := "my-index"

// 构造创建索引的参数
opt := &cos.CreateIndexOptions{
VectorBucketName: bucketName,
IndexName: indexName,
DataType: "float32", // 向量数据类型,当前仅支持 float32
Dimension: 128, // 向量维度,范围 [1, 4096]
DistanceMetric: "cosine", // 距离度量方式:euclidean (欧氏距离) 或 cosine (余弦距离)
// 元数据配置(可选),指定哪些元数据键不用于过滤以节省索引资源
MetadataConfiguration: &cos.MetadataConfiguration{
NonFilterableMetadataKeys: []string{"unfilterable_key_1"},
},
}

// 调用创建索引方法
res, _, err := client.Vector.CreateIndex(context.Background(), opt)
if err != nil {
if vecErr, ok := cos.IsVectorError(err); ok {
fmt.Printf("向量服务错误,错误码: %s, 错误信息: %s, 请求ID: %s\\n",
vecErr.Code, vecErr.Message, vecErr.RequestID)
} else {
fmt.Printf("请求失败: %v\\n", err)
}
return
}

// 打印创建后的向量索引资源名称 QCS
fmt.Printf("向量索引创建成功,QCS: %s\\n", res.IndexQcs)
}