Docs Menu
Docs Home
/
MongoDB Atlas
/

How to Index Fields for Vector Search

On this page

  • Considerations
  • Supported Clients
  • Syntax
  • Atlas Vector Search Index Fields
  • About the vector Type
  • About the filter Type
  • Create an Atlas Vector Search Index
  • Prerequisites
  • Required Access
  • Index Limitations
  • Procedure
  • View an Atlas Vector Search Index
  • Required Access
  • Procedure
  • Edit an Atlas Vector Search Index
  • Required Access
  • Procedure
  • Delete an Atlas Vector Search Index
  • Required Access
  • Procedure
  • Index Status

You can use the vectorSearch type to index fields for running $vectorSearch queries. You can define the index for the vector embeddings that you want to query and the boolean, date, objectId, numeric, string, or UUID values that you want to use to pre-filter your data. Filtering your data is useful to narrow the scope of your semantic search and ensure that certain vector embeddings are not considered for comparison, such as in a multi-tenant environment.

You can use the Atlas UI, Atlas Administration API, Atlas CLI, mongosh, or a supported MongoDB Driver to create your Atlas Vector Search index.

Note

You can't use the deprecated knnBeta operator to query fields indexed using the vectorSearch type index definition.

In a vectorSearch type index definition, you can index arrays with only a single element. You can't index fields inside arrays of documents or fields inside arrays of objects. You can index fields inside documents using the dot notation.

Before indexing your embeddings, we recommend converting your embeddings to BSON BinData vector subtype float32, int1, or int8 vectors for efficient storage in your Atlas cluster. To learn more, see how to convert your embeddings to BSON vectors.

Note

Atlas Vector Search support for the following is available as a Preview feature:

  • Ingestion of BSON BinData vector subtype int1.

  • Automatic scalar quantization.

  • Automatic binary quantization.

You can create and manage Atlas Vector Search indexes through the Atlas UI, mongosh, Atlas CLI, Atlas Administration API, and the following MongoDB Drivers:

MongoDB Driver
Version

1.28.0 or higher

3.11.0 or higher

3.1.0 or higher

1.16.0 or higher

5.2.0 or higher

5.2.0 or higher

6.6.0 or higher

1.20.0 or higher

4.7 or higher

3.1.0 or higher

5.2.0 or higher

The following syntax defines the vectorSearch index type:

1{
2 "fields":[
3 {
4 "type": "vector",
5 "path": "<field-to-index>",
6 "numDimensions": <number-of-dimensions>,
7 "similarity": "euclidean | cosine | dotProduct",
8 "quantization": "none | scalar | binary"
9 },
10 {
11 "type": "filter",
12 "path": "<field-to-index>"
13 },
14 ...
15 ]
16}

The Atlas Vector Search index definition takes the following fields:

Option
Type
Necessity
Purpose

fields

array of documents

Required

Vector and filter fields to index, one per document. At least one document must contain the field definition for the vector field. You can optionally also index boolean, date, number, objectId, string, and UUID fields, one per document, for pre-filtering the data.

fields.type

string

Required

Field type to use to index fields for $vectorSearch. You can specify one of the following values:

  • vector - for fields that contain vector embeddings.

  • filter - for fields that contain boolean, date, objectId, numeric, string, or UUID values.

fields.path

string

Required

Name of the field to index. For nested fields, use dot notation to specify path to embedded fields.

You cannot index field names with two consecutive dots or field names ending with dots. For example, Atlas Vector Search doesn't support indexing the following field names: foo..bar or foo_bar..

fields.numDimensions

int

Required

Number of vector dimensions that Atlas Vector Search enforces at index-time and query-time. You must specify a value less than or equal to 4096. For indexing BinData or quantized vectors, value must be one of the following:

  • 1 to 4096 for int8 vectors for ingestion.

  • Multiple of 8 for int1 vectors for ingestion.

  • 1 to 4096 for binData(float32) and array(float32) vectors for automatic scalar quantization.

  • Multiple of 8 for binData(float32) and array(float32) vectors for automatic binary quantization.

You can set this field only for vector type fields.

fields.similarity

string

Required

Vector similarity function to use to search for top K-nearest neighbors. You can set this field only for vector type fields. Value can be one of the following:

  • euclidean - measures the distance between ends of vectors.

  • cosine - measures similarity based on the angle between vectors.

  • dotProduct - measures similarity like cosine, but takes into account the magnitude of the vector.

To learn more, see About the Similarity Functions.

fields.quantization

string

Optional

Type of automatic vector quantization for your vectors. You can specify the type of quantization to apply on your vectors. Use this setting only if your embeddings are float or double vectors. Value can be one of the following:

  • none - Indicates no automatic quantization for the vector embeddings. Use this setting if you have pre-quantized vectors for ingestion. If omitted, this is the default value.

  • scalar - Indicates scalar quantization, which transforms values to 1 byte integers.

  • binary - Indicates binary quantization, which transforms values to a single bit. To use this quantization, numDimensions must be a multiple of 8.

If precision is critical, select none or scalar instead of binary.

To learn more, see Vector Quantization.

Your index definition's vector field must contain an array of numbers of one of the following types:

  • BSON double

  • BSON BinData vector subtype float32

  • BSON BinData vector subtype int1

  • BSON BinData vector subtype int8

Note

To learn more about generating BSON BinData vector subtype float32 or vector subtype int1 or int8 vectors for your data, see How to Ingest Pre-Quantized Vectors.

Atlas Vector Search support for the following is available as a Preview feature:

  • Ingestion of BSON BinData vector subtype int1.

  • Automatic scalar quantization.

  • Automatic binary quantization.

You must index the vector field as the vector type inside the fields array.

The following syntax defines the vector field type:

1{
2 "fields":[
3 {
4 "type": "vector",
5 "path": <field-to-index>,
6 "numDimensions": <number-of-dimensions>,
7 "similarity": "euclidean | cosine | dotProduct",
8 "quantization": "none | scalar | binary"
9 },
10 ...
11 ]
12}

Atlas Vector Search supports the following similarity functions:

  • euclidean - measures the distance between ends of vectors. This value allows you to measure similarity based on varying dimensions. To learn more, see Euclidean.

  • cosine - measures similarity based on the angle between vectors. This value allows you to measure similarity that isn't scaled by magnitude. You can't use zero magnitude vectors with cosine. To measure cosine similarity, we recommend that you normalize your vectors and use dotProduct instead.

  • dotProduct - measures similarity like cosine, but takes into account the magnitude of the vector. If you normalize the magnitude, cosine and dotProduct are almost identical in measuring similarity.

    To use dotProduct, you must normalize the vector to unit length at index-time and query-time.

The following table shows the similarity functions for the various types:

Vector Embeddings Type
euclidean
consine
dotProduct

binData(int1)

√

binData(int8)

√

√

√

binData(float32)

√

√

√

array(float32)

√

√

√

For vector ingestion.

For automatic scalar or binary quantization.

For best performance, check your embedding model to determine which similarity function aligns with your embedding model's training process. If you don't have any guidance, start with dotProduct. Setting fields.similarity to the dotProduct value allows you to efficiently measure similarity based on both angle and magnitude. dotProduct consumes less computational resources than cosine and is efficient when vectors are of unit length. However, if your vectors aren't normalized, evaluate the similarity scores in the results of a sample query for euclidean distance and cosine similarity to determine which corresponds to reasonable results.

You can optionally index boolean, date, number, objectId, string, and UUID fields to pre-filter your data. Filtering your data is useful to narrow the scope of your semantic search and ensure that not all vectors are considered for comparison. It reduces the number of documents against which to run similarity comparisons, which can decrease query latency and increase the accuracy of search results.

You must index the fields that you want to filter by using the filter type inside the fields array.

The following syntax defines the filter field type:

1{
2 "fields":[
3 {
4 "type": "vector",
5 ...
6 },
7 {
8 "type": "filter",
9 "path": "<field-to-index>"
10 },
11 ...
12 ]
13}

Note

Pre-filtering your data doesn't affect the score that Atlas Vector Search returns using $vectorSearchScore for $vectorSearch queries.

An Atlas Search index is a data structure that categorizes data in an easily searchable format. It is a mapping between terms and the documents that contain those terms. Atlas Search indexes enable faster retrieval of documents using certain identifiers. You must configure an Atlas Search index to query data in your Atlas cluster using Atlas Search.

You can create an Atlas Search index on a single field or on multiple fields. We recommend that you index the fields that you regularly use to sort or filter your data in order to quickly retrieve the documents that contain the relevant data at query-time.

You can create an Atlas Vector Search index for all collections that contain vector embeddings less than or equal to 4096 dimensions in length for any kind of data along with other data on your Atlas cluster through the Atlas UI, Atlas Administration API, Atlas CLI, mongosh, or a supported MongoDB Driver.

To create an Atlas Vector Search index, you must have an Atlas cluster with the following prerequisites:

  • MongoDB version 6.0.11, 7.0.2, or higher

  • A collection for which to create the Atlas Vector Search index

Note

You can use the mongosh command or driver helper methods to create Atlas Search indexes on all Atlas cluster tiers. For a list of supported driver versions, see Supported Clients.

You need the Project Data Access Admin or higher role to create and manage Atlas Vector Search indexes.

You cannot create more than:

  • 3 indexes on M0 clusters.

  • 5 indexes on M2 clusters.

  • 10 indexes on M5 clusters.

We recommend that you create no more than 2,500 search indexes on a single M10+ cluster.


➤ Use the Select your language drop-down menu to select the client you want to use to create your index.


Note

The procedure includes index definition examples for the embedded_movies collection in the sample_mflix database. If you load the sample data on your cluster and create the example Atlas Search indexes for this collection, you can run the sample $vectorSearch queries against this collection. To learn more about the sample queries that you can run, see $vectorSearch Examples.

To create an Atlas Vector Search index for a collection using the Atlas Administration API, send a POST request to the Atlas Search indexes endpoint with the required parameters.

1curl --user "{PUBLIC-KEY}:{PRIVATE-KEY}" --digest \
2--header "Accept: application/json" \
3--header "Content-Type: application/json" \
4--include \
5--request POST "https://mongodb.prakticum-team.ru/proxy/cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes" \
6--data '
7 {
8 "database": "<name-of-database>",
9 "collectionName": "<name-of-collection>",
10 "type": "vectorSearch",
11 "name": "<index-name>",
12 "definition": {
13 "fields":[
14 {
15 "type": "vector",
16 "path": <field-to-index>,
17 "numDimensions": <number-of-dimensions>,
18 "similarity": "euclidean | cosine | dotProduct"
19 },
20 {
21 "type": "filter",
22 "path": "<field-to-index>"
23 },
24 ...
25 }
26 ]
27 }'

