东门芳洲 发表于 2025-11-4 16:25:03

如何通过Python SDK向Collection中插入或更新Doc

本文介绍如何通过Python SDK向Collection中插入或更新Doc。
说明

[*]若调用本接口时Doc Id已存在,则等同于更新Doc;
Doc Id不存在,则等同于插入Doc。
[*]若调用本接口时不指定Doc Id,则等同于插入Doc,DashVector会自动生成Doc Id,并在返回结果中携带id信息。
前提条件


[*]已创建Cluster
[*]已获得API-KEY
[*]已安装最新版SDK
接口定义

Python示例:
Collection.upsert(
    docs: Union, Tuple, List],
    partition: Optional = None,
    async_req: False
) -> DashVectorResponse使用示例

说明

[*]需要使用您的api-key替换示例中的YOUR_API_KEY、您的Cluster Endpoint替换示例中的YOUR_CLUSTER_ENDPOINT,代码才能正常运行。
[*]本示例需要参考新建Collection-使用示例提前创建好名称为quickstart的Collection。
Python示例:
import dashvector
from dashvector import Doc
import numpy as np

client = dashvector.Client(
    api_key='YOUR_API_KEY',
    endpoint='YOUR_CLUSTER_ENDPOINT'
)
collection = client.get(name='quickstart')插入或更新Doc

Python示例:
# 通过Doc对象upsert
ret = collection.upsert(
    Doc(
      id='1',
      vector=
    )
)
# 判断upsert是否成功
assert ret

# 简化形式:通过Tuple upsert
ret = collection.upsert(
    ('2', )               # (id, vector)
)插入或更新不带有Id的Doc

Python
# 通过Doc对象upsert
ret = collection.upsert(
    Doc(vector=)
)
# 简化形式:通过Tuple upsert
ret = collection.upsert(
    (,)         
)插入或更新带有Fields的Doc

Python示例:
# upsert单条数据,并设置Fields Value
ret = collection.upsert(
    Doc(
      id='3',
      vector=np.random.rand(4),
      fields={
            # 设置创建Collection时预定义的Fileds Value
            # name:str, weight:float, age:int, id:long
            'name': 'zhangsan', 'weight':70.0, 'age':30, 'id':1234567890,
            # 设置Schema-Free的Field & Value
            'anykey1': 'str-value', 'anykey2': 1,
            'anykey3': True, 'anykey4': 3.1415926
      }
    )
)

# upsert单条数据,并设置Fields Value
ret = collection.upsert(
    ('4', np.random.rand(4), {'foo': 'bar'})# (id, vector, fields)
)批量插入或更新Doc

Python示例:
# 通过Doc对象,批量upsert 10条数据
ret = collection.upsert(
    [
      Doc(id=str(i+5), vector=np.random.rand(4)) for i in range(10)
    ]
)

# 简化形式:通过Tuple,批量upsert 3条数据
ret = collection.upsert(
    [
      ('15', , {'age': 20}),
      ('16', , {'age': 30}),
      ('17', , {'age': 40})
    ]                                       # List[(id, vector, fields)]
)

# 判断批量upsert是否成功
assert ret异步插入或更新Doc

Python示例:
# 异步批量upsert 10条数据
ret_funture = collection.upsert(
    [
      Doc(id=str(i+18), vector=np.random.rand(4), fields={'name': 'foo' + str(i)}) for i in range(10)
    ],
    async_req=True
)
# 等待并获取异步upsert结果
ret = ret_funture.get()插入或更新带有Sparse Vector的Doc

Python示例:
ret = collection.upsert(
    Doc(
      id='28',
      vector=,
      sparse_vector={1:0.4, 10000:0.6, 222222:0.8}
    )
)
来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

官厌 发表于 2025-11-13 00:55:28

懂技术并乐意极积无私分享的人越来越少。珍惜

孜尊 发表于 2025-12-8 04:36:12

东西不错很实用谢谢分享

纪睐讦 发表于 5 天前

很好很强大我过来先占个楼 待编辑

予捻 发表于 3 天前

懂技术并乐意极积无私分享的人越来越少。珍惜
页: [1]
查看完整版本: 如何通过Python SDK向Collection中插入或更新Doc