帮你快速理解、总结文档立即下载

插入或覆写文档

最近更新时间:2026-11-27 18:59:36
本文档已由 AI 辅助审校
我的收藏

简介

本文介绍通过 Python SDK 插入或覆写文档的示例代码和参数说明。

功能说明

upsert_documents 通过 Native API 按主键整行插入或覆写文档,支持行式和列式负载。
注意:
未在负载中出现的字段会被置为 null。只需更新部分字段时,请使用 部分更新文档。

方法原型

upsert_documents(self, Bucket, Namespace, Rows=None, Columns=None, PrimaryKeySpecified=False, **kwargs)

使用案例

import os
from qcloud_cos import CosConfig, CosVectorsClient, CosServiceError

config = CosConfig(
Region='ap-guangzhou',
SecretId=os.getenv('COS_VECTORS_SECRET_ID'),
SecretKey=os.getenv('COS_VECTORS_SECRET_KEY'),
)
client = CosVectorsClient(config)

try:
resp = client.upsert_documents(
Bucket='examplebucket-1250000000',
Namespace='products',
Rows=[
{
'id': 'product-1',
'title': 'Vector database',
'price': 12.5,
'embedding': [0.1, 0.2, 0.3, 0.4]
},
{
'id': 'product-2',
'title': 'Object storage',
'price': 9.9,
'embedding': [0.4, 0.3, 0.2, 0.1]
}
],
PrimaryKeySpecified=True
)
print('响应头:', resp)
except CosServiceError as e:
print(f'写入失败: {e}')

使用列式负载写入文档

以下示例使用已初始化的 client。每行均显式携带用户主键,因此设置 PrimaryKeySpecified=True。
try:
resp = client.upsert_documents(
Bucket='examplebucket-1250000000',
Namespace='products',
Columns={
'id': ['product-1', 'product-2'],
'title': ['Vector database', 'Object storage'],
'price': [12.5, 9.9],
'embedding': [[0.1, 0.2, 0.3, 0.4], [0.4, 0.3, 0.2, 0.1]]
},
PrimaryKeySpecified=True
)
print('响应头:', resp)
except CosServiceError as e:
print(f'写入失败: {e}')

使用系统自动主键写入文档

以下示例使用未指定 primary_key 的命名空间。行中省略 _id,由服务端逐行生成主键。
try:
resp = client.upsert_documents(
Bucket='examplebucket-1250000000',
Namespace='notes',
Rows=[
{'title': 'First note'},
{'title': 'Second note'}
]
)
print('响应头:', resp)
except CosServiceError as e:
print(f'写入失败: {e}')
PrimaryKeySpecified 默认 False。自动主键场景遇到5xx或网络错误时不进行歧义重试,避免首次写入实际成功后再次生成重复文档。

参数说明

参数
描述
类型
是否必选
Bucket
增强型向量桶名称,采用 <BucketName-APPID> 格式
string
是
Namespace
目标命名空间名称
string
是
Rows
行式负载,每个元素为一个文档。与 Columns 必须且只能提供一个
list
二选一
Columns
列式负载,字段名到取值数组的映射,各列长度必须一致。与 Rows 必须且只能提供一个
dict
二选一
PrimaryKeySpecified
客户端重试声明,不会写入请求体。默认 False,遇到5xx或网络错误不自动重试;为 True 时按客户端重试配置执行,表示调用方保证每行均携带用户主键或显式 _id。SDK 不校验该声明,用于避免自动主键场景重试后重复写入
bool
否
kwargs
设置请求头部
dict
否
负载格式和取值编码请参见 写入负载与取值编码,接口约束请参见 Upsert。

返回结果说明

返回值

resp(dict):响应头信息。

错误处理

请求失败时会抛出 CosServiceError 或 CosClientError,详情请参见 异常处理。