To learn more about the syntax and parameters for the endpoint, see Create One Atlas Search Index.

Example

The following index definition indexes the plot_embedding field as the vector type and the genres and year fields as the filter type in an Atlas Vector Search index. The plot_embedding field contains embeddings created using OpenAI's text-embedding-ada-002 embeddings model. The index definition specifies 1536 vector dimensions and measures similarity using dotProduct function.

The following index definition indexes only the vector embeddings field for performing vector search.

1curl --user "{PUBLIC-KEY}:{PRIVATE-KEY}" --digest \
2--header "Accept: application/json" \
3--header "Content-Type: application/json" \
4--include \
5--request POST "https://mongodb.prakticum-team.ru/proxy/cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes" \
6--data '
7 {
8 "database": "sample_mflix",
9 "collectionName": "embedded_movies",
10 "type": "vectorSearch",
11 "name": "vector_index",
12 "definition: {
13 "fields":[
14 {
15 "type": "vector",
16 "path": "plot_embedding",
17 "numDimensions": 1536,
18 "similarity": "dotProduct"
19 }
20 ]
21 }
22 }'

This index definition indexes the following fields:

  • A string field (genres) and a numeric field (year) for pre-filtering the data.

  • The vector embeddings field (plot_embedding) for performing vector search against pre-filtered data.

1curl --user "{PUBLIC-KEY}:{PRIVATE-KEY}" --digest \
2--header "Accept: application/json" \
3--header "Content-Type: application/json" \
4--include \
5--request POST "https://mongodb.prakticum-team.ru/proxy/cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes" \
6--data '
7 {
8 "database": "sample_mflix",
9 "collectionName": "embedded_movies",
10 "type": "vectorSearch",
11 "name": "vector_index",
12 "definition: {
13 "fields":[
14 {
15 "type": "vector",
16 "path": "plot_embedding",
17 "numDimensions": 1536,
18 "similarity": "dotProduct"
19 },
20 {
21 "type": "filter",
22 "path": "genres"
23 },
24 {
25 "type": "filter",
26 "path": "year"
27 }
28 ]
29 }
30 }'

To create an Atlas Vector Search index for a collection using the Atlas CLI v1.14.3 or later, perform the following steps:

1

Your index definition should resemble the following format:

1{
2 "database": "<name-of-database>",
3 "collectionName": "<name-of-collection>",
4 "type": "vectorSearch",
5 "name": "<index-name>",
6 "fields":[
7 {
8 "type": "vector",
9 "path": "<field-to-index>",
10 "numDimensions": <number-of-dimensions>,
11 "similarity": "euclidean | cosine | dotProduct"
12 },
13 {
14 "type": "filter",
15 "path": "<field-to-index>"
16 },
17 ...
18 ]
19}

Example

Create a file named vector-index.json.

2

<name-of-database>

Database that contains the collection for which you want to create the index.

<name-of-collection>

Collection for which you want to create the index.

<index-name>

Name of your index. If you omit the index name, Atlas Vector Search names the index vector_index.

<number-of-dimensions>

Number of vector dimensions that Atlas Vector Search enforces at index-time and query-time.

<field-to-index>

Vector and filter fields to index.

Example

Copy and paste the following index definition into the vector-index.json file. The following index definition indexes the plot_embedding field as the vector type and the genres and year fields as the filter type in an Atlas Vector Search index. The plot_embedding field contains embeddings created using OpenAI's text-embedding-ada-002 embeddings model. The index definition specifies 1536 vector dimensions and measures similarity using dotProduct function.

The following index definition indexes only the vector embeddings field for performing vector search.

1{
2 "database": "sample_mflix",
3 "collectionName": "embedded_movies",
4 "type": "vectorSearch",
5 "name": "vector_index",
6 "fields": [
7 {
8 "type": "vector",
9 "path": "plot_embedding",
10 "numDimensions": 1536,
11 "similarity": "dotProduct"
12 }
13 ]
14}

This index definition indexes the following fields:

  • A string field (genres) and a numeric field (year) for pre-filtering the data.

  • The vector embeddings field (plot_embedding) for performing vector search against pre-filtered data.

1{
2 "database": "sample_mflix",
3 "collectionName": "embedded_movies",
4 "type": "vectorSearch",
5 "name": "vector_index",
6 "fields":[
7 {
8 "type": "vector",
9 "path": "plot_embedding",
10 "numDimensions": 1536,
11 "similarity": "dotProduct"
12 },
13 {
14 "type": "filter",
15 "path": "genres"
16 },
17 {
18 "type": "filter",
19 "path": "year"
20 }
21 ]
22}
3
atlas clusters search indexes create --clusterName [cluster_name] --file [vector_index].json

In the command, replace the following placeholder values:

  • cluster_name is the name of the Atlas cluster that contains the collection for which you want to create the index.

  • vector_index is the name of the JSON file that contains the index definition for the Atlas Vector Search index.

Example

atlas clusters search indexes create --clusterName [cluster_name] --file vector-index.json

To learn more about the command syntax and parameters, see the Atlas CLI documentation for the atlas clusters search indexes create command.

1
  1. If it's not already displayed, select the organization that contains your desired project from the Organizations menu in the navigation bar.

  2. If it's not already displayed, select your desired project from the Projects menu in the navigation bar.

  3. If it's not already displayed, click Clusters in the sidebar.

    The Clusters page displays.

2

You can go the Atlas Search page from the sidebar, the Data Explorer, or your cluster details page.

  1. In the sidebar, click Atlas Search under the Services heading.

  2. From the Select data source dropdown, select your cluster and click Go to Atlas Search.

    The Atlas Search page displays.

  1. Click the Browse Collections button for your cluster.

  2. Expand the database and select the collection.

  3. Click the Search Indexes tab for the collection.

    The Atlas Search page displays.

  1. Click the cluster's name.

  2. Click the Atlas Search tab.

    The Atlas Search page displays.

3

To create, click Create Search Index.

4
Screenshot of create Atlas Vector Search index
click to enlarge
5
  1. In the Index Name field, enter a name for the index.

    Index name must be unique within the namespace, regardless of the index type.

    Example

    Enter vector_index as the name for the example index. If you already have an index named vector_index on this collection, enter a different name for the index.

  2. In the Database and Collection section, find the database, and select the collection.

    Tip

    If you navigated to this page from the Data Explorer, you can skip this step because Atlas preselects the database and collection that you selected in the Data Explorer.

    Example

    In the Database and Collection section, find the sample_mflix database, and select the embedded_movies collection.

6

An Atlas Vector Search index resembles the following example:

1{
2 "fields":[
3 {
4 "type": "vector",
5 "path": <field-to-index>,
6 "numDimensions": <number-of-dimensions>,
7 "similarity": "euclidean | cosine | dotProduct"
8 },
9 {
10 "type": "filter",
11 "path": "<field-to-index>"
12 },
13 ...
14 ]
15}

To learn more about the fields in the index, see How to Index Fields for Vector Search.

Example

The following index definition indexes the plot_embedding field as the vector type and the genres and year fields as the filter type in an Atlas Vector Search index. The plot_embedding field contains embeddings created using OpenAI's text-embedding-ada-002 embeddings model. The index definition specifies 1536 vector dimensions and measures similarity using dotProduct function.

The following index definition indexes only the vector embeddings field for performing vector search.

1{
2 "fields": [{
3 "type": "vector",
4 "path": "plot_embedding",
5 "numDimensions": 1536,
6 "similarity": "dotProduct"
7 }]
8}

This index definition indexes the following fields:

  • A string field (genres) and a numeric field (year) for pre-filtering the data.

  • The vector embeddings field (plot_embedding) for performing vector search against pre-filtered data.

1{
2 "fields": [{
3 "type": "vector",
4 "path": "plot_embedding",
5 "numDimensions": 1536,
6 "similarity": "dotProduct"
7 },
8 {
9 "type": "filter",
10 "path": "genres"
11 },
12 {
13 "type": "filter",
14 "path": "year"
15 }]
16}
7
8

Atlas displays a modal window to let you know your index is building.

9
10

The newly created index appears on the Atlas Search tab. While the index is building, the Status field reads Build in Progress. When the index is finished building, the Status field reads Active.

Note

Larger collections take longer to index. You will receive an email notification when your index is finished building.

To create an Atlas Vector Search index for a collection using mongosh v2.1.2 or later, perform the following steps:

1

To learn more, see Connect via mongosh.

2

Example

use sample_mflix
switched to db sample_mflix
3

The db.collection.createSearchIndex() method has the following syntax:

1db.<collectionName>.createSearchIndex(
2 "<index-name>",
3 "vectorSearch", //index type
4 {
5 fields: [
6 {
7 "type": "vector",
8 "numDimensions": <number-of-dimensions>,
9 "path": "<field-to-index>",
10 "similarity": "euclidean | cosine | dotProduct"
11 },
12 {
13 "type": "filter",
14 "path": "<field-to-index>"
15 },
16 ...
17 ]
18 }
19);

Example

The following index definition indexes the plot_embedding field as the vector type and the genres and year fields as the filter type in an Atlas Vector Search index. The plot_embedding field contains embeddings created using OpenAI's text-embedding-ada-002 embeddings model. The index definition specifies 1536 vector dimensions and measures similarity using dotProduct function.

The following index definition indexes only the vector embeddings field for performing vector search.

1db.embedded_movies.createSearchIndex(
2 "vector_index",
3 "vectorSearch",
4 {
5 "fields": [
6 {
7 "type": "vector",
8 "path": "plot_embedding",
9 "numDimensions": 1536,
10 "similarity": "dotProduct"
11 }
12 ]
13 }
14);

This index definition indexes the following fields:

  • A string field (genres) and a numeric field (year) for pre-filtering the data.

  • The vector embeddings field (plot_embedding) for performing vector search against pre-filtered data.

1db.embedded_movies.createSearchIndex(
2 "vector_index",
3 "vectorSearch",
4 {
5 "fields": [
6 {
7 "type": "vector",
8 "path": "plot_embedding",
9 "numDimensions": 1536,
10 "similarity": "dotProduct"
11 },
12 {
13 "type": "filter",
14 "path": "genres"
15 },
16 {
17 "type": "filter",
18 "path": "year"
19 }
20 ]
21 }
22);

To create an Atlas Vector Search index for a collection using the MongoDB Go driver v1.16.0 or later, perform the following steps:

