-
Notifications
You must be signed in to change notification settings - Fork 324
/
QdrantVectorStore.ts
348 lines (297 loc) · 7.74 KB
/
QdrantVectorStore.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
import type { BaseNode } from "../../Node.js";
import {
VectorStoreBase,
type IEmbedModel,
type VectorStoreNoEmbedModel,
type VectorStoreQuery,
type VectorStoreQueryResult,
} from "./types.js";
import { QdrantClient } from "@qdrant/js-client-rest";
import { metadataDictToNode, nodeToMetadata } from "./utils.js";
type PointStruct = {
id: string;
payload: Record<string, string>;
vector: number[];
};
type QdrantParams = {
collectionName?: string;
client?: QdrantClient;
url?: string;
apiKey?: string;
batchSize?: number;
} & Partial<IEmbedModel>;
type QuerySearchResult = {
id: string;
score: number;
payload: Record<string, unknown>;
vector: number[] | null;
version: number;
};
/**
* Qdrant vector store.
*/
export class QdrantVectorStore
extends VectorStoreBase
implements VectorStoreNoEmbedModel
{
storesText: boolean = true;
batchSize: number;
collectionName: string;
private db: QdrantClient;
private collectionInitialized: boolean = false;
/**
* Creates a new QdrantVectorStore.
* @param collectionName Qdrant collection name
* @param client Qdrant client
* @param url Qdrant URL
* @param apiKey Qdrant API key
* @param batchSize Number of vectors to upload in a single batch
* @param embedModel Embedding model
*/
constructor({
collectionName,
client,
url,
apiKey,
batchSize,
embedModel,
}: QdrantParams) {
super(embedModel);
if (!client && !url) {
if (!url) {
throw new Error("QdrantVectorStore requires url and collectionName");
}
}
if (client) {
this.db = client;
} else {
this.db = new QdrantClient({
url: url,
apiKey: apiKey,
});
}
this.collectionName = collectionName ?? "default";
this.batchSize = batchSize ?? 100;
}
/**
* Returns the Qdrant client.
* @returns Qdrant client
*/
client() {
return this.db;
}
/**
* Creates a collection in Qdrant.
* @param collectionName Qdrant collection name
* @param vectorSize Dimensionality of the vectors
*/
async createCollection(collectionName: string, vectorSize: number) {
await this.db.createCollection(collectionName, {
vectors: {
size: vectorSize,
distance: "Cosine",
},
});
}
/**
* Checks if the collection exists in Qdrant and creates it if not.
* @param collectionName Qdrant collection name
* @returns
*/
async collectionExists(collectionName: string): Promise<boolean> {
try {
await this.db.getCollection(collectionName);
return true;
} catch (e) {
return false;
}
}
/**
* Initializes the collection in Qdrant.
* @param vectorSize Dimensionality of the vectors
*/
async initializeCollection(vectorSize: number) {
const exists = await this.collectionExists(this.collectionName);
if (!exists) {
await this.createCollection(this.collectionName, vectorSize);
}
this.collectionInitialized = true;
}
/**
* Builds a list of points from the given nodes.
* @param nodes
* @returns
*/
async buildPoints(nodes: BaseNode[]): Promise<{
points: PointStruct[];
ids: string[];
}> {
const points: PointStruct[] = [];
const ids = [];
for (let i = 0; i < nodes.length; i++) {
const nodeIds = [];
const vectors = [];
const payloads = [];
for (let j = 0; j < this.batchSize && i < nodes.length; j++, i++) {
const node = nodes[i];
nodeIds.push(node);
vectors.push(node.getEmbedding());
const metadata = nodeToMetadata(node);
payloads.push(metadata);
}
for (let k = 0; k < nodeIds.length; k++) {
const point: PointStruct = {
id: nodeIds[k].id_,
payload: payloads[k],
vector: vectors[k],
};
points.push(point);
}
ids.push(...nodeIds.map((node) => node.id_));
}
return {
points: points,
ids: ids,
};
}
/**
* Adds the given nodes to the vector store.
* @param embeddingResults List of nodes
* @returns List of node IDs
*/
async add(embeddingResults: BaseNode[]): Promise<string[]> {
if (embeddingResults.length > 0 && !this.collectionInitialized) {
await this.initializeCollection(
embeddingResults[0].getEmbedding().length,
);
}
const { points, ids } = await this.buildPoints(embeddingResults);
const batchUpsert = async (points: PointStruct[]) => {
await this.db.upsert(this.collectionName, {
points: points,
});
};
for (let i = 0; i < points.length; i += this.batchSize) {
const chunk = points.slice(i, i + this.batchSize);
await batchUpsert(chunk);
}
return ids;
}
/**
* Deletes the given nodes from the vector store.
* @param refDocId Node ID
*/
async delete(refDocId: string): Promise<void> {
const mustFilter = [
{
key: "doc_id",
match: {
value: refDocId,
},
},
];
await this.db.delete(this.collectionName, {
filter: {
must: mustFilter,
},
});
}
/**
* Converts the result of a query to a VectorStoreQueryResult.
* @param response Query response
* @returns VectorStoreQueryResult
*/
private parseToQueryResult(
response: Array<QuerySearchResult>,
): VectorStoreQueryResult {
const nodes = [];
const similarities = [];
const ids = [];
for (let i = 0; i < response.length; i++) {
const item = response[i];
const payload = item.payload;
const node = metadataDictToNode(payload);
ids.push(item.id);
nodes.push(node);
similarities.push(item.score);
}
return {
nodes: nodes,
similarities: similarities,
ids: ids,
};
}
/**
* Queries the vector store for the closest matching data to the query embeddings.
* @param query The VectorStoreQuery to be used
* @param options Required by VectorStore interface. Currently ignored.
* @returns Zero or more Document instances with data from the vector store.
*/
async query(
query: VectorStoreQuery,
options?: any,
): Promise<VectorStoreQueryResult> {
const qdrantFilters = options?.qdrant_filters;
let queryFilters;
if (!query.queryEmbedding) {
throw new Error("No query embedding provided");
}
if (qdrantFilters) {
queryFilters = qdrantFilters;
} else {
queryFilters = await this.buildQueryFilter(query);
}
const result = (await this.db.search(this.collectionName, {
vector: query.queryEmbedding,
limit: query.similarityTopK,
...(queryFilters && { filter: queryFilters }),
})) as Array<QuerySearchResult>;
return this.parseToQueryResult(result);
}
/**
* Qdrant filter builder
* @param query The VectorStoreQuery to be used
*/
private async buildQueryFilter(query: VectorStoreQuery) {
if (!query.docIds && !query.queryStr && !query.filters) {
return null;
}
const mustConditions = [];
if (query.docIds) {
mustConditions.push({
key: "doc_id",
match: {
any: query.docIds,
},
});
}
if (!query.filters) {
return {
must: mustConditions,
};
}
const metadataFilters = query.filters.filters;
for (let i = 0; i < metadataFilters.length; i++) {
const filter = metadataFilters[i];
if (typeof filter.key === "number") {
mustConditions.push({
key: filter.key,
match: {
gt: filter.value,
lt: filter.value,
},
});
} else {
mustConditions.push({
key: filter.key,
match: {
value: filter.value,
},
});
}
}
return {
must: mustConditions,
};
}
}