Elasticsearch 向量儲存
ElasticSearchVector 類別使用 Elasticsearch 的 dense_vector 欄位類型及 k-NN 搜尋功能提供向量搜尋。
它是 @mastra/elasticsearch 套件的一部分。
安裝安裝 的直接連結
- npm
- pnpm
- Yarn
- Bun
npm install @mastra/elasticsearch@latest
pnpm add @mastra/elasticsearch@latest
yarn add @mastra/elasticsearch@latest
bun add @mastra/elasticsearch@latest
用法用法 的直接連結
import { ElasticSearchVector } from "@mastra/elasticsearch";
const store = new ElasticSearchVector({
id: "elasticsearch-vector",
url: process.env.ELASTICSEARCH_URL,
});
// Create an index
await store.createIndex({
indexName: "my-collection",
dimension: 1536,
});
// Add vectors with metadata
const vectors = [[0.1, 0.2, ...], [0.3, 0.4, ...]];
const metadata = [
{ text: "first document", category: "A" },
{ text: "second document", category: "B" }
];
await store.upsert({
indexName: "my-collection",
vectors,
metadata,
});
// Query similar vectors
const results = await store.query({
indexName: "my-collection",
queryVector: [0.1, 0.2, ...],
topK: 10,
filter: { category: "A" },
});
建構函數選項建構函數選項 的直接連結
id:
string
此向量儲存執行個體的唯一識別碼
url:
string
Elasticsearch 連線 URL(例如 'http://localhost:9200')
方法方法 的直接連結
createIndex()createindex 的直接連結
使用指定的配置建立新索引。
indexName:
string
要建立的索引名稱
dimension:
number
向量維度(必須與你的嵌入模型相符)
metric?:
'cosine' | 'euclidean' | 'dotproduct'
= cosine
相似度搜尋所用的距離度量
upsert()upsert 的直接連結
在索引中新增或更新向量及其中繼資料。
indexName:
string
要插入資料的索引名稱
vectors:
number[][]
嵌入向量陣列
metadata?:
Record<string, any>[]
每個向量的中繼資料
ids?:
string[]
可選的向量 ID(如未提供則自動產生)
query()query 的直接連結
搜尋相似向量,並可選擇使用中繼資料篩選。
indexName:
string
要搜尋的索引名稱
queryVector:
number[]
用於尋找相似向量的查詢向量
topK?:
number
= 10
要傳回的結果數目
filter?:
Record<string, any>
中繼資料篩選條件
includeVector?:
boolean
= false
是否在結果中包含向量資料
describeIndex()describeindex 的直接連結
取得索引的資料。
indexName:
string
要描述的索引名稱
傳回:
interface IndexStats {
dimension: number
count: number
metric: 'cosine' | 'euclidean' | 'dotproduct'
}
deleteIndex()deleteindex 的直接連結
刪除索引及其所有資料。
indexName:
string
要刪除的索引名稱
listIndexes()listindexes 的直接連結
列出所有向量索引。
傳回:Promise<string[]>
updateVector()updatevector 的直接連結
按 ID 或中繼資料篩選條件更新單一向量。必須提供 id 或 filter 其中一項,但不可同時提供兩者。
indexName:
string
包含該向量的索引名稱
id?:
string
要更新的向量 ID(不可與 filter 同時使用)
filter?:
Record<string, any>
用於識別要更新向量的中繼資料篩選條件(不可與 id 同時使用)
update:
object
包含向量及/或中繼資料的更新資料
update.vector?:
number[]
新的向量資料
update.metadata?:
Record<string, any>
新的中繼資料
deleteVector()deletevector 的直接連結
按 ID 刪除單一向量。
indexName:
string
包含該向量的索引名稱
id:
string
要刪除的向量 ID
deleteVectors()deletevectors 的直接連結
按 ID 或中繼資料篩選條件刪除多個向量。必須提供 ids 或 filter 其中一項,但不可同時提供兩者。
indexName:
string
包含要刪除向量的索引名稱
ids?:
string[]
要刪除的向量 ID 陣列(不可與 filter 同時使用)
filter?:
Record<string, any>
用於識別要刪除向量的中繼資料篩選條件(不可與 ids 同時使用)
回應類型回應類型 的直接連結
查詢結果會以以下格式傳回:
interface QueryResult {
id: string
score: number
metadata: Record<string, any>
vector?: number[] // Only included if includeVector is true
}