1
1package main
2
3import (
4 "context"
5 "fmt"
6 "log"
7
8 "go.mongodb.org/mongo-driver/bson"
9 "go.mongodb.org/mongo-driver/mongo"
10 "go.mongodb.org/mongo-driver/mongo/options"
11)
12
13func main() {
14 ctx := context.Background()
15
16 // Replace the placeholder with your Atlas connection string
17 const uri = "<connectionString>"
18
19 // Connect to your Atlas cluster
20 clientOptions := options.Client().ApplyURI(uri)
21 client, err := mongo.Connect(ctx, clientOptions)
22 if err != nil {
23 log.Fatalf("failed to connect to the server: %v", err)
24 }
25 defer func() { _ = client.Disconnect(ctx) }()
26
27 // Set the namespace
28 coll := client.Database("<databaseName>").Collection("<collectionName>")
29
30 // Define the index details
31 type vectorDefinitionField struct {
32 Type string `bson:"type"`
33 Path string `bson:"path"`
34 NumDimensions int `bson:"numDimensions"`
35 Similarity string `bson:"similarity"`
36 }
37
38 type vectorDefinition struct {
39 Fields []vectorDefinitionField `bson:"fields"`
40 }
41
42 indexName := "<indexName>"
43 opts := options.SearchIndexes().SetName(indexName).SetType("vectorSearch")
44
45 indexModel := mongo.SearchIndexModel{
46 Definition: vectorDefinition{
47 Fields: []vectorDefinitionField{{
48 Type: "vector",
49 Path: "<fieldToIndex>",
50 NumDimensions: <numberOfDimensions>,
51 Similarity: "euclidean | cosine | dotProduct"}},
52 },
53 Options: opts,
54 }
55
56 // Create the index
57 log.Println("Creating the index.")
58 searchIndexName, err := coll.SearchIndexes().CreateOne(ctx, indexModel)
59 if err != nil {
60 log.Fatalf("failed to create the search index: %v", err)
61 }
62
63 // Await the creation of the index.
64 log.Println("Polling to confirm successful index creation.")
65 log.Println("NOTE: This may take up to a minute.")
66 searchIndexes := coll.SearchIndexes()
67 var doc bson.Raw
68 for doc == nil {
69 cursor, err := searchIndexes.List(ctx, options.SearchIndexes().SetName(searchIndexName))
70 if err != nil {
71 fmt.Errorf("failed to list search indexes: %w", err)
72 }
73
74 if !cursor.Next(ctx) {
75 break
76 }
77
78 name := cursor.Current.Lookup("name").StringValue()
79 queryable := cursor.Current.Lookup("queryable").Boolean()
80 if name == searchIndexName && queryable {
81 doc = cursor.Current
82 } else {
83 time.Sleep(5 * time.Second)
84 }
85 }
86
87 log.Println("Name of Index Created: " + searchIndexName)
88}

Example

Create a file named vector-index.go.

2

<connectionString>

Atlas connection string. To learn more, see Connect via Drivers.

<databaseName>

Database that contains the collection for which you want to create the index.

<collectionName>

Collection for which you want to create the index.

<indexName>

Name of your index. If you omit the index name, Atlas Search names the index vector_index.

<numberOfDimensions>

Number of vector dimensions that Atlas Vector Search enforces at index-time and query-time.

<fieldToIndex>

Vector and filter fields to index.

Example

Copy and paste the following into the vector-index.go file and replace the <connectionString> placeholder value. The following index definition indexes the plot_embedding field as the vector type and the genres and year fields as the filter type in an Atlas Vector Search index. The plot_embedding field contains embeddings created using OpenAI's text-embedding-ada-002 embeddings model. The index definition specifies 1536 vector dimensions and measures similarity using dotProduct function.

The following index definition indexes only the vector embeddings field (plot_embedding) for performing vector search.

1package main
2
3import (
4 "context"
5 "fmt"
6 "log"
7 "time"
8
9 "go.mongodb.org/mongo-driver/bson"
10 "go.mongodb.org/mongo-driver/mongo"
11 "go.mongodb.org/mongo-driver/mongo/options"
12)
13
14func main() {
15 ctx := context.Background()
16
17 // Replace the placeholder with your Atlas connection string
18 const uri = "<connectionString>"
19
20 // Connect to your Atlas cluster
21 clientOptions := options.Client().ApplyURI(uri)
22 client, err := mongo.Connect(ctx, clientOptions)
23 if err != nil {
24 log.Fatalf("failed to connect to the server: %v", err)
25 }
26 defer func() { _ = client.Disconnect(ctx) }()
27
28 // Set the namespace
29 coll := client.Database("sample_mflix").Collection("embedded_movies")
30
31 // Define the index details
32 type vectorDefinitionField struct {
33 Type string `bson:"type"`
34 Path string `bson:"path"`
35 NumDimensions int `bson:"numDimensions"`
36 Similarity string `bson:"similarity"`
37 }
38
39 type vectorDefinition struct {
40 Fields []vectorDefinitionField `bson:"fields"`
41 }
42
43 indexName := "vector_index"
44 opts := options.SearchIndexes().SetName(indexName).SetType("vectorSearch")
45
46 indexModel := mongo.SearchIndexModel{
47 Definition: vectorDefinition{
48 Fields: []vectorDefinitionField{{
49 Type: "vector",
50 Path: "plot_embedding",
51 NumDimensions: 1536,
52 Similarity: "dotProduct"}},
53 },
54 Options: opts,
55 }
56
57 // Create the index
58 searchIndexName, err := coll.SearchIndexes().CreateOne(ctx, indexModel)
59 if err != nil {
60 log.Fatalf("failed to create the search index: %v", err)
61 }
62 log.Println("New search index named " + searchIndexName + " is building.")
63
64 // Await the creation of the index.
65 log.Println("Polling to check if the index is ready. This may take up to a minute.")
66 searchIndexes := coll.SearchIndexes()
67 var doc bson.Raw
68 for doc == nil {
69 cursor, err := searchIndexes.List(ctx, options.SearchIndexes().SetName(searchIndexName))
70 if err != nil {
71 fmt.Errorf("failed to list search indexes: %w", err)
72 }
73
74 if !cursor.Next(ctx) {
75 break
76 }
77
78 name := cursor.Current.Lookup("name").StringValue()
79 queryable := cursor.Current.Lookup("queryable").Boolean()
80 if name == searchIndexName && queryable {
81 doc = cursor.Current
82 } else {
83 time.Sleep(5 * time.Second)
84 }
85 }
86
87 log.Println(searchIndexName + " is ready for querying.")
88}

This index definition indexes the following fields:

  • A string field (genres) and a numeric field (year) for pre-filtering the data.

  • The vector embeddings field (plot_embedding) for performing vector search against pre-filtered data.

1package main
2
3import (
4 "context"
5 "fmt"
6 "log"
7 "time"
8
9 "go.mongodb.org/mongo-driver/bson"
10 "go.mongodb.org/mongo-driver/mongo"
11 "go.mongodb.org/mongo-driver/mongo/options"
12)
13
14func main() {
15 ctx := context.Background()
16
17 // Replace the placeholder with your Atlas connection string
18 const uri = "<connectionString>"
19
20 // Connect to your Atlas cluster
21 clientOptions := options.Client().ApplyURI(uri)
22 client, err := mongo.Connect(ctx, clientOptions)
23 if err != nil {
24 log.Fatalf("failed to connect to the server: %v", err)
25 }
26 defer func() { _ = client.Disconnect(ctx) }()
27
28 // Set the namespace
29 coll := client.Database("sample_mflix").Collection("embedded_movies")
30 indexName := "vector_index"
31 opts := options.SearchIndexes().SetName(indexName).SetType("vectorSearch")
32
33 type vectorDefinitionField struct {
34 Type string `bson:"type"`
35 Path string `bson:"path"`
36 NumDimensions int `bson:"numDimensions"`
37 Similarity string `bson:"similarity"`
38 }
39
40 type filterField struct {
41 Type string `bson:"type"`
42 Path string `bson:"path"`
43 }
44
45 type indexDefinition struct {
46 Fields []vectorDefinitionField `bson:"fields"`
47 }
48
49 vectorDefinition := vectorDefinitionField{
50 Type: "vector",
51 Path: "plot_embedding",
52 NumDimensions: 1536,
53 Similarity: "dotProduct"}
54 genreFilterDefinition := filterField{"filter", "genres"}
55 yearFilterDefinition := filterField{"filter", "year"}
56
57 indexModel := mongo.SearchIndexModel{
58 Definition: bson.D{{"fields", [3]interface{}{
59 vectorDefinition,
60 genreFilterDefinition,
61 yearFilterDefinition}}},
62 Options: opts,
63 }
64
65 // Create the index
66 searchIndexName, err := coll.SearchIndexes().CreateOne(ctx, indexModel)
67 if err != nil {
68 log.Fatalf("failed to create the search index: %v", err)
69 }
70 log.Println("New search index named " + searchIndexName + " is building.")
71
72 // Await the creation of the index.
73 log.Println("Polling to check if the index is ready. This may take up to a minute.")
74 searchIndexes := coll.SearchIndexes()
75 var doc bson.Raw
76 for doc == nil {
77 cursor, err := searchIndexes.List(ctx, options.SearchIndexes().SetName(searchIndexName))
78 if err != nil {
79 fmt.Errorf("failed to list search indexes: %w", err)
80 }
81
82 if !cursor.Next(ctx) {
83 break
84 }
85
86 name := cursor.Current.Lookup("name").StringValue()
87 queryable := cursor.Current.Lookup("queryable").Boolean()
88 if name == searchIndexName && queryable {
89 doc = cursor.Current
90 } else {
91 time.Sleep(5 * time.Second)
92 }
93 }
94
95 log.Println(searchIndexName + " is ready for querying.")
96}
3
go run <file-name>.go

Example

go run vector-index.go

To create an Atlas Vector Search index for a collection using the MongoDB Java driver v5.2.0 or later, perform the following steps:

1
1import com.mongodb.client.ListSearchIndexesIterable;
2import com.mongodb.client.MongoClient;
3import com.mongodb.client.MongoClients;
4import com.mongodb.client.MongoCollection;
5import com.mongodb.client.MongoCursor;
6import com.mongodb.client.MongoDatabase;
7import com.mongodb.client.model.SearchIndexModel;
8import com.mongodb.client.model.SearchIndexType;
9import org.bson.Document;
10import org.bson.conversions.Bson;
11
12import java.util.Arrays;
13import java.util.Collections;
14import java.util.List;
15
16public class VectorIndex {
17
18 public static void main(String[] args) {
19
20 // Replace the placeholder with your Atlas connection string
21 String uri = "<connectionString>";
22
23 // Connect to your Atlas cluster
24 try (MongoClient mongoClient = MongoClients.create(uri)) {
25
26 // Set the namespace
27 MongoDatabase database = mongoClient.getDatabase("<databaseName>");
28 MongoCollection<Document> collection = database.getCollection("<collectionName>");
29
30 // Define the index details
31 String indexName = "<indexName>";
32 Bson definition = new Document(
33 "fields",
34 Arrays.asList(
35 new Document("type", "vector")
36 .append("path", "<fieldToIndex>")
37 .append("numDimensions", <numberOfDimensions>)
38 .append("similarity", "euclidean | cosine | dotProduct"),
39 new Document("type", "filter")
40 .append("path", "<fieldToIndex>"),
41 ...
42 )
43 );
44
45 // Define the index model
46 SearchIndexModel indexModel = new SearchIndexModel(
47 indexName,
48 definition,
49 SearchIndexType.vectorSearch()
50 );
51
52 // Create the index
53 try {
54 List<String> result = collection.createSearchIndexes(Collections.singletonList(indexModel));
55 System.out.println("New search index named " + result.get(0) + " is building.");
56 } catch (Exception e) {
57 throw new RuntimeException("Error creating index: " + e);
58 }
59
60
61 // Wait for Atlas to build the index
62 System.out.println("Polling to check if the index is ready. This may take up to a minute.");
63
64 ListSearchIndexesIterable<Document> searchIndexes = collection.listSearchIndexes();
65 Document doc = null;
66 while (doc == null) {
67 try (MongoCursor<Document> cursor = searchIndexes.iterator()) {
68 if (!cursor.hasNext()) {
69 break;
70 }
71 Document current = cursor.next();
72 String name = current.getString("name");
73 // When the index completes building, it becomes `queryable`
74 boolean queryable = current.getBoolean("queryable");
75 if (name.equals(indexName) && queryable) {
76 doc = current;
77 } else {
78 Thread.sleep(500);
79 }
80 } catch (Exception e) {
81 throw new RuntimeException("Failed to list search indexes: " + e);
82 mongoClient.close();
83 }
84 }
85 System.out.println(indexName + " is ready for querying.");
86
87 } catch (Exception e) {
88 throw new RuntimeException("Error connecting to MongoDB: " + e);
89 }
90 }
91}
2

<connectionString>

Atlas connection string. To learn more, see Connect via Drivers.

<databaseName>

Database that contains the collection for which you want to create the index.

<collectionName>

Collection for which you want to create the index.

<indexName>

Name of your index. If you omit the index name, Atlas Search names the index vector_index.

<numberOfDimensions>

Number of vector dimensions that Atlas Vector Search enforces at index-time and query-time.

<fieldToIndex>

Vector and filter fields to index.

The following example index definitions:

  • Index the plot_embedding field as the vector type and the genres and year fields as the filter type in an Atlas Vector Search index.

  • Specifies the plot_embedding field as the vector embeddings field, which contains embeddings created using OpenAI's text-embedding-ada-002 embeddings model.

  • Specifies 1536 vector dimensions and measures similarity using dotProduct function.

This index definition indexes only the vector embeddings field (plot_embedding) for performing vector search.

Copy and paste the following into the file you created, and replace the <connectionString> placeholder value.

1import com.mongodb.client.ListSearchIndexesIterable;
2import com.mongodb.client.MongoClient;
3import com.mongodb.client.MongoClients;
4import com.mongodb.client.MongoCollection;
5import com.mongodb.client.MongoCursor;
6import com.mongodb.client.MongoDatabase;
7import com.mongodb.client.model.SearchIndexModel;
8import com.mongodb.client.model.SearchIndexType;
9import org.bson.Document;
10import org.bson.conversions.Bson;
11
12import java.util.Collections;
13import java.util.List;
14
15public class VectorIndex {
16
17 public static void main(String[] args) {
18
19 // Replace the placeholder with your Atlas connection string
20 String uri = "<connectionString>";
21
22 // Connect to your Atlas cluster
23 try (MongoClient mongoClient = MongoClients.create(uri)) {
24
25 // Set the namespace
26 MongoDatabase database = mongoClient.getDatabase("sample_mflix");
27 MongoCollection<Document> collection = database.getCollection("embedded_movies");
28
29 // Define the index details
30 String indexName = "vector_index";
31 Bson definition = new Document(
32 "fields",
33 Collections.singletonList(
34 new Document("type", "vector")
35 .append("path", "plot_embedding")
36 .append("numDimensions", 1536)
37 .append("similarity", "dotProduct")));
38
39 // Define the index model
40 SearchIndexModel indexModel = new SearchIndexModel(
41 indexName,
42 definition,
43 SearchIndexType.vectorSearch());
44
45 // Create the index
46 try {
47 List<String> result = collection.createSearchIndexes(Collections.singletonList(indexModel));
48 System.out.println("New search index named " + result.get(0) + " is building.");
49 } catch (Exception e) {
50 throw new RuntimeException("Error creating index: " + e);
51 }
52
53 // Wait for Atlas to build the index
54 System.out.println("Polling to check if the index is ready. This may take up to a minute.");
55
56 ListSearchIndexesIterable<Document> searchIndexes = collection.listSearchIndexes();
57 Document doc = null;
58 while (doc == null) {
59 try (MongoCursor<Document> cursor = searchIndexes.iterator()) {
60 if (!cursor.hasNext()) {
61 break;
62 }
63 Document current = cursor.next();
64 String name = current.getString("name");
65 // When the index completes building, it becomes `queryable`
66 boolean queryable = current.getBoolean("queryable");
67 if (name.equals(indexName) && queryable) {
68 doc = current;
69 } else {
70 Thread.sleep(500);
71 }
72 } catch (Exception e) {
73 throw new RuntimeException("Failed to list search indexes: " + e);
74 }
75 }
76 System.out.println(indexName + " is ready for querying.");
77
78 } catch (Exception e) {
79 throw new RuntimeException("Error connecting to MongoDB: " + e);
80 }
81 }
82}

This index definition indexes the following fields:

  • A string field (genres) and a numeric field (year) for pre-filtering the data.

  • The vector embeddings field (plot_embedding) for performing vector search against pre-filtered data.

Copy and paste the following into the file you created, and replace the <connectionString> placeholder value.

1import com.mongodb.client.ListSearchIndexesIterable;
2import com.mongodb.client.MongoClient;
3import com.mongodb.client.MongoClients;
4import com.mongodb.client.MongoCollection;
5import com.mongodb.client.MongoCursor;
6import com.mongodb.client.MongoDatabase;
7import com.mongodb.client.model.SearchIndexModel;
8import com.mongodb.client.model.SearchIndexType;
9import org.bson.Document;
10import org.bson.conversions.Bson;
11
12import java.util.Arrays;
13import java.util.Collections;
14import java.util.List;
15
16public class VectorIndex {
17
18 public static void main(String[] args) {
19
20 // Replace the placeholder with your Atlas connection string
21 String uri = "<connectionString>";
22
23 // Connect to your Atlas cluster
24 try (MongoClient mongoClient = MongoClients.create(uri)) {
25
26 // Set the namespace
27 MongoDatabase database = mongoClient.getDatabase("sample_mflix");
28 MongoCollection<Document> collection = database.getCollection("embedded_movies");
29
30 // Define the index details with the filter fields
31 String indexName = "vector_index";
32 Bson definition = new Document(
33 "fields",
34 Arrays.asList(
35 new Document("type", "vector")
36 .append("path", "plot_embedding")
37 .append("numDimensions", 1536)
38 .append("similarity", "dotProduct"),
39 new Document("type", "filter")
40 .append("path", "genres"),
41 new Document("type", "filter")
42 .append("path", "year")));
43
44 // Define the index model
45 SearchIndexModel indexModel = new SearchIndexModel(
46 indexName,
47 definition,
48 SearchIndexType.vectorSearch());
49
50 // Create the filtered index
51 try {
52 List<String> result = collection.createSearchIndexes(Collections.singletonList(indexModel));
53 System.out.println("New search index named " + result.get(0) + " is building.");
54 } catch (Exception e) {
55 throw new RuntimeException("Error creating index: " + e);
56 }
57
58 // Wait for Atlas to build the index
59 System.out.println("Polling to check if the index is ready. This may take up to a minute.");
60
61 ListSearchIndexesIterable<Document> searchIndexes = collection.listSearchIndexes();
62 Document doc = null;
63 while (doc == null) {
64 try (MongoCursor<Document> cursor = searchIndexes.iterator()) {
65 if (!cursor.hasNext()) {
66 break;
67 }
68 Document current = cursor.next();
69 String name = current.getString("name");
70 // When the index completes building, it becomes `queryable`
71 boolean queryable = current.getBoolean("queryable");
72 if (name.equals(indexName) && queryable) {
73 doc = current;
74 } else {
75 Thread.sleep(500);
76 }
77 } catch (Exception e) {
78 throw new RuntimeException("Failed to list search indexes: " + e);
79 mongoClient.close();
80 }
81 }
82 System.out.println(indexName + " is ready for querying.");
83
84 } catch (Exception e) {
85 throw new RuntimeException("Error connecting to MongoDB: " + e);
86 }
87 }
88}
3

From your IDE, run the file to create the index.

To create an Atlas Vector Search index for a collection using the MongoDB Node driver v6.6.0 or later, perform the following steps:

1
1const { MongoClient } = require("mongodb");
2
3// connect to your Atlas deployment
4const uri = "<connectionString>";
5
6const client = new MongoClient(uri);
7
8async function run() {
9 try {
10 const database = client.db("<databaseName>");
11 const collection = database.collection("<collectionName>");
12
13 // define your Atlas Vector Search index
14 const index = {
15 name: "<indexName>",
16 type: "vectorSearch",
17 definition: {
18 "fields": [
19 {
20 "type": "vector",
21 "numDimensions": <numberOfDimensions>,
22 "path": "<fieldToIndex>",
23 "similarity": "euclidean | cosine | dotProduct"
24 },
25 {
26 "type": "filter",
27 "path": "<fieldToIndex>"
28 },
29 ...
30 ]
31 }
32 }
33
34 // run the helper method
35 const result = await collection.createSearchIndex(index);
36 console.log(`New search index named ${result} is building.`);
37 // wait for the index to be ready to query
38 console.log("Polling to check if the index is ready. This may take up to a minute.")
39 let isQueryable = false;
40 while (!isQueryable) {
41 const cursor = collection.listSearchIndexes();
42 for await (const index of cursor) {
43 if (index.name === result) {
44 if (index.queryable) {
45 console.log(`${result} is ready for querying.`);
46 isQueryable = true;
47 } else {
48 await new Promise(resolve => setTimeout(resolve, 5000));
49 }
50 }
51 }
52 }
53 } finally {
54 await client.close();
55 }
56}
57run().catch(console.dir);

