-
Notifications
You must be signed in to change notification settings - Fork 306
/
MongoDBAtlasVectorStore.ts
167 lines (147 loc) · 4.36 KB
/
MongoDBAtlasVectorStore.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
import { getEnv } from "@llamaindex/env";
import type { BulkWriteOptions, Collection } from "mongodb";
import { MongoClient } from "mongodb";
import type { BaseNode } from "../../Node.js";
import { MetadataMode } from "../../Node.js";
import type {
MetadataFilters,
VectorStore,
VectorStoreQuery,
VectorStoreQueryResult,
} from "./types.js";
import { metadataDictToNode, nodeToMetadata } from "./utils.js";
// Utility function to convert metadata filters to MongoDB filter
function toMongoDBFilter(
standardFilters: MetadataFilters,
): Record<string, any> {
const filters: Record<string, any> = {};
for (const filter of standardFilters?.filters ?? []) {
filters[filter.key] = filter.value;
}
return filters;
}
// MongoDB Atlas Vector Store class implementing VectorStore
export class MongoDBAtlasVectorSearch implements VectorStore {
storesText: boolean = true;
flatMetadata: boolean = true;
mongodbClient: MongoClient;
indexName: string;
embeddingKey: string;
idKey: string;
textKey: string;
metadataKey: string;
insertOptions?: BulkWriteOptions;
private collection: Collection;
constructor(
init: Partial<MongoDBAtlasVectorSearch> & {
dbName: string;
collectionName: string;
},
) {
if (init.mongodbClient) {
this.mongodbClient = init.mongodbClient;
} else {
const mongoUri = getEnv("MONGODB_URI");
if (!mongoUri) {
throw new Error(
"Must specify MONGODB_URI via env variable if not directly passing in client.",
);
}
this.mongodbClient = new MongoClient(mongoUri);
}
this.collection = this.mongodbClient
.db(init.dbName ?? "default_db")
.collection(init.collectionName ?? "default_collection");
this.indexName = init.indexName ?? "default";
this.embeddingKey = init.embeddingKey ?? "embedding";
this.idKey = init.idKey ?? "id";
this.textKey = init.textKey ?? "text";
this.metadataKey = init.metadataKey ?? "metadata";
this.insertOptions = init.insertOptions;
}
async add(nodes: BaseNode[]): Promise<string[]> {
if (!nodes || nodes.length === 0) {
return [];
}
const dataToInsert = nodes.map((node) => {
const metadata = nodeToMetadata(
node,
true,
this.textKey,
this.flatMetadata,
);
return {
[this.idKey]: node.id_,
[this.embeddingKey]: node.getEmbedding(),
[this.textKey]: node.getContent(MetadataMode.NONE) || "",
[this.metadataKey]: metadata,
};
});
console.debug("Inserting data into MongoDB: ", dataToInsert);
const insertResult = await this.collection.insertMany(
dataToInsert,
this.insertOptions,
);
console.debug("Result of insert: ", insertResult);
return nodes.map((node) => node.id_);
}
async delete(refDocId: string, deleteOptions?: any): Promise<void> {
await this.collection.deleteOne(
{
[`${this.metadataKey}.ref_doc_id`]: refDocId,
},
deleteOptions,
);
}
get client(): any {
return this.mongodbClient;
}
async query(
query: VectorStoreQuery,
options?: any,
): Promise<VectorStoreQueryResult> {
const params: any = {
queryVector: query.queryEmbedding,
path: this.embeddingKey,
numCandidates: query.similarityTopK * 10,
limit: query.similarityTopK,
index: this.indexName,
};
if (query.filters) {
params.filter = toMongoDBFilter(query.filters);
}
const queryField = { $vectorSearch: params };
const pipeline = [
queryField,
{
$project: {
score: { $meta: "vectorSearchScore" },
[this.embeddingKey]: 0,
},
},
];
console.debug("Running query pipeline: ", pipeline);
const cursor = await this.collection.aggregate(pipeline);
const nodes: BaseNode[] = [];
const ids: string[] = [];
const similarities: number[] = [];
for await (const res of await cursor) {
const text = res[this.textKey];
const score = res.score;
const id = res[this.idKey];
const metadata = res[this.metadataKey];
const node = metadataDictToNode(metadata);
node.setContent(text);
ids.push(id);
nodes.push(node);
similarities.push(score);
}
const result = {
nodes,
similarities,
ids,
};
console.debug("Result of query (ids):", ids);
return result;
}
}