> For the complete documentation index, see [llms.txt](https://docs.unitlab.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.unitlab.ai/api-sdk-cli/zh/sdks/upsert-and-search-vectors.md).

# 写入与搜索向量

使用 Unitlab Python SDK 为资产库文件和视频帧写入（upsert）向量，并通过向量相似度搜索最相似的文件或帧。

## 写入向量 <a href="#write-vectors" id="write-vectors"></a>

```python
space.upsert("ASSET_ID", vector)                         # one file
space.upsert("VIDEO_ASSET_ID", vector, frame_index=120)  # one video frame

report = space.upsert_many(
    {"asset_id": asset_id, "vector": vec} for asset_id, vec in my_vectors
)
print(report["created"], "created,", report["updated"], "updated")
```

为已有向量的文件或帧写入向量时，会替换原有向量。每次 `upsert_many()` 调用最多发送 1,000 条，更大的数据请拆分。

## 搜索 <a href="#search" id="search"></a>

```python
hits = space.search(query_vector, limit=20, project_id=project.id, level="asset")
for hit in hits["results"]:
    print(hit["score"], hit["file_name"], hit["asset_id"], hit["frame_index"])
```

| 参数           | 默认值     | 含义                                     |
| ------------ | ------- | -------------------------------------- |
| `vector`     | 必填      | 长度与空间一致                                |
| `limit`      | 20      | 1 到 100 条结果                            |
| `project_id` | 无       | 仅搜索该项目中的文件                             |
| `level`      | `asset` | `asset` 表示每个文件一条结果，`frame` 表示每个视频帧一条结果 |

`score` 为余弦相似度：1 表示完全相同。

## 相关内容 <a href="#related" id="related"></a>

[Embedding Space](https://docs.unitlab.ai/api-sdk-cli/zh/sdks/embedding-spaces.md) · [模式：向量检索](https://docs.unitlab.ai/api-sdk-cli/zh/sdks/pattern-custom-embedding-pipeline.md)