Example

Create a file named vector-index.js.

2

<connectionString>

Atlas connection string. To learn more, see Connect via Drivers.

<databaseName>

Database that contains the collection for which you want to create the index.

<collectionName>

Collection for which you want to create the index.

<indexName>

Name of your index. If you omit the index name, Atlas Search names the index vector_index.

<numberOfDimensions>

Number of vector dimensions that Atlas Vector Search enforces at index-time and query-time.

<fieldToIndex>

Vector and filter fields to index.

Example

Copy and paste the following into the vector-index.js file and replace the <connectionString> placeholder value. The following index definition indexes the plot_embedding field as the vector type and the genres and year fields as the filter type in an Atlas Vector Search index. The plot_embedding field contains embeddings created using OpenAI's text-embedding-ada-002 embeddings model. The index definition specifies 1536 vector dimensions and measures similarity using dotProduct function.

The following index definition indexes only the vector embeddings field (plot_embedding) for performing vector search.

1const { MongoClient } = require("mongodb");
2
3// connect to your Atlas deployment
4const uri = "<connectionString>";
5
6const client = new MongoClient(uri);
7
8async function run() {
9 try {
10 const database = client.db("sample_mflix");
11 const collection = database.collection("embedded_movies");
12
13 // define your Atlas Vector Search index
14 const index = {
15 name: "vector_index",
16 type: "vectorSearch",
17 definition: {
18 "fields": [
19 {
20 "type": "vector",
21 "numDimensions": 1536,
22 "path": "plot_embedding",
23 "similarity": "dotProduct"
24 }
25 ]
26 }
27 }
28
29 // run the helper method
30 const result = await collection.createSearchIndex(index);
31 console.log(`New search index named ${result} is building.`);
32
33 // wait for the index to be ready to query
34 console.log("Polling to check if the index is ready. This may take up to a minute.")
35 let isQueryable = false;
36 while (!isQueryable) {
37 const cursor = collection.listSearchIndexes();
38 for await (const index of cursor) {
39 if (index.name === result) {
40 if (index.queryable) {
41 console.log(`${result} is ready for querying.`);
42 isQueryable = true;
43 } else {
44 await new Promise(resolve => setTimeout(resolve, 5000));
45 }
46 }
47 }
48 }
49 } finally {
50 await client.close();
51 }
52}
53run().catch(console.dir);

This index definition indexes the following fields:

  • A string field (genres) and a numeric field (year) for pre-filtering the data.

  • The vector embeddings field (plot_embedding) for performing vector search against pre-filtered data.

1const { MongoClient } = require("mongodb");
2
3// connect to your Atlas deployment
4const uri = "<connectionString>";
5
6const client = new MongoClient(uri);
7
8async function run() {
9 try {
10 const database = client.db("sample_mflix");
11 const collection = database.collection("embedded_movies");
12
13 // define your Atlas Vector Search index
14 const index = {
15 name: "vector_index",
16 type: "vectorSearch",
17 definition: {
18 "fields": [
19 {
20 "type": "vector",
21 "numDimensions": 1536,
22 "path": "plot_embedding",
23 "similarity": "dotProduct"
24 },
25 {
26 "type": "filter",
27 "path": "genres"
28 },
29 {
30 "type": "filter",
31 "path": "year"
32 }
33 ]
34 }
35 }
36
37 // run the helper method
38 const result = await collection.createSearchIndex(index);
39 console.log(`New search index named ${result} is building.`);
40
41 // wait for the index to be ready to query
42 console.log("Polling to check if the index is ready. This may take up to a minute.")
43 let isQueryable = false;
44 while (!isQueryable) {
45 const cursor = collection.listSearchIndexes();
46 for await (const index of cursor) {
47 if (index.name === result) {
48 if (index.queryable) {
49 console.log(`${result} is ready for querying.`);
50 isQueryable = true;
51 } else {
52 await new Promise(resolve => setTimeout(resolve, 5000));
53 }
54 }
55 }
56 }
57 } finally {
58 await client.close();
59 }
60}
61run().catch(console.dir);
3
node <file-name>.js

Example

node vector_index.js

To create an Atlas Vector Search index for a collection using the PyMongo driver v4.7 or later, perform the following steps:

1
1import pymongo
2from pymongo.mongo_client import MongoClient
3from pymongo.operations import SearchIndexModel
4
5# Connect to your Atlas deployment
6uri = "<connectionString>"
7client = MongoClient(uri)
8
9# Access your database and collection
10database = client["<databaseName>"]
11collection = database["<collectionName>"]
12
13# Create your index model, then create the search index
14search_index_model = SearchIndexModel(
15 definition={
16 "fields": [
17 {
18 "type": "vector",
19 "numDimensions": <numberofDimensions>,
20 "path": "<fieldToIndex>",
21 "similarity": "euclidean | cosine | dotProduct"
22 },
23 {
24 "type": "filter",
25 "path": "<fieldToIndex>"
26 },
27 ...
28 ]
29 },
30 name="<indexName>",
31 type="vectorSearch",
32)
33
34result = collection.create_search_index(model=search_index_model)
35print("New search index named " + result + " is building.")
36
37# Wait for initial sync to complete
38print("Polling to check if the index is ready. This may take up to a minute.")
39predicate=None
40if predicate is None:
41 predicate = lambda index: index.get("queryable") is True
42
43while True:
44 indices = list(collection.list_search_indexes(result))
45 if len(indices) and predicate(indices[0]):
46 break
47 time.sleep(5)
48print(result + " is ready for querying.")
49
50client.close()

To learn more, see the create_search_index() method.

1from pymongo.mongo_client import MongoClient
2from pymongo.operations import SearchIndexModel
3
4def create_indexes():
5 # Connect to your Atlas deployment
6 uri = "<connectionString>"
7 client = MongoClient(uri)
8
9 # Access your database and collection
10 database = client["<databaseName>"]
11 collection = database["<collectionName>"]
12
13 # Create your index models and add them to an array
14 first_model = SearchIndexModel(
15 definition={
16 "fields": [
17 {
18 "type": "vector",
19 "numDimensions": <numberOfDimensions>,
20 "path": "<fieldToIndex>",
21 "similarity": "euclidean | cosine | dotProduct"
22 },
23 {
24 "type": "filter",
25 "path": "<fieldToIndex>"
26 },
27 ...
28 ]
29 },
30 name="<indexName>",
31 type="vectorSearch",
32 )
33
34 second_model = SearchIndexModel(
35 definition={
36 "fields": [
37 {
38 "type": "vector",
39 "numDimensions": <numberOfDimensions>,
40 "path": "<fieldToIndex>",
41 "similarity": "euclidean | cosine | dotProduct"
42 },
43 {
44 "type": "filter",
45 "path": "<fieldToIndex>"
46 },
47 ...
48 ]
49 },
50 name="<index name>",
51 type="vectorSearch",
52 )
53
54 ...
55
56 idx_models = [first_model, second_model, ...]
57
58 # Create the search indexes
59 result = collection.create_search_indexes(models=idx_models)
60 print(result)
61
62 client.close()

To learn more, see the create_search_indexes() method.

Example

Create a file named vector-index.py.

2

<connectionString>

Atlas connection string. To learn more, see Connect via Drivers.

<databaseName>

Database that contains the collection for which you want to create the index.

<collectionName>

Collection for which you want to create the index.

<indexName>

Name of your index. If you omit the index name, Atlas Search names the index vector_index.

<numberOfDimensions>

Number of vector dimensions that Atlas Vector Search enforces at index-time and query-time.

<fieldToIndex>

Vector and filter fields to index.

Example

Copy and paste the following into the vector-index.py and replace the <connectionString> placeholder value. The following index definition indexes the plot_embedding field as the vector type and the genres and year fields as the filter type in an Atlas Vector Search index. The plot_embedding field contains embeddings created using OpenAI's text-embedding-ada-002 embeddings model. The index definition specifies 1536 vector dimensions and measures similarity using dotProduct function.

The following index definition indexes only the vector embeddings field (plot_embedding) for performing vector search.

1from pymongo.mongo_client import MongoClient
2from pymongo.operations import SearchIndexModel
3import time
4
5# Connect to your Atlas deployment
6uri = "<connectionString>"
7client = MongoClient(uri)
8
9# Access your database and collection
10database = client["sample_mflix"]
11collection = database["embedded_movies"]
12
13# Create your index model, then create the search index
14search_index_model = SearchIndexModel(
15 definition={
16 "fields": [
17 {
18 "type": "vector",
19 "path": "plot_embedding",
20 "numDimensions": 1536,
21 "similarity": "dotProduct"
22 }
23 ]
24 },
25 name="vector_index",
26 type="vectorSearch",
27)
28
29result = collection.create_search_index(model=search_index_model)
30print("New search index named " + result + " is building.")
31# Wait for initial sync to complete
32print("Polling to check if the index is ready. This may take up to a minute.")
33predicate=None
34if predicate is None:
35 predicate = lambda index: index.get("queryable") is True
36
37while True:
38 indices = list(collection.list_search_indexes(name))
39 if len(indices) and predicate(indices[0]):
40 break
41 time.sleep(5)
42print(result + " is ready for querying.")
43
44client.close()

This index definition indexes the following fields:

  • A string field (genres) and a numeric field (year) for pre-filtering the data.

  • The vector embeddings field (plot_embedding) for performing vector search against pre-filtered data.

1from pymongo.mongo_client import MongoClient
2from pymongo.operations import SearchIndexModel
3import time
4
5# Connect to your Atlas deployment
6uri = "<connectionString>"
7client = MongoClient(uri)
8
9# Access your database and collection
10database = client["sample_mflix"]
11collection = database["embedded_movies"]
12
13# Create your index model, then create the search index
14search_index_model = SearchIndexModel(
15 definition={
16 "fields": [
17 {
18 "type": "vector",
19 "path": "plot_embedding",
20 "numDimensions": 1536,
21 "similarity": "dotProduct"
22 },
23 {
24 "type": "filter",
25 "path": "genres"
26 },
27 {
28 "type": "filter",
29 "path": "year"
30 }
31 ]
32 },
33 name="vector_index",
34 type="vectorSearch",
35)
36
37result = collection.create_search_index(model=search_index_model)
38print("New search index named " + result + " is building.")
39# Wait for initial sync to complete
40print("Polling to check if the index is ready. This may take up to a minute.")
41predicate=None
42if predicate is None:
43 predicate = lambda index: index.get("queryable") is True
44
45while True:
46 indices = list(collection.list_search_indexes(result))
47 if len(indices) and predicate(indices[0]):
48 break
49 time.sleep(5)
50print(result + " is ready for querying.")
51
52client.close()
3
python <file-name>.py

