> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-HK/llms.txt # Upstash 向量儲存 UpstashVector 類別使用 [Upstash Vector](https://upstash.com/vector) 提供向量搜尋。Upstash Vector 是無伺服器向量資料庫服務,支援具備元資料篩選功能的向量相似度搜尋及混合搜尋。 ## 建構函式選項 **url** (`string`): Upstash Vector 資料庫 URL **token** (`string`): Upstash Vector API token。 ## 方法 ### `createIndex()` 注意:Upstash 會自動建立索引,因此此方法不會執行任何操作。 **indexName** (`string`): 要建立的索引名稱 **dimension** (`number`): 向量維度(必須與 embedding 模型相符) **metric** (`'cosine' | 'euclidean' | 'dotproduct'`): 相似度搜尋所用的距離度量 (Default: `cosine`) ### `upsert()` **indexName** (`string`): 要 upsert 至的索引名稱 **vectors** (`number[][]`): embedding 向量陣列 **sparseVectors** (`{ indices: number[], values: number[] }[]`): 用於混合搜尋的稀疏向量陣列。每個稀疏向量的 indices 與 values 陣列必須互相對應。 **metadata** (`Record[]`): 每個向量的元資料 **ids** (`string[]`): 可選的向量 ID(如未提供則自動產生) ### `query()` **indexName** (`string`): 要查詢的索引名稱 **queryVector** (`number[]`): 用來尋找相似向量的查詢向量 **sparseVector** (`{ indices: number[], values: number[] }`): 用於混合搜尋的可選稀疏向量。其 indices 與 values 陣列必須互相對應。 **topK** (`number`): 要傳回的結果數目 (Default: `10`) **filter** (`Record`): 查詢所用的元資料篩選條件 **includeVector** (`boolean`): 結果中是否包含向量 (Default: `false`) **fusionAlgorithm** (`FusionAlgorithm`): 在混合搜尋中用來合併密集與稀疏搜尋結果的演算法(例如 RRF,即倒數排名融合) **queryMode** (`QueryMode`): 搜尋模式:'DENSE' 只進行密集搜尋,'SPARSE' 只進行稀疏搜尋,'HYBRID' 則進行組合搜尋 ### `listIndexes()` 以字串陣列形式傳回索引名稱(命名空間)。 ### `describeIndex()` **indexName** (`string`): 要描述的索引名稱 傳回: ```typescript interface IndexStats { dimension: number count: number metric: 'cosine' | 'euclidean' | 'dotproduct' } ``` ### `deleteIndex()` **indexName** (`string`): 要刪除的索引(命名空間)名稱 ### `updateVector()` **indexName** (`string`): 要更新的索引名稱 **id** (`string`): 要更新項目的 ID **update** (`object`): 包含向量、稀疏向量及/或元資料的更新物件 `update` 物件可包含以下屬性: - `vector`(可選):表示新密集向量的數值陣列。 - `sparseVector`(可選):用於混合索引,並包含 `indices` 及 `values` 陣列的稀疏向量物件。 - `metadata`(可選):元資料的鍵值配對記錄。 ### `deleteVector()` **indexName** (`string`): 要從中刪除項目的索引名稱 **id** (`string`): 要刪除項目的 ID 嘗試按項目 ID 從指定索引中刪除項目。如刪除失敗,則記錄錯誤訊息。 ## 混合向量搜尋 Upstash Vector 支援混合搜尋,結合語義搜尋(密集向量)與關鍵字搜尋(稀疏向量),以提高相關性及準確度。 ### 基本混合搜尋用法 ```typescript import { UpstashVector } from '@mastra/upstash' const vectorStore = new UpstashVector({ id: 'upstash-vector', url: process.env.UPSTASH_VECTOR_URL, token: process.env.UPSTASH_VECTOR_TOKEN, }) // Upsert vectors with both dense and sparse components const denseVectors = [ [0.1, 0.2, 0.3], [0.4, 0.5, 0.6], ] const sparseVectors = [ { indices: [1, 5, 10], values: [0.8, 0.6, 0.4] }, { indices: [2, 6, 11], values: [0.7, 0.5, 0.3] }, ] await vectorStore.upsert({ indexName: 'hybrid-index', vectors: denseVectors, sparseVectors: sparseVectors, metadata: [{ title: 'Document 1' }, { title: 'Document 2' }], }) // Query with hybrid search const results = await vectorStore.query({ indexName: 'hybrid-index', queryVector: [0.1, 0.2, 0.3], sparseVector: { indices: [1, 5], values: [0.9, 0.7] }, topK: 10, }) ``` ### 進階混合搜尋選項 ```typescript import { FusionAlgorithm, QueryMode } from '@upstash/vector' // Query with specific fusion algorithm const fusionResults = await vectorStore.query({ indexName: 'hybrid-index', queryVector: [0.1, 0.2, 0.3], sparseVector: { indices: [1, 5], values: [0.9, 0.7] }, fusionAlgorithm: FusionAlgorithm.RRF, topK: 10, }) // Dense-only search const denseResults = await vectorStore.query({ indexName: 'hybrid-index', queryVector: [0.1, 0.2, 0.3], queryMode: QueryMode.DENSE, topK: 10, }) // Sparse-only search const sparseResults = await vectorStore.query({ indexName: 'hybrid-index', queryVector: [0.1, 0.2, 0.3], // Still required for index structure sparseVector: { indices: [1, 5], values: [0.9, 0.7] }, queryMode: QueryMode.SPARSE, topK: 10, }) ``` ### 更新混合向量 ```typescript // Update both dense and sparse components await vectorStore.updateVector({ indexName: 'hybrid-index', id: 'vector-id', update: { vector: [0.2, 0.3, 0.4], sparseVector: { indices: [2, 7, 12], values: [0.9, 0.8, 0.6] }, metadata: { title: 'Updated Document' }, }, }) ``` ## 回應類型 查詢結果會以下列格式傳回: ```typescript interface QueryResult { id: string score: number metadata: Record vector?: number[] // Only included if includeVector is true } ``` ## 錯誤處理 此儲存會擲出可被捕捉的具型別錯誤: ```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 } } ``` ## 環境變數 必要的環境變數: - `UPSTASH_VECTOR_URL`:你的 Upstash Vector 資料庫 URL - `UPSTASH_VECTOR_TOKEN`:你的 Upstash Vector API token ## 使用範例 ### 使用 fastembed 的本機 embedding Embedding 是 Memory 的 `semanticRecall` 所使用的數值向量,可按語義(而非關鍵字)擷取相關訊息。此設定使用 `@mastra/fastembed` 產生向量 embedding。 安裝 `fastembed` 以開始使用: **npm**: ```bash npm install @mastra/fastembed@latest ``` **pnpm**: ```bash pnpm add @mastra/fastembed@latest ``` **Yarn**: ```bash yarn add @mastra/fastembed@latest ``` **Bun**: ```bash bun add @mastra/fastembed@latest ``` 將以下內容加入你的 Agent: ```typescript import { Memory } from '@mastra/memory' import { Agent } from '@mastra/core/agent' import { UpstashStore, UpstashVector } from '@mastra/upstash' import { fastembed } from '@mastra/fastembed' export const upstashAgent = new Agent({ id: 'upstash-agent', name: 'Upstash Agent', instructions: 'You are an AI agent with the ability to automatically recall memories from previous interactions.', model: 'openai/gpt-5.6-sol', memory: new Memory({ storage: new UpstashStore({ id: 'upstash-agent-storage', url: process.env.UPSTASH_REDIS_REST_URL!, token: process.env.UPSTASH_REDIS_REST_TOKEN!, }), vector: new UpstashVector({ id: 'upstash-agent-vector', url: process.env.UPSTASH_VECTOR_REST_URL!, token: process.env.UPSTASH_VECTOR_REST_TOKEN!, }), embedder: fastembed, options: { lastMessages: 10, semanticRecall: { topK: 3, messageRange: 2, }, }, }), }) ``` ## 相關內容 - [元資料篩選條件](https://mastra.zisheng.pro/zh-HK/reference/rag/metadata-filters)