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.
Considerations
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
or int8
vectors for efficient storage and
ingestion of your vectors in your Atlas cluster. To learn more,
see how to convert your embeddings to BSON vectors.
Supported Clients
You can create and manage Atlas Vector Search indexes through the Atlas UI,
mongosh
, Atlas CLI, Atlas Administration API, and the following
MongoDB Drivers:
Syntax
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 }, 9 { 10 "type": "filter", 11 "path": "<field-to-index>" 12 }, 13 ... 14 ] 15 }
Atlas Vector Search Index Fields
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
|
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: |
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 . 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
To learn more, see About the Similarity Functions. |
About the vector
Type
Your index definition's vector
field must contain an array of numbers of
one of the following types:
Note
To learn more about generating BSON BinData vector
subtype float32
or vector
subtype int8
vectors for your data, see
How to Ingest Quantized Vectors.
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 }, 9 ... 10 ] 11 }
About the Similarity Functions
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 withcosine
. To measure cosine similarity, we recommend that you normalize your vectors and usedotProduct
instead.dotProduct
- measures similarity likecosine
, but takes into account the magnitude of the vector. If you normalize the magnitude,cosine
anddotProduct
are almost identical in measuring similarity.To use
dotProduct
, you must normalize the vector to unit length at index-time and query-time.
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.
About the filter
Type
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.
Create an Atlas Vector Search Index
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.
Prerequisites
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 higherA 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.
Required Access
You need the Project Data Access Admin
or higher role to create
and manage Atlas Vector Search indexes.
Index Limitations
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.
Procedure
➤ 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.
1 curl --user "{PUBLIC-KEY}:{PRIVATE-KEY}" --digest \ 2 --header "Accept: application/json" \ 3 --header "Content-Type: application/json" \ 4 --include \ 5 --request POST "https://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 euclidean
distance.
The following index definition indexes only the vector embeddings field for performing vector search.
1 curl --user "{PUBLIC-KEY}:{PRIVATE-KEY}" --digest \ 2 --header "Accept: application/json" \ 3 --header "Content-Type: application/json" \ 4 --include \ 5 --request POST "https://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": "euclidean" 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.
1 curl --user "{PUBLIC-KEY}:{PRIVATE-KEY}" --digest \ 2 --header "Accept: application/json" \ 3 --header "Content-Type: application/json" \ 4 --include \ 5 --request POST "https://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": "euclidean" 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:
Create a .json
file and define the index in the file.
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
.
Replace the following placeholder values and save the file.
<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 euclidean
distance.
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": "euclidean" 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": "euclidean" 12 }, 13 { 14 "type": "filter", 15 "path": "genres" 16 }, 17 { 18 "type": "filter", 19 "path": "year" 20 } 21 ] 22 }
Run the following command to create the index.
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.
In Atlas, go to the Clusters page for your project.
If it's not already displayed, select the organization that contains your desired project from the Organizations menu in the navigation bar.
If it's not already displayed, select your desired project from the Projects menu in the navigation bar.
If it's not already displayed, click Clusters in the sidebar.
The Clusters page displays.
Go to the Atlas Search page for your cluster.
You can go the Atlas Search page from the sidebar, the Data Explorer, or your cluster details page.
In the sidebar, click Atlas Search under the Services heading.
From the Select data source dropdown, select your cluster and click Go to Atlas Search.
The Atlas Search page displays.
Click the Browse Collections button for your cluster.
Expand the database and select the collection.
Click the Search Indexes tab for the collection.
The Atlas Search page displays.
Click the cluster's name.
Click the Atlas Search tab.
The Atlas Search page displays.
Enter the Index Name, and set the Database and Collection.
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.
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 theembedded_movies
collection.
Specify an index definition.
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 euclidean
distance.
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": "euclidean" 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": "euclidean" 7 }, 8 { 9 "type": "filter", 10 "path": "genres" 11 }, 12 { 13 "type": "filter", 14 "path": "year" 15 }] 16 }
Check the status.
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:
Connect to the Atlas cluster using mongosh
.
To learn more, see Connect via mongosh
.
Run the db.collection.createSearchIndex()
method.
The db.collection.createSearchIndex()
method has the
following syntax:
1 db.<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 euclidean
distance.
The following index definition indexes only the vector embeddings field for performing vector search.
1 db.embedded_movies.createSearchIndex( 2 "vector_index", 3 "vectorSearch", 4 { 5 "fields": [ 6 { 7 "type": "vector", 8 "path": "plot_embedding", 9 "numDimensions": 1536, 10 "similarity": "euclidean" 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.
1 db.embedded_movies.createSearchIndex( 2 "vector_index", 3 "vectorSearch", 4 { 5 "fields": [ 6 { 7 "type": "vector", 8 "path": "plot_embedding", 9 "numDimensions": 1536, 10 "similarity": "euclidean" 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:
Create a .go
file and define the index in the file.
1 package main 2 3 import ( 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 13 func 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
.
Replace the following values and save the file.
<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 euclidean
distance.
The following index definition indexes only the vector
embeddings field (plot_embedding
) for performing vector search.
1 package main 2 3 import ( 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 14 func 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: "euclidean"}}, 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.
1 package main 2 3 import ( 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 14 func 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: "euclidean"} 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 }
To create an Atlas Vector Search index for a collection using the MongoDB Java driver v5.2.0 or later, perform the following steps:
Create a .java
file and define the index in the file.
1 import com.mongodb.client.ListSearchIndexesIterable; 2 import com.mongodb.client.MongoClient; 3 import com.mongodb.client.MongoClients; 4 import com.mongodb.client.MongoCollection; 5 import com.mongodb.client.MongoCursor; 6 import com.mongodb.client.MongoDatabase; 7 import com.mongodb.client.model.SearchIndexModel; 8 import com.mongodb.client.model.SearchIndexType; 9 import org.bson.Document; 10 import org.bson.conversions.Bson; 11 12 import java.util.Arrays; 13 import java.util.Collections; 14 import java.util.List; 15 16 public 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 }
Replace the following values and save the file.
<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 thevector
type and thegenres
andyear
fields as thefilter
type in an Atlas Vector Search index.Specifies the
plot_embedding
field as the vector embeddings field, which contains embeddings created using OpenAI'stext-embedding-ada-002
embeddings model.Specifies
1536
vector dimensions and measures similarity usingeuclidean
distance.
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.
1 import com.mongodb.client.ListSearchIndexesIterable; 2 import com.mongodb.client.MongoClient; 3 import com.mongodb.client.MongoClients; 4 import com.mongodb.client.MongoCollection; 5 import com.mongodb.client.MongoCursor; 6 import com.mongodb.client.MongoDatabase; 7 import com.mongodb.client.model.SearchIndexModel; 8 import com.mongodb.client.model.SearchIndexType; 9 import org.bson.Document; 10 import org.bson.conversions.Bson; 11 12 import java.util.Collections; 13 import java.util.List; 14 15 public 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", "euclidean"))); 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.
1 import com.mongodb.client.ListSearchIndexesIterable; 2 import com.mongodb.client.MongoClient; 3 import com.mongodb.client.MongoClients; 4 import com.mongodb.client.MongoCollection; 5 import com.mongodb.client.MongoCursor; 6 import com.mongodb.client.MongoDatabase; 7 import com.mongodb.client.model.SearchIndexModel; 8 import com.mongodb.client.model.SearchIndexType; 9 import org.bson.Document; 10 import org.bson.conversions.Bson; 11 12 import java.util.Arrays; 13 import java.util.Collections; 14 import java.util.List; 15 16 public 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", "euclidean"), 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 }
To create an Atlas Vector Search index for a collection using the MongoDB Node driver v6.6.0 or later, perform the following steps:
Create a .js
file and define the index in the file.
1 const { MongoClient } = require("mongodb"); 2 3 // connect to your Atlas deployment 4 const uri = "<connectionString>"; 5 6 const client = new MongoClient(uri); 7 8 async 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 } 57 run().catch(console.dir);
Example
Create a file named vector-index.js
.
Replace the following values and save the file.
<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 euclidean
distance.
The following index definition indexes only the vector
embeddings field (plot_embedding
) for performing vector search.
1 const { MongoClient } = require("mongodb"); 2 3 // connect to your Atlas deployment 4 const uri = "<connectionString>"; 5 6 const client = new MongoClient(uri); 7 8 async 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": "euclidean" 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 } 53 run().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.
1 const { MongoClient } = require("mongodb"); 2 3 // connect to your Atlas deployment 4 const uri = "<connectionString>"; 5 6 const client = new MongoClient(uri); 7 8 async 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": "euclidean" 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 } 61 run().catch(console.dir);
To create an Atlas Vector Search index for a collection using the PyMongo driver v4.7 or later, perform the following steps:
Create a .py
file and define the index in the file.
1 import pymongo 2 from pymongo.mongo_client import MongoClient 3 from pymongo.operations import SearchIndexModel 4 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 model, then create the search index 14 search_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 34 result = collection.create_search_index(model=search_index_model) 35 print("New search index named " + result + " is building.") 36 37 # Wait for initial sync to complete 38 print("Polling to check if the index is ready. This may take up to a minute.") 39 predicate=None 40 if predicate is None: 41 predicate = lambda index: index.get("queryable") is True 42 43 while True: 44 indices = list(collection.list_search_indexes(result)) 45 if len(indices) and predicate(indices[0]): 46 break 47 time.sleep(5) 48 print(result + " is ready for querying.") 49 50 client.close()
To learn more, see the create_search_index() method.
1 from pymongo.mongo_client import MongoClient 2 from pymongo.operations import SearchIndexModel 3 4 def 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
.
Replace the following values and save the file.
<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 euclidean
distance.
The following index definition indexes only the vector
embeddings field (plot_embedding
) for performing
vector search.
1 from pymongo.mongo_client import MongoClient 2 from pymongo.operations import SearchIndexModel 3 import time 4 5 # Connect to your Atlas deployment 6 uri = "<connectionString>" 7 client = MongoClient(uri) 8 9 # Access your database and collection 10 database = client["sample_mflix"] 11 collection = database["embedded_movies"] 12 13 # Create your index model, then create the search index 14 search_index_model = SearchIndexModel( 15 definition={ 16 "fields": [ 17 { 18 "type": "vector", 19 "path": "plot_embedding", 20 "numDimensions": 1536, 21 "similarity": "euclidean" 22 } 23 ] 24 }, 25 name="vector_index", 26 type="vectorSearch", 27 ) 28 29 result = collection.create_search_index(model=search_index_model) 30 print("New search index named " + result + " is building.") 31 # Wait for initial sync to complete 32 print("Polling to check if the index is ready. This may take up to a minute.") 33 predicate=None 34 if predicate is None: 35 predicate = lambda index: index.get("queryable") is True 36 37 while True: 38 indices = list(collection.list_search_indexes(name)) 39 if len(indices) and predicate(indices[0]): 40 break 41 time.sleep(5) 42 print(result + " is ready for querying.") 43 44 client.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.
1 from pymongo.mongo_client import MongoClient 2 from pymongo.operations import SearchIndexModel 3 import time 4 5 # Connect to your Atlas deployment 6 uri = "<connectionString>" 7 client = MongoClient(uri) 8 9 # Access your database and collection 10 database = client["sample_mflix"] 11 collection = database["embedded_movies"] 12 13 # Create your index model, then create the search index 14 search_index_model = SearchIndexModel( 15 definition={ 16 "fields": [ 17 { 18 "type": "vector", 19 "path": "plot_embedding", 20 "numDimensions": 1536, 21 "similarity": "euclidean" 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 37 result = collection.create_search_index(model=search_index_model) 38 print("New search index named " + result + " is building.") 39 # Wait for initial sync to complete 40 print("Polling to check if the index is ready. This may take up to a minute.") 41 predicate=None 42 if predicate is None: 43 predicate = lambda index: index.get("queryable") is True 44 45 while True: 46 indices = list(collection.list_search_indexes(result)) 47 if len(indices) and predicate(indices[0]): 48 break 49 time.sleep(5) 50 print(result + " is ready for querying.") 51 52 client.close()
View an Atlas Vector Search Index
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.
Required Access
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.
Procedure
➤ 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.
1 curl --user "{PUBLIC-KEY}:{PRIVATE-KEY}" --digest \ 2 --header "Accept: application/json" \ 3 --include \ 4 --request GET "https://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.
1 curl --user "{PUBLIC-KEY}:{PRIVATE-KEY}" --digest \ 2 --header "Accept: application/json" \ 3 --include \ 4 --request GET "https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes/{indexId} | https://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:
Run the following command to retrieve the indexes for the collection.
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.
In Atlas, go to the Clusters page for your project.
If it's not already displayed, select the organization that contains your desired project from the Organizations menu in the navigation bar.
If it's not already displayed, select your desired project from the Projects menu in the navigation bar.
If it's not already displayed, click Clusters in the sidebar.
The Clusters page displays.
Go to the Atlas Search page for your cluster.
You can go the Atlas Search page from the sidebar, the Data Explorer, or your cluster details page.
In the sidebar, click Atlas Search under the Services heading.
From the Select data source dropdown, select your cluster and click Go to Atlas Search.
The Atlas Search page displays.
Click the Browse Collections button for your cluster.
Expand the database and select the collection.
Click the Search Indexes tab for the collection.
The Atlas Search page displays.
Click the cluster's name.
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:
|
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 |
To view an Atlas Vector Search index for a collection using mongosh
,
perform the following steps:
Connect to the Atlas cluster using mongosh
.
To learn more, see Connect via mongosh
.
Run the db.collection.getSearchIndexes()
method.
The db.collection.getSearchIndexes()
method has the
following syntax:
1 db.<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:
Create the .go
file and use the SearchIndexes().List()
method to retrieve the index.
1 package main 2 3 import ( 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 14 func 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 }
Replace the following values and save the file.
<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. |
To view an Atlas Vector Search index for a collection using the MongoDB Java driver v5.2.0 or later, perform the following steps:
Create a .java
file and use the listSearchIndexes()
method to retrieve the index.
1 import com.mongodb.client.MongoClient; 2 import com.mongodb.client.MongoClients; 3 import com.mongodb.client.MongoCollection; 4 import com.mongodb.client.MongoDatabase; 5 import org.bson.Document; 6 7 public 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 }
Replace the following values and save the file.
<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. |
To view an Atlas Vector Search index for a collection using MongoDB Node driver v6.6.0 or later, perform the following steps:
Create the .js
file and use the listSearchIndexes()
method to retrieve the index.
1 const { MongoClient } = require("mongodb"); 2 3 // connect to your Atlas deployment 4 const uri = "<connectionString>"; 5 6 const client = new MongoClient(uri); 7 8 async 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 } 20 run().catch(console.dir);
Replace the following values and save the file.
<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. |
To view Atlas Vector Search indexes for a collection using PyMongo driver v4.7 or later, perform the following steps:
Create a .py
file and use the list_search_indexes()
method to retrieve the indexes for the collection.
1 from pymongo.mongo_client import MongoClient 2 3 # Connect to your Atlas deployment 4 uri = "<connectionString>" 5 client = MongoClient(uri) 6 7 # Access your database and collection 8 database = client["<databaseName>"] 9 collection = database["<collectionName>"] 10 11 # Get a list of the collection's search indexes and print them 12 cursor = collection.list_search_indexes() 13 for index in cursor: 14 print(index)
To learn more, see the list_search_indexes() method.
Replace the following values and save the file.
<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. |
Edit an Atlas Vector Search Index
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.
Required Access
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.
Procedure
➤ 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.
1 curl --user "{PUBLIC-KEY}:{PRIVATE-KEY}" --digest --include \ 2 --header "Accept: application/json" \ 3 --header "Content-Type: application/json" \ 4 --request PATCH "https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes/{indexId} | https://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:
Create a .json
file and define the changes to the index in the file.
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 }
Replace the following placeholder values and save the file.
<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. |
Run the following command to update the index.
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.
In Atlas, go to the Clusters page for your project.
If it's not already displayed, select the organization that contains your desired project from the Organizations menu in the navigation bar.
If it's not already displayed, select your desired project from the Projects menu in the navigation bar.
If it's not already displayed, click Clusters in the sidebar.
The Clusters page displays.
Go to the Atlas Search page for your cluster.
You can go the Atlas Search page from the sidebar, the Data Explorer, or your cluster details page.
In the sidebar, click Atlas Search under the Services heading.
From the Select data source dropdown, select your cluster and click Go to Atlas Search.
The Atlas Search page displays.
Click the Browse Collections button for your cluster.
Expand the database and select the collection.
Click the Search Indexes tab for the collection.
The Atlas Search page displays.
Click the cluster's name.
Click the Atlas Search tab.
The Atlas Search page displays.
Edit the index.
Locate the
vectorSearch
type index to edit.Click Edit Index from the Actions dropdown for that index.
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.
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:
Connect to the Atlas cluster using mongosh
.
To learn more, see Connect via mongosh
.
Run the db.collection.updateSearchIndex()
method.
The db.collection.updateSearchIndex()
method has the
following syntax:
1 db.<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:
Create the go
file and define the index changes in the file.
1 package main 2 3 import ( 4 "context" 5 "fmt" 6 "log" 7 8 "go.mongodb.org/mongo-driver/mongo" 9 "go.mongodb.org/mongo-driver/mongo/options" 10 ) 11 12 func 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 }
Replace the following values and save the file.
<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. |
To edit an Atlas Vector Search index for a collection using the MongoDB Java driver v5.2.0 or later, perform the following steps:
Create the .java
file and define the index changes in the file.
1 import com.mongodb.client.MongoClient; 2 import com.mongodb.client.MongoClients; 3 import com.mongodb.client.MongoCollection; 4 import com.mongodb.client.MongoDatabase; 5 import org.bson.Document; 6 import org.bson.conversions.Bson; 7 8 import java.util.Collections; 9 10 public 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 }
Replace the following values and save the file.
<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. |
To update an Atlas Vector Search index for a collection using the MongoDB Node driver v6.6.0 or later, perform the following steps:
Create the .js
file and define the index changes in the file.
1 const { MongoClient } = require("mongodb"); 2 3 // connect to your Atlas deployment 4 const uri = "<connection-string>"; 5 6 const client = new MongoClient(uri); 7 8 async 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 } 41 run().catch(console.dir);
Replace the following values and save the file.
<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. |
To update an Atlas Vector Search index for a collection using the PyMongo driver v4.7 or later, perform the following steps:
Create the .py
file and define the index changes in the file.
1 from pymongo.mongo_client import MongoClient 2 3 # Connect to your Atlas deployment 4 uri = "<connectionString>" 5 client = MongoClient(uri) 6 7 # Access your database and collection 8 database = client["<databaseName>"] 9 collection = database["<collectionName>"] 10 11 definition = { 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 28 collection.update_search_index("<indexName>", definition)
To learn more, see the update_search_index() method.
Replace the following values and save the file.
<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. |
Delete an Atlas Vector Search Index
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.
Required Access
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.
Procedure
➤ 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.
1 curl --user "{PUBLIC-KEY}:{PRIVATE-KEY}" --digest \ 2 --header "Accept: application/json" \ 3 --include \ 4 --request DELETE "https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes/{indexId} | https://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:
Run the command to delete the index.
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.
In Atlas, go to the Clusters page for your project.
If it's not already displayed, select the organization that contains your desired project from the Organizations menu in the navigation bar.
If it's not already displayed, select your desired project from the Projects menu in the navigation bar.
If it's not already displayed, click Clusters in the sidebar.
The Clusters page displays.
Go to the Atlas Search page for your cluster.
You can go the Atlas Search page from the sidebar, the Data Explorer, or your cluster details page.
In the sidebar, click Atlas Search under the Services heading.
From the Select data source dropdown, select your cluster and click Go to Atlas Search.
The Atlas Search page displays.
Click the Browse Collections button for your cluster.
Expand the database and select the collection.
Click the Search Indexes tab for the collection.
The Atlas Search page displays.
Click the cluster's name.
Click the Atlas Search tab.
The Atlas Search page displays.
To delete an Atlas Vector Search index for a collection using mongosh
,
perform the following steps:
Connect to the Atlas cluster using mongosh
.
To learn more, see Connect via mongosh
.
Run the db.collection.dropSearchIndex()
method.
The db.collection.dropSearchIndex()
method has the
following syntax:
1 db.<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:
Create the .go
file and use the SearchIndexes().DropOne()
method to delete the index.
1 package main 2 3 import ( 4 "context" 5 "fmt" 6 "log" 7 8 "go.mongodb.org/mongo-driver/mongo" 9 "go.mongodb.org/mongo-driver/mongo/options" 10 ) 11 12 func 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 }
Replace the following values and save the file.
<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 . |
To delete an Atlas Vector Search index for a collection using the MongoDB Java driver v5.2.0 or later, perform the following steps:
Create the .java
file and use the collection.dropSearchIndex()
method to delete the index.
1 import com.mongodb.client.MongoClient; 2 import com.mongodb.client.MongoClients; 3 import com.mongodb.client.MongoCollection; 4 import com.mongodb.client.MongoDatabase; 5 import org.bson.Document; 6 7 public 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 }
Replace the following values and save the file.
<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 . |
To delete an Atlas Vector Search index for a collection using MongoDB Node driver v6.6.0 or later, perform the following steps:
Create the .js
file and use the dropSearchIndex()
method to delete the index.
1 const { MongoClient } = require("mongodb"); 2 3 // connect to your Atlas deployment 4 const uri = "<connectionString>"; 5 6 const client = new MongoClient(uri); 7 8 async 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 } 20 run().catch(console.dir);
Replace the following values and save the file.
<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 . |
To delete an Atlas Vector Search index for a collection using PyMongo driver v4.7 or later, perform the following steps:
Create the .py
file and use the drop_search_index()
method to delete the index.
1 from pymongo.mongo_client import MongoClient 2 3 # Connect to your Atlas deployment 4 uri = "<connectionString>" 5 client = MongoClient(uri) 6 7 # Access your database and collection 8 database = client["<databaseName>"] 9 collection = database["<collectionName>"] 10 11 # Delete your search index 12 collection.drop_search_index("<indexName>")
To learn more, see the drop_search_index() method.
Replace the following values and save the file.
<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. |
Index Status
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:
|
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.