Example

python vector-index.py

You can view Atlas Vector Search indexes for all collections from the Atlas UI, Atlas Administration API, Atlas CLI, mongosh, or a supported MongoDB Driver.

You need the Project Search Index Editor or higher role to view Atlas Vector Search indexes.

Note

You can use the mongosh command or driver helper methods to retrieve Atlas Search indexes on all Atlas cluster tiers. For a list of supported driver versions, see Supported Clients.


➤ Use the Select your language drop-down menu to set the language of the example in this section.


To retrieve all the Atlas Vector Search indexes for a collection using the Atlas Administration API, send a GET request to the Atlas Search indexes endpoint with the name of the database and collection.

1curl --user "{PUBLIC-KEY}:{PRIVATE-KEY}" --digest \
2 --header "Accept: application/json" \
3 --include \
4 --request GET "https://mongodb.prakticum-team.ru/proxy/cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes/{databaseName}/{collectionName}"

To learn more about the syntax and parameters for the endpoint, see Return All Atlas Search Indexes for One Collection.

To retrieve one Atlas Vector Search index for a collection using the Atlas Administration API, send a GET request to the Atlas Search indexes endpoint with either the unique ID or name of the index (line 4) to retrieve.

1curl --user "{PUBLIC-KEY}:{PRIVATE-KEY}" --digest \
2 --header "Accept: application/json" \
3 --include \
4 --request GET "https://mongodb.prakticum-team.ru/proxy/cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes/{indexId} | https://mongodb.prakticum-team.ru/proxy/cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes/{databaseName}/{collectionName}/{indexName|indexId}"

To learn more about the syntax and parameters for the endpoint, Get One By Name and Get One By ID.

To return Atlas Vector Search indexes for a collection using Atlas CLI, perform the following steps:

1

clusterName

The name of the Atlas cluster.

db

The name of the database on the Atlas cluster that contains your indexed collection.

collection

The name of the indexed collection in the database.

projectId

The unique identifier of the project.

2
atlas clusters search indexes list --clusterName [cluster_name] --db <db-name> --collection <collection-name>

In the command, replace the following placeholder values:

  • cluster-name - the name of the Atlas cluster that contains the indexed collection.

  • db-name - the name of the database that contains the collection for which you want to retrieve the indexes.

  • collection-name - the name of the collection for which you want to retrieve the indexes.

To learn more about the command syntax and parameters, see the Atlas CLI documentation for the atlas clusters search indexes list command.

1
  1. If it's not already displayed, select the organization that contains your desired project from the Organizations menu in the navigation bar.

  2. If it's not already displayed, select your desired project from the Projects menu in the navigation bar.

  3. If it's not already displayed, click Clusters in the sidebar.

    The Clusters page displays.

2

You can go the Atlas Search page from the sidebar, the Data Explorer, or your cluster details page.

  1. In the sidebar, click Atlas Search under the Services heading.

  2. From the Select data source dropdown, select your cluster and click Go to Atlas Search.

    The Atlas Search page displays.

  1. Click the Browse Collections button for your cluster.

  2. Expand the database and select the collection.

  3. Click the Search Indexes tab for the collection.

    The Atlas Search page displays.

  1. Click the cluster's name.

  2. Click the Atlas Search tab.

    The Atlas Search page displays.

The page displays the following details for the indexes on the page:

Name

Label that identifies the index.

Index Type

Label that indicates an Atlas Search or Atlas Vector Search index. Values include:

  • search for Atlas Search indexes.

  • vectorSearch for Atlas Vector Search indexes.

Index Fields

List that contains the fields that this index indexes.

Status

Current state of the index on the primary node of the cluster. For valid values, see Index Status.

Size

Size of the index on the primary node.

Documents

Number of indexed documents out of the total number of documents in the collection.

Actions

Actions that you can take on the index. You can:

You can't run queries in the Search Tester UI against indexes of the vectorSearch type. If you click the Query button, Atlas Vector Search displays a sample $vectorSearch that you can copy, modify, and run in Atlas UI and using other supported clients.

To view an Atlas Vector Search index for a collection using mongosh, perform the following steps:

1

To learn more, see Connect via mongosh.

2
3

The db.collection.getSearchIndexes() method has the following syntax:

1db.<collectionName>.getSearchIndexes( "<index-name>" );

To view an Atlas Vector Search index for a collection using MongoDB Go driver v1.16.0 or later, perform the following steps:

1
1package main
2
3import (
4 "context"
5 "encoding/json"
6 "fmt"
7 "log"
8
9 "go.mongodb.org/mongo-driver/bson"
10 "go.mongodb.org/mongo-driver/mongo"
11 "go.mongodb.org/mongo-driver/mongo/options"
12)
13
14func main() {
15 ctx := context.Background()
16
17 // Replace the placeholder with your Atlas connection string
18 const uri = "<connectionString>"
19
20 // Connect to your Atlas cluster
21 clientOptions := options.Client().ApplyURI(uri)
22 client, err := mongo.Connect(ctx, clientOptions)
23 if err != nil {
24 log.Fatalf("failed to connect to the server: %v", err)
25 }
26 defer func() { _ = client.Disconnect(ctx) }()
27
28 // Set the namespace
29 coll := client.Database("<databaseName>").Collection("<collectionName>")
30
31 // Specify the options for the index to retrieve
32 indexName := "<indexName>"
33 opts := options.SearchIndexes().SetName(indexName)
34
35 // Get the index
36 cursor, err := coll.SearchIndexes().List(ctx, opts)
37 if err != nil {
38 log.Fatalf("failed to get the index: %v", err)
39 }
40
41 // Print the index details to the console as JSON
42 var results []bson.M
43 if err := cursor.All(ctx, &results); err != nil {
44 log.Fatalf("failed to unmarshal results to bson: %v", err)
45 }
46 res, err := json.Marshal(results)
47 if err != nil {
48 log.Fatalf("failed to marshal results to json: %v", err)
49 }
50 fmt.Println(string(res))
51}
2

<connectionString>

Your Atlas connection string. To learn more, see Connect via Drivers.

<databaseName>

The database that contains the collection.

<collectionName>

The collection for which you want to retrieve the indexes.

<indexName>

The name of your index if you want to retrieve a specific index. To return all indexes on the collection, omit this value.

3
go run <file-name>.go

To view an Atlas Vector Search index for a collection using the MongoDB Java driver v5.2.0 or later, perform the following steps:

1
1import com.mongodb.client.MongoClient;
2import com.mongodb.client.MongoClients;
3import com.mongodb.client.MongoCollection;
4import com.mongodb.client.MongoDatabase;
5import org.bson.Document;
6
7public class ViewVectorIndex {
8
9 public static void main(String[] args) {
10
11 // Replace the placeholder with your Atlas connection string
12 String uri = "<connectionString>";
13
14 // Connect to your Atlas cluster
15 try (MongoClient mongoClient = MongoClients.create(uri)) {
16
17 // Set the namespace
18 MongoDatabase database = mongoClient.getDatabase("<databaseName>");
19 MongoCollection<Document> collection = database.getCollection("<collectionName>");
20
21 // Specify the options for the index to retrieve
22 String indexName = "<indexName>";
23
24 // Get the index and print details to the console as JSON
25 try {
26 Document listSearchIndex = collection.listSearchIndexes().name(indexName).first();
27 if (listSearchIndex != null) {
28 System.out.println("Index found: " + listSearchIndex.toJson());
29 } else {
30 System.out.println("Index not found.");
31 }
32 } catch (Exception e) {
33 throw new RuntimeException("Error finding index: " + e);
34 }
35
36 } catch (Exception e) {
37 throw new RuntimeException("Error connecting to MongoDB: " + e);
38 }
39 }
40}
2

<connectionString>

Your Atlas connection string. To learn more, see Connect via Drivers.

<databaseName>

The database that contains the collection.

<collectionName>

The collection for which you want to retrieve the indexes.

<indexName>

The name of your index if you want to retrieve a specific index. To return all indexes on the collection, omit this value.

3

From your IDE, run the file to retrieve the specified index.

To view an Atlas Vector Search index for a collection using MongoDB Node driver v6.6.0 or later, perform the following steps:

1
1const { MongoClient } = require("mongodb");
2
3// connect to your Atlas deployment
4const uri = "<connectionString>";
5
6const client = new MongoClient(uri);
7
8async function run() {
9 try {
10 const database = client.db("<databaseName>");
11 const collection = database.collection("<collectionName>");
12
13 // run the helper method
14 const result = await collection.listSearchIndexes("<indexName>").toArray();
15 console.log(result);
16 } finally {
17 await client.close();
18 }
19}
20run().catch(console.dir);
2

<connectionString>

Your Atlas connection string. To learn more, see Connect via Drivers.

<databaseName>

The database that contains the collection.

<collectionName>

The collection for which you want to retrieve the indexes.

<indexName>

The name of your index if you want to retrieve a specific index. To return all indexes on the collection, omit this value.

3
node <file-name>.js

To view Atlas Vector Search indexes for a collection using PyMongo driver v4.7 or later, perform the following steps:

1
1from pymongo.mongo_client import MongoClient
2
3# Connect to your Atlas deployment
4uri = "<connectionString>"
5client = MongoClient(uri)
6
7# Access your database and collection
8database = client["<databaseName>"]
9collection = database["<collectionName>"]
10
11# Get a list of the collection's search indexes and print them
12cursor = collection.list_search_indexes()
13for index in cursor:
14 print(index)

To learn more, see the list_search_indexes() method.

2

<connectionString>

Your Atlas connection string. To learn more, see Connect via Drivers.

<databaseName>

The name of the database that contains the collection.

<collectionName>

The name of the collection.

3
python <file-name>.py

You can change the index definition of an existing Atlas Vector Search index from the Atlas UI, Atlas Administration API, Atlas CLI, mongosh, or a supported MongoDB Driver. You can't rename an index or change the index type. If you need to change an index name or type, you must create a new index and delete the old one.

