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.js
More file actions
63 lines (59 loc) · 2.05 KB
/
create-index-basic.js
File metadata and controls
63 lines (59 loc) · 2.05 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
54
55
56
57
58
59
60
61
62
63
// :replace-start: {
// "terms": {
// "process.env.ATLAS_CONNECTION_STRING": "\"<connection-string>\""
// }
// }
// :snippet-start: example
import { MongoClient } from 'mongodb';
export async function createIndexBasic() {
// connect to the Atlas deployment
const uri = process.env.ATLAS_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();
}
}
// :uncomment-start:
//createIndexBasic().catch(console.dir);
// :uncomment-end:
// :snippet-end:
// :replace-end: