跳至主要內容

Elasticsearch 向量儲存

ElasticSearchVector 類別使用 Elasticsearchdense_vector 欄位型別與 k-NN 搜尋功能提供向量搜尋。 它是 @mastra/elasticsearch 套件的一部分。

安裝
「安裝」的直接連結

npm install @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 或中繼資料篩選條件更新單一向量。必須提供 idfilter 其中一項,但不能同時提供兩者。

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 或中繼資料篩選條件刪除多個向量。必須提供 idsfilter 其中一項,但不能同時提供兩者。

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
}