Important

After you edit an index, Atlas Vector Search rebuilds it. While the index rebuilds, you can continue to run vector search queries by using the old index definition. When the index finishes rebuilding, the old index is automatically replaced. This process follows the same process as standard Atlas Search indexes.

To learn more, see Creating and Updating an Atlas Search Index.

You must have the Project Search Index Editor or higher role to edit an Atlas Vector Search index.

Note

You can use the mongosh command or driver helper methods to edit Atlas Search indexes on all Atlas cluster tiers. For a list of supported driver versions, see Supported Clients.


➤ Use the Select your language drop-down menu to select the client you want to use to edit your index.


To edit an Atlas Vector Search index for a collection using the Atlas Administration API, send a PATCH request to the Atlas Search indexes endpoint with either the unique ID or name of the index (line 4) to edit.

1curl --user "{PUBLIC-KEY}:{PRIVATE-KEY}" --digest --include \
2 --header "Accept: application/json" \
3 --header "Content-Type: application/json" \
4 --request PATCH "https://mongodb.prakticum-team.ru/proxy/cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes/{indexId} | https://mongodb.prakticum-team.ru/proxy/cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes/{databaseName}/{collectionName}/{indexName|indexId}" \
5 --data'
6 {
7 "database": "<name-of-database>",
8 "collectionName": "<name-of-collection>",
9 "type": "vectorSearch",
10 "name": "<index-name>",
11 "definition": {
12 "fields":[
13 {
14 "type": "vector",
15 "path": <field-to-index>,
16 "numDimensions": <number-of-dimensions>,
17 "similarity": "euclidean | cosine | dotProduct"
18 },
19 {
20 "type": "filter",
21 "path": "<field-to-index>"
22 },
23 ...
24 }
25 ]
26 }'

To learn more about the syntax and parameters for the endpoints, see Update One By Name and Update One By ID.

To edit an Atlas Vector Search index for a collection using Atlas CLI, perform the following steps:

1

Your index definition should resemble the following format:

1{
2 "database": "<name-of-database>",
3 "collectionName": "<name-of-collection>",
4 "type": "vectorSearch",
5 "name": "<index-name>",
6 "fields":[
7 {
8 "type": "vector",
9 "path": "<field-to-index>",
10 "numDimensions": <number-of-dimensions>,
11 "similarity": "euclidean | cosine | dotProduct"
12 },
13 {
14 "type": "filter",
15 "path": "<field-to-index>"
16 },
17 ...
18 ]
19}
2

<name-of-database>

Database that contains the collection for which you want to create the index.

<name-of-collection>

Collection for which you want to create the index.

<index-name>

Name of your index. If you omit the index name, Atlas Vector Search names the index vector_index.

<number-of-dimensions>

Number of vector dimensions that Atlas Vector Search enforces at index-time and query-time.

<field-to-index>

Vector and filter fields to index.

3
atlas clusters search indexes update <indexId> --clusterName [cluster_name] --file [vector-_index].json

In the command, replace the following placeholder values:

  • cluster_name - the name of the Atlas cluster that contains the collection for which you want to update the index.

  • vector_index - the name of the JSON file that contains the modified index definition for the Atlas Vector Search index.

To learn more about the command syntax and parameters, see the Atlas CLI documentation for the atlas clusters search indexes update command.

1
  1. If it's not already displayed, select the organization that contains your desired project from the Organizations menu in the navigation bar.

  2. If it's not already displayed, select your desired project from the Projects menu in the navigation bar.

  3. If it's not already displayed, click Clusters in the sidebar.

    The Clusters page displays.

2

You can go the Atlas Search page from the sidebar, the Data Explorer, or your cluster details page.

  1. In the sidebar, click Atlas Search under the Services heading.

  2. From the Select data source dropdown, select your cluster and click Go to Atlas Search.

    The Atlas Search page displays.

  1. Click the Browse Collections button for your cluster.

  2. Expand the database and select the collection.

  3. Click the Search Indexes tab for the collection.

    The Atlas Search page displays.

  1. Click the cluster's name.

  2. Click the Atlas Search tab.

    The Atlas Search page displays.

3
  1. Locate the vectorSearch type index to edit.

  2. Click Edit Index from the Actions dropdown for that index.

  3. Review the current configuration settings and edit them as needed.

    To learn more about the fields in an Atlas Vector Search index, see How to Index Fields for Vector Search.

  4. Click Save to apply the changes.

The index's status changes from Active to Building. In this state, you can continue to use the old index because Atlas Vector Search does not delete the old index until the updated index is ready for use. Once the status returns to Active, the modified index is ready to use.

To edit an Atlas Vector Search index for a collection using mongosh, perform the following steps:

1

To learn more, see Connect via mongosh.

2
3

The db.collection.updateSearchIndex() method has the following syntax:

1db.<collectionName>.updateSearchIndex(
2 "<index-name>",
3 {
4 fields: [
5 {
6 "type": "vector",
7 "numDimensions": <number-of-dimensions>,
8 "path": "<field-to-index>",
9 "similarity": "euclidean | cosine | dotProduct"
10 },
11 {
12 "type": "filter",
13 "path": "<field-to-index>"
14 },
15 ...
16 ]
17 }
18);

To update an Atlas Vector Search index for a collection using the MongoDB Go driver v1.16.0 or later, perform the following steps:

1
1package main
2
3import (
4 "context"
5 "fmt"
6 "log"
7
8 "go.mongodb.org/mongo-driver/mongo"
9 "go.mongodb.org/mongo-driver/mongo/options"
10)
11
12func main() {
13 ctx := context.Background()
14
15 // Replace the placeholder with your Atlas connection string
16 const uri = "<connection-string>"
17
18 // Connect to your Atlas cluster
19 clientOptions := options.Client().ApplyURI(uri)
20 client, err := mongo.Connect(ctx, clientOptions)
21 if err != nil {
22 log.Fatalf("failed to connect to the server: %v", err)
23 }
24 defer func() { _ = client.Disconnect(ctx) }()
25
26 // Set the namespace
27 coll := client.Database("<databaseName>").Collection("<collectionName>")
28 indexName := "<indexName>"
29
30 type vectorDefinitionField struct {
31 Type string `bson:"type"`
32 Path string `bson:"path"`
33 NumDimensions int `bson:"numDimensions"`
34 Similarity string `bson:"similarity"`
35 }
36
37 type vectorDefinition struct {
38 Fields []vectorDefinitionField `bson:"fields"`
39 }
40
41 definition := vectorDefinition{
42 Fields: []vectorDefinitionField{{
43 Type: "vector",
44 Path: "<fieldToIndex>",
45 NumDimensions: <numberOfDimensions>,
46 Similarity: "euclidean | cosine | dotProduct"}},
47 }
48 err = coll.SearchIndexes().UpdateOne(ctx, indexName, definition)
49
50 if err != nil {
51 log.Fatalf("failed to update the index: %v", err)
52 }
53
54 fmt.Println("Successfully updated the search index")
55}
2

<connectionString>

Atlas connection string. To learn more, see Connect via Drivers.

<databaseName>

Database that contains the collection for which you want to create the index.

<collectionName>

Collection for which you want to create the index.

<indexName>

Name of your index. If you omit the index name, Atlas Search names the index vector_index.

<numberOfDimensions>

Number of vector dimensions that Atlas Vector Search enforces at index-time and query-time.

<fieldToIndex>

Vector and filter fields to index.

3
go run <file-name>.go

To edit an Atlas Vector Search index for a collection using the MongoDB Java driver v5.2.0 or later, perform the following steps:

1
1import com.mongodb.client.MongoClient;
2import com.mongodb.client.MongoClients;
3import com.mongodb.client.MongoCollection;
4import com.mongodb.client.MongoDatabase;
5import org.bson.Document;
6import org.bson.conversions.Bson;
7
8import java.util.Collections;
9
10public class EditVectorIndex {
11
12 public static void main(String[] args) {
13
14 // Replace the placeholder with your Atlas connection string
15 String uri = "<connectionString>";
16
17 // Connect to your Atlas cluster
18 try (MongoClient mongoClient = MongoClients.create(uri)) {
19
20 // Set the namespace
21 MongoDatabase database = mongoClient.getDatabase("<databaseName>");
22 MongoCollection<Document> collection = database.getCollection("<collectionName>");
23
24 // Define the index changes
25 String indexName = "<indexName>";
26 Bson definition = new Document(
27 "fields",
28 Collections.singletonList(
29 new Document("type", "vector")
30 .append("path", "<fieldToIndex>")
31 .append("numDimensions", <numberOfDimensions>)
32 .append("similarity", "euclidean | cosine | dotProduct")
33 )
34 );
35
36 // Update the index
37 try {
38 collection.updateSearchIndex(indexName, definition);
39 System.out.println("Successfully updated the index");
40 } catch (Exception e) {
41 throw new RuntimeException("Error creating index: " + e);
42 mongoClient.close();
43 }
44
45 } catch (Exception e) {
46 throw new RuntimeException("Error connecting to MongoDB: " + e);
47 }
48 }
49}
2

<connectionString>

Atlas connection string. To learn more, see Connect via Drivers.

<databaseName>

Database that contains the collection for which you want to create the index.

<collectionName>

Collection for which you want to create the index.

<indexName>

Name of your index. If you omit the index name, Atlas Search names the index vector_index.

<numberOfDimensions>

Number of vector dimensions that Atlas Vector Search enforces at index-time and query-time.

<fieldToIndex>

Vector and filter fields to index.

3

From your IDE, run the file to update the index with your changes.

To update an Atlas Vector Search index for a collection using the MongoDB Node driver v6.6.0 or later, perform the following steps:

1
1const { MongoClient } = require("mongodb");
2
3// connect to your Atlas deployment
4const uri = "<connection-string>";
5
6const client = new MongoClient(uri);
7
8async function run() {
9 try {
10 const database = client.db("<databaseName>");
11 const collection = database.collection("<collectionName>");
12
13 // define your Atlas Search index
14 const index = {
15 name: "<indexName>",
16 type: "vectorSearch",
17 //updated search index definition
18 definition: {
19 "fields": [
20 {
21 "type": "vector",
22 "numDimensions": <numberOfDimensions>,
23 "path": "<field-to-index>",
24 "similarity": "euclidean | cosine | dotProduct"
25 },
26 {
27 "type": "filter",
28 "path": "<fieldToIndex>"
29 },
30 ...
31 ]
32 }
33 }
34
35 // run the helper method
36 await collection.updateSearchIndex("<index-name>", index);
37 } finally {
38 await client.close();
39 }
40}
41run().catch(console.dir);
2

