> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-HK/llms.txt # Amazon S3 向量儲存 `S3Vectors` 類別使用 [Amazon S3 Vectors(預覽版)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/s3-vectors.html)提供向量搜尋功能。它會將向量儲存在**向量儲存貯體**中,並在**向量索引**內執行相似度搜尋,同時支援以 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 向量儲存貯體名稱。 **clientConfig** (`S3VectorsClientConfig`): AWS SDK v3 用戶端選項(例如 region、credentials)。 **nonFilterableMetadataKeys** (`string[]`): 不應用於篩選的元資料鍵(建立索引時套用)。適合用於 content 等大型文字欄位。 ## 方法 ### `createIndex()` 在已設定的向量儲存貯體中建立新的向量索引。如果索引已存在,此呼叫會驗證結構描述而不執行任何操作(保留現有的度量及維度)。 **indexName** (`string`): 邏輯索引名稱。系統會在內部將名稱標準化:以連字號取代底線,並將名稱轉為小寫。 **dimension** (`number`): 向量維度(必須與嵌入模型相符) **metric** (`'cosine' | 'euclidean'`): 相似度搜尋所用的距離度量。S3 Vectors 不支援 dotproduct。 (Default: `cosine`) ### `upsert()` 新增或取代向量(寫入完整記錄)。如果未提供 `ids`,系統會產生 UUID。 **indexName** (`string`): 要寫入或更新資料的索引名稱 **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()` 列出已設定向量儲存貯體中的所有索引。 傳回:`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 處理常式以釋放通訊端。 ## 回應類型 查詢結果會以下列格式傳回: ```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 毫秒,以用於數值比較及陣列元素。 - **不允許在等值位置使用 Date**(`field: value` 或 `$eq/$ne`)。等值必須為 **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 **向量儲存貯體**名稱(用於填入 `vectorBucketName`)。 - `AWS_REGION`:S3 Vectors 儲存貯體所在的 AWS 區域。 - **AWS 憑證**:透過標準 AWS SDK 供應者鏈(`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`。 ## 相關內容 - [Metadata 篩選器](https://mastra.zisheng.pro/zh-HK/reference/rag/metadata-filters)