forked from mongodb/docs-code-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreate-index-basic.snippet.example.js
More file actions
53 lines (49 loc) · 1.82 KB
/
create-index-basic.snippet.example.js
File metadata and controls
53 lines (49 loc) · 1.82 KB
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
import { MongoClient } from 'mongodb';
export async function createIndexBasic() {
// connect to the Atlas deployment
const uri = "<connection-string>";
const client = new MongoClient(uri);
try {
const database = client.db("sample_mflix");
const collection = database.collection("embedded_movies");
// define your Atlas Vector Search index
const indexName = "vector_index";
const index = {
name: indexName,
type: "vectorSearch",
definition: {
"fields": [
{
"type": "vector",
"numDimensions": 1536,
"path": "plot_embedding",
"similarity": "euclidean"
}
]
}
}
// create the index
const result = await collection.createSearchIndex(index);
console.log(`Successfully created index named "${result}"`);
// wait for the index to be ready to query
console.log("Polling to confirm the index has finished building and can be queried.")
console.log("NOTE: This may take up to a minute.")
let isQueryable = false;
while (!isQueryable) {
const cursor = collection.listSearchIndexes();
for await (const index of cursor) {
if (index.name === indexName) {
if (index.queryable) {
console.log(`The search index "${indexName}" is queryable.`);
isQueryable = true;
} else {
await new Promise(resolve => setTimeout(resolve, 5000));
}
}
}
}
} finally {
await client.close();
}
}
createIndexBasic().catch(console.dir);