<connectionString>

Atlas connection string. To learn more, see Connect via Drivers.

<databaseName>

Database that contains the collection for which you want to create the index.

<collectionName>

Collection for which you want to create the index.

<indexName>

Name of your index. If you omit the index name, Atlas Search names the index vector_index.

<numberOfDimensions>

Number of vector dimensions that Atlas Vector Search enforces at index-time and query-time.

<fieldToIndex>

Vector and filter fields to index.

3
node <file-name>.js

To update an Atlas Vector Search index for a collection using the PyMongo driver v4.7 or later, perform the following steps:

1
1from pymongo.mongo_client import MongoClient
2
3# Connect to your Atlas deployment
4uri = "<connectionString>"
5client = MongoClient(uri)
6
7# Access your database and collection
8database = client["<databaseName>"]
9collection = database["<collectionName>"]
10
11definition = {
12 "fields": [
13 {
14 "type": "vector",
15 "numDimensions": <numberofDimensions>,
16 "path": "<fieldToIndex>",
17 "similarity": "euclidean | cosine | dotProduct"
18 },
19 {
20 "type": "filter",
21 "path": "<fieldToIndex>"
22 },
23 ...
24 ]
25}
26
27# Update your search index
28collection.update_search_index("<indexName>", definition)

To learn more, see the update_search_index() method.

2

<connectionString>

Atlas connection string. To learn more, see Connect via Drivers.

<databaseName>

Database that contains the collection for which you want to create the index.

<collectionName>

Collection for which you want to create the index.

<indexName>

Bame of your index. If you omit the index name, Atlas Search names the index vector_index.

<numberOfDimensions>

Number of vector dimensions that Atlas Vector Search enforces at index-time and query-time.

<fieldToIndex>

Vector and filter fields to index.

3
python <file-name>.py

You can delete an Atlas Vector Search index at any time from the Atlas UI, Atlas Administration API, Atlas CLI, mongosh, or a supported MongoDB Driver.

You must have the Project Search Index Editor or higher role to delete an Atlas Vector Search index.

Note

You can use the mongosh command or driver helper methods to delete Atlas Search indexes on all Atlas cluster tiers. For a list of supported driver versions, see Supported Clients.


➤ Use the Select your language drop-down menu to select the client you want to use to delete your index.


To delete an Atlas Vector Search index for a collection using the Atlas Administration API, send a DELETE request to the Atlas Search indexes endpoint with either the unique ID or the name of the index to delete.

1curl --user "{PUBLIC-KEY}:{PRIVATE-KEY}" --digest \
2 --header "Accept: application/json" \
3 --include \
4 --request DELETE "https://mongodb.prakticum-team.ru/proxy/cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes/{indexId} | https://mongodb.prakticum-team.ru/proxy/cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes/{databaseName}/{collectionName}/{indexName|indexId}"

To learn more about the syntax and parameters for the endpoint, see Remove One Search Index By Name and Remove One Search Index By ID.

To delete an Atlas Vector Search index for a collection using Atlas CLI, perform the following steps:

1

<indexId>

The unique identifier of the index to delete.

<clusterName>

The name of the Atlas cluster.

<projectId>

The unique identifier of the project.

2
atlas clusters search indexes delete <indexId> [options]

In the command, replace the indexId placeholder value with the unique identifier of the index to delete.

To learn more about the command syntax and parameters, see the Atlas CLI documentation for the atlas clusters search indexes delete command.

1
  1. If it's not already displayed, select the organization that contains your desired project from the Organizations menu in the navigation bar.

  2. If it's not already displayed, select your desired project from the Projects menu in the navigation bar.

  3. If it's not already displayed, click Clusters in the sidebar.

    The Clusters page displays.

2

You can go the Atlas Search page from the sidebar, the Data Explorer, or your cluster details page.

  1. In the sidebar, click Atlas Search under the Services heading.

  2. From the Select data source dropdown, select your cluster and click Go to Atlas Search.

    The Atlas Search page displays.

  1. Click the Browse Collections button for your cluster.

  2. Expand the database and select the collection.

  3. Click the Search Indexes tab for the collection.

    The Atlas Search page displays.

  1. Click the cluster's name.

  2. Click the Atlas Search tab.

    The Atlas Search page displays.

3
  1. Locate the vectorSearch type index to delete.

  2. Click Delete Index from the Actions dropdown for that index.

  3. Click Drop Index in the confirmation window.

To delete an Atlas Vector Search index for a collection using mongosh, perform the following steps:

1

To learn more, see Connect via mongosh.

2
3

The db.collection.dropSearchIndex() method has the following syntax:

1db.<collectionName>.dropSearchIndex( "<index-name>" );

To delete an Atlas Vector Search index for a collection using MongoDB Go driver v1.16.0 or later, perform the following steps:

1
1package main
2
3import (
4 "context"
5 "fmt"
6 "log"
7
8 "go.mongodb.org/mongo-driver/mongo"
9 "go.mongodb.org/mongo-driver/mongo/options"
10)
11
12func main() {
13 ctx := context.Background()
14
15 // Replace the placeholder with your Atlas connection string
16 const uri = "<connectionString>"
17
18 // Connect to your Atlas cluster
19 clientOptions := options.Client().ApplyURI(uri)
20 client, err := mongo.Connect(ctx, clientOptions)
21 if err != nil {
22 log.Fatalf("failed to connect to the server: %v", err)
23 }
24 defer func() { _ = client.Disconnect(ctx) }()
25
26 // Set the namespace
27 coll := client.Database("<databaseName>").Collection("<collectionName>")
28 indexName := "<indexName>"
29
30 err = coll.SearchIndexes().DropOne(ctx, indexName)
31 if err != nil {
32 log.Fatalf("failed to delete the index: %v", err)
33 }
34
35 fmt.Println("Successfully deleted the Vector Search index")
36}
2

<connectionString>

Your Atlas connection string. To learn more, see Connect via Drivers.

<databaseName>

The database that contains the collection for which you want to create the index.

<collectionName>

The collection for which you want to create the index.

<indexName>

The name of your index. If you omit the index name, Atlas Search names the index vector_index.

3
go run <file-name>.go

To delete an Atlas Vector Search index for a collection using the MongoDB Java driver v5.2.0 or later, perform the following steps:

1
1import com.mongodb.client.MongoClient;
2import com.mongodb.client.MongoClients;
3import com.mongodb.client.MongoCollection;
4import com.mongodb.client.MongoDatabase;
5import org.bson.Document;
6
7public class DeleteIndex {
8
9 public static void main(String[] args) {
10
11 // Replace the placeholder with your Atlas connection string
12 String uri = "<connectionString>";
13
14 // Connect to your Atlas cluster
15 try (MongoClient mongoClient = MongoClients.create(uri)) {
16
17 // Set the namespace
18 MongoDatabase database = mongoClient.getDatabase("<databaseName>");
19 MongoCollection<Document> collection = database.getCollection("<collectionName>");
20
21 // Specify the index to delete
22 String indexName = "<indexName>";
23
24 try {
25 collection.dropSearchIndex(indexName);
26 } catch (Exception e) {
27 throw new RuntimeException("Error deleting index: " + e);
28 }
29
30 } catch (Exception e) {
31 throw new RuntimeException("Error connecting to MongoDB: " + e);
32 }
33 }
34}
2

<connectionString>

Your Atlas connection string. To learn more, see Connect via Drivers.

<databaseName>

The database that contains the collection for which you want to create the index.

<collectionName>

The collection for which you want to create the index.

<indexName>

The name of your index. If you omit the index name, Atlas Search names the index vector_index.

3

From your IDE, run the file to delete the specified index.

To delete an Atlas Vector Search index for a collection using MongoDB Node driver v6.6.0 or later, perform the following steps:

1
1const { MongoClient } = require("mongodb");
2
3// connect to your Atlas deployment
4const uri = "<connectionString>";
5
6const client = new MongoClient(uri);
7
8async function run() {
9 try {
10 const database = client.db("<databaseName>");
11 const collection = database.collection("<collectionName>");
12
13 // run the helper method
14 await collection.dropSearchIndex("<indexName>");
15
16 } finally {
17 await client.close();
18 }
19}
20run().catch(console.dir);
2

<connectionString>

Your Atlas connection string. To learn more, see Connect via Drivers.

<databaseName>

The database that contains the collection for which you want to create the index.

<collectionName>

The collection for which you want to create the index.

<indexName>

The name of your index. If you omit the index name, Atlas Search names the index vector_index.

3
node <file-name>.js

To delete an Atlas Vector Search index for a collection using PyMongo driver v4.7 or later, perform the following steps:

1
1from pymongo.mongo_client import MongoClient
2
3# Connect to your Atlas deployment
4uri = "<connectionString>"
5client = MongoClient(uri)
6
7# Access your database and collection
8database = client["<databaseName>"]
9collection = database["<collectionName>"]
10
11# Delete your search index
12collection.drop_search_index("<indexName>")

To learn more, see the drop_search_index() method.

2

<connectionString>

Your Atlas connection string. To learn more, see Connect via Drivers.

<databaseName>

The name of the database that contains the collection.

<collectionName>

The name of the collection.

<indexName>

The name of the index to delete.

3
python <file-name>.py

When you create the Atlas Vector Search index, the Status column shows the current state of the index on the primary node of the cluster. Click the View status details link below the status to view the state of the index on all the nodes of the cluster.

When the Status column reads Active, the index is ready to use. In other states, queries against the index may return incomplete results.

Status
Description

Not Started

Atlas has not yet started building the index.

Initial Sync

Atlas is building the index or re-building the index after an edit. When the index is in this state:

  • For a new index, Atlas Vector Search doesn't serve queries until the index build is complete.

  • For an existing index, you can continue to use the old index for existing and new queries until the index rebuild is complete.

Active

Index is ready to use.

Recovering

Replication encountered an error. This state commonly occurs when the current replication point is no longer available on the mongod oplog. You can still query the existing index until it updates and its status changes to Active. Use the error in the View status details modal window to troubleshoot the issue. To learn more, see Fix Atlas Search Issues.

Failed

Atlas could not build the index. Use the error in the View status details modal window to troubleshoot the issue. To learn more, see Fix Atlas Search Issues.

Delete in Progress

Atlas is deleting the index from the cluster nodes.

While Atlas builds the index and after the build completes, the Documents column shows the percentage and number of documents indexed. The column also shows the total number of documents in the collection.

Back

How to Create Vector Embeddings