-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
elasticsearch.ts
374 lines (342 loc) Β· 12 KB
/
elasticsearch.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
import * as uuid from "uuid";
import { Client, estypes } from "@elastic/elasticsearch";
import type { EmbeddingsInterface } from "@langchain/core/embeddings";
import { VectorStore } from "@langchain/core/vectorstores";
import { Document } from "@langchain/core/documents";
/**
* Type representing the k-nearest neighbors (k-NN) engine used in
* Elasticsearch.
*/
type ElasticKnnEngine = "hnsw";
/**
* Type representing the similarity measure used in Elasticsearch.
*/
type ElasticSimilarity = "l2_norm" | "dot_product" | "cosine";
/**
* Interface defining the options for vector search in Elasticsearch.
*/
interface VectorSearchOptions {
readonly engine?: ElasticKnnEngine;
readonly similarity?: ElasticSimilarity;
readonly m?: number;
readonly efConstruction?: number;
readonly candidates?: number;
}
/**
* Interface defining the arguments required to create an Elasticsearch
* client.
*/
export interface ElasticClientArgs {
readonly client: Client;
readonly indexName?: string;
readonly vectorSearchOptions?: VectorSearchOptions;
}
/**
* Type representing a filter object in Elasticsearch.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type ElasticFilter = object | { field: string; operator: string; value: any }[];
/**
* Class for interacting with an Elasticsearch database. It extends the
* VectorStore base class and provides methods for adding documents and
* vectors to the Elasticsearch database, performing similarity searches,
* deleting documents, and more.
*/
export class ElasticVectorSearch extends VectorStore {
declare FilterType: ElasticFilter;
private readonly client: Client;
private readonly indexName: string;
private readonly engine: ElasticKnnEngine;
private readonly similarity: ElasticSimilarity;
private readonly efConstruction: number;
private readonly m: number;
private readonly candidates: number;
_vectorstoreType(): string {
return "elasticsearch";
}
constructor(embeddings: EmbeddingsInterface, args: ElasticClientArgs) {
super(embeddings, args);
this.engine = args.vectorSearchOptions?.engine ?? "hnsw";
this.similarity = args.vectorSearchOptions?.similarity ?? "l2_norm";
this.m = args.vectorSearchOptions?.m ?? 16;
this.efConstruction = args.vectorSearchOptions?.efConstruction ?? 100;
this.candidates = args.vectorSearchOptions?.candidates ?? 200;
this.client = args.client.child({
headers: { "user-agent": "langchain-js-vs/0.0.1" },
});
this.indexName = args.indexName ?? "documents";
}
/**
* Method to add documents to the Elasticsearch database. It first
* converts the documents to vectors using the embeddings, then adds the
* vectors to the database.
* @param documents The documents to add to the database.
* @param options Optional parameter that can contain the IDs for the documents.
* @returns A promise that resolves with the IDs of the added documents.
*/
async addDocuments(documents: Document[], options?: { ids?: string[] }) {
const texts = documents.map(({ pageContent }) => pageContent);
return this.addVectors(
await this.embeddings.embedDocuments(texts),
documents,
options
);
}
/**
* Method to add vectors to the Elasticsearch database. It ensures the
* index exists, then adds the vectors and their corresponding documents
* to the database.
* @param vectors The vectors to add to the database.
* @param documents The documents corresponding to the vectors.
* @param options Optional parameter that can contain the IDs for the documents.
* @returns A promise that resolves with the IDs of the added documents.
*/
async addVectors(
vectors: number[][],
documents: Document[],
options?: { ids?: string[] }
) {
await this.ensureIndexExists(
vectors[0].length,
this.engine,
this.similarity,
this.efConstruction,
this.m
);
const documentIds =
options?.ids ?? Array.from({ length: vectors.length }, () => uuid.v4());
const operations = vectors.flatMap((embedding, idx) => [
{
index: {
_id: documentIds[idx],
_index: this.indexName,
},
},
{
embedding,
metadata: documents[idx].metadata,
text: documents[idx].pageContent,
},
]);
const results = await this.client.bulk({ refresh: true, operations });
if (results.errors) {
const reasons = results.items.map(
(result) => result.index?.error?.reason
);
throw new Error(`Failed to insert documents:\n${reasons.join("\n")}`);
}
return documentIds;
}
/**
* Method to perform a similarity search in the Elasticsearch database
* using a vector. It returns the k most similar documents along with
* their similarity scores.
* @param query The query vector.
* @param k The number of most similar documents to return.
* @param filter Optional filter to apply to the search.
* @returns A promise that resolves with an array of tuples, where each tuple contains a Document and its similarity score.
*/
async similaritySearchVectorWithScore(
query: number[],
k: number,
filter?: ElasticFilter
): Promise<[Document, number][]> {
const result = await this.client.search({
index: this.indexName,
size: k,
knn: {
field: "embedding",
query_vector: query,
filter: { bool: this.buildMetadataTerms(filter) },
k,
num_candidates: this.candidates,
},
});
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return result.hits.hits.map((hit: any) => [
new Document({
pageContent: hit._source.text,
metadata: hit._source.metadata,
}),
hit._score,
]);
}
/**
* Method to delete documents from the Elasticsearch database.
* @param params Object containing the IDs of the documents to delete.
* @returns A promise that resolves when the deletion is complete.
*/
async delete(params: { ids: string[] }): Promise<void> {
const operations = params.ids.map((id) => ({
delete: {
_id: id,
_index: this.indexName,
},
}));
if (operations.length > 0)
await this.client.bulk({ refresh: true, operations });
}
/**
* Static method to create an ElasticVectorSearch instance from texts. It
* creates Document instances from the texts and their corresponding
* metadata, then calls the fromDocuments method to create the
* ElasticVectorSearch instance.
* @param texts The texts to create the ElasticVectorSearch instance from.
* @param metadatas The metadata corresponding to the texts.
* @param embeddings The embeddings to use for the documents.
* @param args The arguments to create the Elasticsearch client.
* @returns A promise that resolves with the created ElasticVectorSearch instance.
*/
static fromTexts(
texts: string[],
metadatas: object[] | object,
embeddings: EmbeddingsInterface,
args: ElasticClientArgs
): Promise<ElasticVectorSearch> {
const documents = texts.map((text, idx) => {
const metadata = Array.isArray(metadatas) ? metadatas[idx] : metadatas;
return new Document({ pageContent: text, metadata });
});
return ElasticVectorSearch.fromDocuments(documents, embeddings, args);
}
/**
* Static method to create an ElasticVectorSearch instance from Document
* instances. It adds the documents to the Elasticsearch database, then
* returns the ElasticVectorSearch instance.
* @param docs The Document instances to create the ElasticVectorSearch instance from.
* @param embeddings The embeddings to use for the documents.
* @param dbConfig The configuration for the Elasticsearch database.
* @returns A promise that resolves with the created ElasticVectorSearch instance.
*/
static async fromDocuments(
docs: Document[],
embeddings: EmbeddingsInterface,
dbConfig: ElasticClientArgs
): Promise<ElasticVectorSearch> {
const store = new ElasticVectorSearch(embeddings, dbConfig);
await store.addDocuments(docs).then(() => store);
return store;
}
/**
* Static method to create an ElasticVectorSearch instance from an
* existing index in the Elasticsearch database. It checks if the index
* exists, then returns the ElasticVectorSearch instance if it does.
* @param embeddings The embeddings to use for the documents.
* @param dbConfig The configuration for the Elasticsearch database.
* @returns A promise that resolves with the created ElasticVectorSearch instance if the index exists, otherwise it throws an error.
*/
static async fromExistingIndex(
embeddings: EmbeddingsInterface,
dbConfig: ElasticClientArgs
): Promise<ElasticVectorSearch> {
const store = new ElasticVectorSearch(embeddings, dbConfig);
const exists = await store.doesIndexExist();
if (exists) {
return store;
}
throw new Error(`The index ${store.indexName} does not exist.`);
}
private async ensureIndexExists(
dimension: number,
engine = "hnsw",
similarity = "l2_norm",
efConstruction = 100,
m = 16
): Promise<void> {
const request: estypes.IndicesCreateRequest = {
index: this.indexName,
mappings: {
dynamic_templates: [
{
// map all metadata properties to be keyword except loc
metadata_except_loc: {
match_mapping_type: "*",
match: "metadata.*",
unmatch: "metadata.loc",
mapping: { type: "keyword" },
},
},
],
properties: {
text: { type: "text" },
metadata: {
type: "object",
properties: {
loc: { type: "object" }, // explicitly define loc as an object
},
},
embedding: {
type: "dense_vector",
dims: dimension,
index: true,
similarity,
index_options: {
type: engine,
m,
ef_construction: efConstruction,
},
},
},
},
};
const indexExists = await this.doesIndexExist();
if (indexExists) return;
await this.client.indices.create(request);
}
private buildMetadataTerms(filter?: ElasticFilter): {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
must: { [operator: string]: { [field: string]: any } }[];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
must_not: { [operator: string]: { [field: string]: any } }[];
} {
if (filter == null) return { must: [], must_not: [] };
const filters = Array.isArray(filter)
? filter
: Object.entries(filter).map(([key, value]) => ({
operator: "term",
field: key,
value,
}));
const must = [];
const must_not = [];
for (const condition of filters) {
const metadataField = `metadata.${condition.field}`;
if (condition.operator === "exists") {
must.push({
[condition.operator]: {
field: metadataField,
},
});
} else if (condition.operator === "exclude") {
must_not.push({
terms: {
[metadataField]: condition.value,
},
});
} else {
must.push({
[condition.operator]: {
[metadataField]: condition.value,
},
});
}
}
return { must, must_not };
}
/**
* Method to check if an index exists in the Elasticsearch database.
* @returns A promise that resolves with a boolean indicating whether the index exists.
*/
async doesIndexExist(): Promise<boolean> {
return await this.client.indices.exists({ index: this.indexName });
}
/**
* Method to delete an index from the Elasticsearch database if it exists.
* @returns A promise that resolves when the deletion is complete.
*/
async deleteIfExists(): Promise<void> {
const indexExists = await this.doesIndexExist();
if (!indexExists) return;
await this.client.indices.delete({ index: this.indexName });
}
}