> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-TW/llms.txt # Amazon S3 向量儲存 `S3Vectors` 類別使用 [Amazon S3 Vectors(預覽版)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/s3-vectors.html)提供向量搜尋。它會將向量儲存在**向量 bucket** 中,並在**向量索引**中搭配 JSON 中繼資料篩選條件執行相似度搜尋。 > **警告:** Amazon S3 Vectors 是預覽版服務。預覽功能可能會變更或移除,恕不另行通知,且不受 AWS SLA 保障。其行為、限制與區域可用性隨時可能變更。此程式庫可能會引入重大變更,以與 AWS 保持一致。 ## 安裝 **npm**: ```bash npm install @mastra/s3vectors@latest ``` **pnpm**: ```bash pnpm add @mastra/s3vectors@latest ``` **Yarn**: ```bash yarn add @mastra/s3vectors@latest ``` **Bun**: ```bash bun add @mastra/s3vectors@latest ``` ## 使用範例 ```typescript import { S3Vectors } from '@mastra/s3vectors' const store = new S3Vectors({ vectorBucketName: process.env.S3_VECTORS_BUCKET_NAME!, // e.g. "my-vector-bucket" clientConfig: { region: process.env.AWS_REGION!, // credentials use the default AWS provider chain }, // Optional: mark large/long-text fields as non-filterable at index creation time nonFilterableMetadataKeys: ['content'], }) // Create an index (names are normalized: "_" → "-" and lowercased) await store.createIndex({ indexName: 'my_index', dimension: 1536, metric: 'cosine', // "euclidean" also supported; "dotproduct" is NOT supported }) // Upsert vectors (ids auto-generated if omitted). Date values in metadata are serialized to epoch ms. const ids = await store.upsert({ indexName: 'my_index', vectors: [ [0.1, 0.2 /* … */], [0.3, 0.4 /* … */], ], metadata: [ { text: 'doc1', genre: 'documentary', year: 2023, createdAt: new Date('2024-01-01'), }, { text: 'doc2', genre: 'comedy', year: 2021 }, ], }) // Query with metadata filters (implicit AND is canonicalized) const results = await store.query({ indexName: 'my-index', queryVector: [0.1, 0.2 /* … */], topK: 10, // Service-side limits may apply (commonly 30) filter: { genre: { $in: ['documentary', 'comedy'] }, year: { $gte: 2020 } }, includeVector: false, // set true to include raw vectors (may trigger a secondary fetch) }) // Clean up resources (closes the underlying HTTP handler) await store.disconnect() ``` ## 建構函式選項 **vectorBucketName** (`string`): 目標 S3 Vectors 向量 bucket 名稱。 **clientConfig** (`S3VectorsClientConfig`): AWS SDK v3 使用者端選項(例如 region、credentials)。 **nonFilterableMetadataKeys** (`string[]`): 不應允許篩選的中繼資料鍵(建立索引時套用)。請將此選項用於 content 等大型文字欄位。 ## 方法 ### `createIndex()` 在設定的向量 bucket 中建立新的向量索引。如果索引已存在,呼叫會驗證 schema,且不執行任何操作(保留現有度量與維度)。 **indexName** (`string`): 邏輯索引名稱。內部會進行正規化:以連字號取代底線,並將名稱轉為小寫。 **dimension** (`number`): 向量維度(必須與嵌入模型相符) **metric** (`'cosine' | 'euclidean'`): 相似度搜尋使用的距離度量。S3 Vectors 不支援 dotproduct。 (Default: `cosine`) ### `upsert()` 新增或取代向量(完整記錄 put)。未提供 `ids` 時會產生 UUID。 **indexName** (`string`): 要 upsert 資料的索引名稱 **vectors** (`number[][]`): 嵌入向量陣列 **metadata** (`Record[]`): 每個向量的中繼資料 **ids** (`string[]`): 選用的向量 ID(未提供時會自動產生) ### `query()` 搜尋最近鄰,並可選擇套用中繼資料篩選。 **indexName** (`string`): 要查詢的索引名稱 **queryVector** (`number[]`): 用於尋找相似向量的查詢向量 **topK** (`number`): 要傳回的結果數量 (Default: `10`) **filter** (`S3VectorsFilter`): 以 JSON 為基礎的中繼資料篩選條件,支援 $and、$or、$eq、$ne、$gt、$gte、$lt、$lte、$in、$nin、$exists。 **includeVector** (`boolean`): 結果是否包含向量 (Default: `false`) > **備註:** 結果包含 `score = 1/(1 + distance)`,因此分數越高越好,同時保留底層的距離排名。 ### `describeIndex()` 傳回索引的相關資訊。 **indexName** (`string`): 要描述的索引名稱。 傳回: ```typescript interface IndexStats { dimension: number count: number // computed via ListVectors pagination (O(n)) metric: 'cosine' | 'euclidean' } ``` ### `deleteIndex()` 刪除索引及其中資料。 **indexName** (`string`): 要刪除的索引。 ### `listIndexes()` 列出設定之向量 bucket 中的所有索引。 傳回:`Promise` ### `updateVector()` 更新索引中特定 ID 的向量或中繼資料。 **indexName** (`string`): 包含該向量的索引。 **id** (`string`): 要更新的 ID。 **update** (`object`): 包含向量及/或中繼資料的更新資料 **update.vector** (`number[]`): 要更新的新向量資料 **update.metadata** (`Record`): 要更新的新中繼資料 ### `deleteVector()` 依 ID 刪除指定向量。 **indexName** (`string`): 包含該向量的索引。 **id** (`string`): 要刪除的 ID。 ### `disconnect()` 關閉底層 AWS SDK HTTP 處理常式,以釋放 socket。 ## 回應型別 查詢結果會以下列格式傳回: ```typescript interface QueryResult { id: string score: number // 1/(1 + distance) metadata: Record vector?: number[] // Only included if includeVector is true } ``` ## 篩選語法 S3 Vectors 僅支援嚴格限定的運算子與值型別子集。Mastra 篩選轉譯器會: - **將隱含 AND 標準化**:`{a:1,b:2}` → `{ $and: [{a:1},{b:2}] }`。 - **將 Date 值正規化**為 epoch 毫秒,供數值比較與陣列元素使用。 - 等值位置(`field: value` 或 `$eq/$ne`)**不允許 Date**。等值必須為 **string | number | boolean**。 - 等值比較會**拒絕** null/undefined。不支援**陣列等值比較**(請使用 `$in`/`$nin`)。 - 頂層邏輯運算子只允許 **`$and`/`$or`**。 - 邏輯運算子必須包含**欄位條件**(不能直接包含運算子)。 **支援的運算子:** - **邏輯:**`$and`、`$or`(非空陣列) - **基本:**`$eq`、`$ne`(string | number | boolean) - **數值:**`$gt`、`$gte`、`$lt`、`$lte`(number 或 `Date` → epoch 毫秒) - **陣列:**`$in`、`$nin`(由 string | number | boolean 組成的非空陣列;`Date` → epoch 毫秒) - **元素:**`$exists`(boolean) **不支援/不允許(會拒絕):**`$not`、`$nor`、`$regex`、`$all`、`$elemMatch`、`$size`、`$text` 等。 **範例:** ```typescript // Implicit AND { genre: { $in: ["documentary", "comedy"] }, year: { $gte: 2020 } } // Explicit logicals and ranges { $and: [ { price: { $gte: 100, $lte: 1000 } }, { $or: [{ stock: { $gt: 0 } }, { preorder: true }] } ] } // Dates in range (converted to epoch ms) { timestamp: { $gt: new Date("2024-01-01T00:00:00Z") } } ``` > **備註:** 如果建立索引時設定 `nonFilterableMetadataKeys`,這些鍵會儲存,但**不能**用於篩選條件。 ## 錯誤處理 此儲存會擲回可攔截的具型別錯誤: ```typescript try { await store.query({ indexName: 'index-name', queryVector: queryVector, }) } catch (error) { if (error instanceof VectorStoreError) { console.log(error.code) // 'connection_failed' | 'invalid_dimension' | etc console.log(error.details) // Additional error context } } ``` ## 環境變數 整合應用程式時通常使用下列環境變數: - `S3_VECTORS_BUCKET_NAME`:你的 S3 **向量 bucket** 名稱(用於填入 `vectorBucketName`)。 - `AWS_REGION`:S3 Vectors bucket 所在的 AWS 區域。 - **AWS 憑證**:透過標準 AWS SDK Provider 鏈(`AWS_ACCESS_KEY_ID`、`AWS_SECRET_ACCESS_KEY`、`AWS_PROFILE` 等)提供。 ## 最佳實務 - 選擇與嵌入模型相符的度量(`cosine` 或 `euclidean`)。不支援 `dotproduct`。 - 讓**可篩選**的中繼資料保持小型且具結構(string/number/boolean)。將大型文字(例如 `content`)儲存為**不可篩選**。 - 巢狀中繼資料使用**點號路徑**,複雜邏輯則明確使用 `$and`/`$or`。 - 避免在熱路徑上呼叫 `describeIndex()`。`count` 會透過分頁的 `ListVectors` 計算(**O(n)**)。 - 只有需要原始向量時才使用 `includeVector: true`。 ## 相關內容 - [中繼資料篩選條件](https://mastra.zisheng.pro/zh-TW/reference/rag/metadata-filters)