> 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/ja/sdks/upsert-and-search-vectors.md).

# ベクトルのアップサートと検索

Unitlab Python SDK でライブラリファイルや動画フレームのベクトルを埋め込みスペースに書き込み（アップサート）、コサイン類似度で最も類似したファイルやフレームを検索する方法を解説します。

## ベクトルの書き込み <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 回あたり最大 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` はファイルごとに 1 件、`frame` は動画フレームごとに 1 件 |

`score` はコサイン類似度で、1 は同一を意味します。

## 関連情報 <a href="#related" id="related"></a>

[埋め込みスペース](https://docs.unitlab.ai/api-sdk-cli/ja/sdks/embedding-spaces.md) · [パターン：埋め込み検索](https://docs.unitlab.ai/api-sdk-cli/ja/sdks/pattern-custom-embedding-pipeline.md)
