插入向量

最近更新时间:2026-04-01 15:41:32

我的收藏

简介

本文档介绍如何使用对象存储 COS 的 Go SDK 向指定的向量索引中插入一个或多个向量。

功能说明

PutVectors 方法用于向指定的向量索引中写入向量数据及其关联的元数据。使用向量的 Key 字段作为唯一标识符,如果插入的 Key 已存在,旧数据将被新数据覆盖
注意:
单次请求最多可插入500条向量。
向量数据中不允许出现无效值(如 NaN 或 Infinity)。
若目标向量索引以余弦距离(cosine)度量,则不允许写入零向量。

方法原型

func (s *VectorService) PutVectors(ctx context.Context, opt *PutVectorsOptions, vectors []InputVector) (*Response, error)

请求参数说明

PutVectorsOptions 结构体字段说明:
参数
描述
类型
是否必填
VectorBucketName
向量桶名称,格式为 <BucketName-APPID>,例如 examplebucket-1250000000
支持小写字母、数字和 -,长度限制为3-63个字符。
string
IndexName
向量索引名称。
string
vectors 参数说明:
参数
描述
类型
是否必填
vectors
写入的向量数据列表,数组长度为1~500。
[]InputVector
InputVector 结构体字段说明:
参数
描述
类型
是否必填
Key
向量的主键,用于标识向量索引内的唯一向量。长度为1~1024字符,需为 UTF-8格式。单次请求中不允许出现相同 Key 的多条向量。
string
Data
向量数据。输入向量的维度和数据类型必须与创建向量索引时指定的相匹配。
*VectorData
Metadata
向量关联的元数据。限制条件:
元数据总大小不超过40KB。
可过滤元数据总大小不超过2KB。
元数据键个数不超过10个。
支持类型:整数、浮点数、字符串、数组。
map[string]interface{}
VectorData 结构体字段说明:
参数
描述
类型
是否必填
Float32
float32 类型的向量数据(数组形式)。
[]float32

返回结果说明

调用成功后,将返回 (*Response, error) 两个值。本方法无特殊的业务返回字段,当 error == nil 时表示插入成功。
返回值
描述
类型
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.PutVectorsOptions{
VectorBucketName: bucketName,
IndexName: indexName,
}

// 构建向量数据(单条)
vectors := []cos.InputVector{
{
Key: "vector-001",
Data: &cos.VectorData{
Float32: []float32{0.1, 0.2, 0.3},
},
Metadata: map[string]interface{}{
"category": "document",
"title": "示例文档",
},
},
}

// 调用插入向量方法
_, err := client.Vector.PutVectors(context.Background(), opt, vectors)
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
}

fmt.Println("向量插入成功")
}

案例二:批量插入多条向量(含元数据)

package main

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

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

func main() {
vectorURL, _ := cos.NewVectorURL("ap-guangzhou", true)

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 := "examplebucket-1250000000"
indexName := "my-index"

opt := &cos.PutVectorsOptions{
VectorBucketName: bucketName,
IndexName: indexName,
}

// 批量构建向量数据
vectors := []cos.InputVector{
{
Key: "doc-001",
Data: &cos.VectorData{Float32: []float32{0.1, 0.2, 0.3}},
Metadata: map[string]interface{}{
"genre": "drama",
"year": 2023,
"tags": []string{"经典", "推荐"},
},
},
{
Key: "doc-002",
Data: &cos.VectorData{Float32: []float32{0.4, 0.5, 0.6}},
Metadata: map[string]interface{}{
"genre": "comedy",
"year": 2024,
"tags": []string{"热门"},
},
},
{
Key: "doc-003",
Data: &cos.VectorData{Float32: []float32{0.7, 0.8, 0.9}},
Metadata: map[string]interface{}{
"genre": "action",
"year": 2025,
},
},
}

_, err := client.Vector.PutVectors(context.Background(), opt, vectors)
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
}

fmt.Printf("成功插入 %d 条向量到索引 %s\\n", len(vectors), indexName)
}