vector-type
For the complete MongoDB documentation index, see www.mongodb.com/docs/llms.txt
<!-- Tab options on this page. Append to the .md URL to filter: ?tabs=<id,...> select specific tabs (e.g. ?tabs=nodejs,shell) ?allTabs=true include every tab (no param) default: one tab per tabset
Available tabs: other tabs: vib, jsonib, cloud, local, maven bom, gradle bom, maven, gradle -->
How to Index Vector Fields
You can use the vector type to index vector embeddings. The vector field must contain an array of [numbers](https://www.mongodb.com/docs/search/indexes/field-types/number-type.md#std-label-bson-data-types-number of the following types:
-
BSON (Binary Javascript Object Notation)
int32,int64, ordoubledata types -
BSON (Binary Javascript Object Notation)
doubledata type
You can use the [vectorSearch](https://www.mongodb.com/docs/search/query/operators-collectors/vectorsearch.md#std-label-fts-vectorSearch-ref operator, similar to the [$vectorSearch](https://www.mongodb.com/docs/vector-search/query/aggregation-stages/vector-search-stage.md#mongodb-pipeline-pipe.-vectorSearch stage, in your [$search](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search aggregation pipeline to query fields indexed as the vector type.
vector Type Limitations
The following limitations apply:
-
You can't index fields with arrays of objects (MongoDB Search
embeddedDocumentstype) asvectortype. -
You can't set [storedSource](https://www.mongodb.com/docs/search/indexes/stored-source-definition.md#std-label-fts-stored-source-definition to
truein index definitions that containvectortype. Instead, useincludeto specify the fields to store onmongotor useexcludeto exclude thevectortype field from storage. -
You can't use the [
$vectorSearch](https://www.mongodb.com/docs/vector-search/query/aggregation-stages/vector-search-stage.md#mongodb-pipeline-pipe.-vectorSearch stage to query fields indexed as thevectortype. -
You can index fields as the
vectortype in the MongoDB Search Playground.
Define the Index for the vector Type
- Retrieve your Service Account access token for the project.
Use your service account to generate an access token, which authenticates your requests to the Atlas Administration API. To learn how to generate an access token, see [Make an API (Application Programming Interface) Request.](https://www.mongodb.com/docs/atlas/configure-api-access.md#std-label-example-api-request
- Make an API (Application Programming Interface) call.
Replace the following values in the curl command below. This command sends a POST request to your cluster to create a MongoDB Search index with the vector field type.
-
Replace {
ACCESS-TOKEN} with the output from the preceding step -
Replace {
groupId} with the project ID of the project where you want to create the MongoDB Search index -
Replace {
clusterName} with the name of the cluster where you want to create the MongoDB Search index
shell
curl --header "Authorization: Bearer ${ACCESS_TOKEN}" \
--header "Accept: application/vnd.atlas.2025-03-12+json" \
--header "Content-Type: application/json" \
-X POST "https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes" \
-d '{ "collectionName": "<collection>",
"database": "<database>",
"name": "default",
"type": "search",
"definition": {
"mappings": {
"dynamic": true|false,
"fields": {
"<field-name>": {
"type": "vector",
"numDimensions": <number-of-dimensions>,
"similarity": "euclidean | cosine | dotProduct",
"quantization": "none | scalar | binary",
"indexingMethod": "flat | hnsw",
"hnswOptions": {
"maxEdges": <number-of-connected-neighbors>,
"numEdgeCandidates": <number-of-nearest-neighbors>
}
}
}
}
}
}'
1) Create a search-index.json configuration file and specify the vector type.
json
{
"name": "default",
"collectionName": "<collection>",
"database": "<database>",
"definition": {
"mappings": {
"dynamic": true|false,
"fields": {
"<field-name>": {
"type": "token",
"normalizer": "lowercase|none"
}
}
}
}
}
2) Connect to the Atlas CLI
In your terminal, connect to your cluster from the Atlas CLI. To learn more, see Connect from the Atlas CLI.
3) Create a MongoDB Search index.
Run the atlas clusters search indexes create command in your terminal, replacing <clusterName> with the name of the cluster, and <path-to-file> with the path to the search-index.json file:
shell
atlas clusters search indexes create --clusterName <cluster-name> --file <path-to-file>
- Connect to your cluster using MongoDB Compass.
Open Compass and connect to your cluster. For detailed instructions, see [Connect to a Cluster via Compass.](https://www.mongodb.com/docs/atlas/compass-connection.md#std-label-atlas-connect-via-compass
- Specify the database and collection.
On the Database screen, click the name of the database, then click the name of the collection.
- Create the MongoDB Search index.
Click the Indexes tab, then select Search Indexes.
Click Create Atlas Search Index to open the index creation dialog box.
Specify a name for the index.
Your MongoDB Search index is named default by default. If you keep this name, then your index will be the default Search index for any MongoDB Search query that does not specify a different index option in its [operators](https://www.mongodb.com/docs/search/query/operators-collectors/overview.md#std-label-fts-operators. If you are creating multiple indexes, we recommend that you maintain a consistent, descriptive naming convention across your indexes.
Specify the JSON (Javascript Object Notation) MongoDB Search index definition.
json
{
"mappings": {
"dynamic": true|false,
"fields": {
"<field-name>": {
"type": "vector",
"numDimensions": <number-of-dimensions>,
"similarity": "euclidean | cosine | dotProduct",
"quantization": "none | scalar | binary",
"indexingMethod": "flat | hnsw",
"hnswOptions": {
"maxEdges": <number-of-connected-neighbors>,
"numEdgeCandidates": <number-of-nearest-neighbors>
}
},
...
}
}
}
Click Create Search Index.
1) Connect to the deployment by using mongosh.
In your terminal, connect to your Atlas cloud-hosted deployment or local deployment from [mongosh](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh. For detailed instructions on how to connect, see Connect to a Deployment.
2) Switch to the database that contains the collection for which you want to create the index.
shell
use <database>
Output:
shell
switched to db <database>
3) Run the db.collection.createSearchIndex() method to create the index.
shell
db.<collection>.createSearchIndex(
"default",
{
"mappings": {
"dynamic": true|false,
"fields": {
"<field-name>": {
"type": "vector",
"numDimensions": <number-of-dimensions>,
"similarity": "euclidean | cosine | dotProduct",
"quantization": "none | scalar | binary",
"indexingMethod": "flat | hnsw",
"hnswOptions": {
"maxEdges": <number-of-connected-neighbors>,
"numEdgeCandidates": <number-of-nearest-neighbors>
}
},
...
}
}
}
)
Output:
text
default
Choose your preferred configuration method in the Atlas UI and then select the database and collection.
Visual Editor
You can't create an index for vector field type from the Atlas UI Visual Editor. Instead, use the JSON Editor.
- Set up the C project.
In your terminal, navigate to where you want to create your application, then run the following command to create a directory called atlas-search-project for this project:
shell
# Create a new directory for the project
mkdir atlas-search-project && cd atlas-search-project
Add the C driver to your project by following the instructions in the MongoDB C Driver documentation.
- Define the index.
Create a create_index.c file in your project directory, and copy and paste the following code into the file.
```c
#include
int main (void) { mongoc_client_t client = NULL; mongoc_collection_t collection = NULL; mongoc_database_t *database = NULL; bson_error_t error; bson_t cmd = BSON_INITIALIZER; bool ok = true;
mongoc_init();
// Connect to your Atlas deployment
client = mongoc_client_new("<connectionString>");
if (!client) {
fprintf(stderr, "Failed to create a MongoDB client.\n");
ok = false;
goto cleanup;
}
// Access your database and collection
database = mongoc_client_get_database(client, "<databaseName>");
collection = mongoc_database_get_collection(database, "<collectionName>");
// Specify the command and the new index
const char *cmd_str = BSON_STR({
"createSearchIndexes" : "<collectionName>",
"indexes" : [ {
"name" : "default",
"definition" : {
"mappings": {
"dynamic": true|false,
"fields": {
"<field-name>" : {
"type": "vector",
"numDimensions": "<number-of-dimensions>",
"similarity": "euclidean | cosine | dotProduct",
"quantization": "none | scalar | binary",
"indexingMethod": "flat | hnsw",
"hnswOptions": {
"maxEdges": "<number-of-connected-neighbors>",
"numEdgeCandidates": "<number-of-nearest-neighbors>"
}
}
}
},
}
} ]
});
// Convert your command to BSON
if (!bson_init_from_json(&cmd, cmd_str, -1, &error)) {
fprintf(stderr, "Failed to parse command: %s\n", error.message);
ok = false;
goto cleanup;
}
// Create the MongoDB Search index by running the command
if (!mongoc_collection_command_simple (collection, &cmd, NULL, NULL, &error)) {
fprintf(stderr, "Failed to run createSearchIndexes: %s\n", error.message);
ok = false;
goto cleanup;
}
printf ("Index created!\n");
cleanup: mongoc_collection_destroy (collection); mongoc_client_destroy (client); mongoc_database_destroy (database); bson_destroy (&cmd); mongoc_cleanup (); return ok ? EXIT_SUCCESS : EXIT_FAILURE; }
```
Replace <connection-string> with the connection string for your Atlas cluster or local Atlas deployment.
To learn more about finding your connection string, see [Connect to a Cluster via Client Libraries.](https://www.mongodb.com/docs/atlas/driver-connection.md#std-label-connect-via-driver
Note:
For a local or self-managed deployment, your connection string should use the following format:
text
mongodb://localhost:<port-number>/?directConnection=true
To learn more, see [Connection Strings.](https://www.mongodb.com/docs/manual/reference/connection-string.md#std-label-mongodb-uri
- Set up a CMake application
To configure your application, create a CMakeLists.txt file in your project directory. Then, add the following code to the file:
```txt
cmake_minimum_required(VERSION 3.11)
project(atlas-search-index LANGUAGES C)
add_executable (index.out create_index.c)
find_package(mongoc
```
The preceding code performs the following actions:
-
Configures a C project.
-
Creates a
index.outexecutable for your application. -
Finds and requires the C driver. Replace the
<version>placeholder with your C driver version token, such as2.0.0. -
Links the program to the
libmongoclibrary.
Note:
In the sample CMakeLists.txt file, the mongoc::mongoc target points to either the static library or the shared library. The library type depends on which one is available and whichever type the user specifies in the MONGOC_DEFAULT_IMPORTED_LIBRARY_TYPE CMake configuration setting. If you don't set this value and both library types are available, mongoc::mongoc uses the static library.
You can use the mongoc::static target to explicitly use the static library or the mongoc::shared target to use the shared library.
- Create the index.
In your terminal, run the following commands to build and run this application:
shell
cmake -S. -Bcmake-build
cmake --build cmake-build --target index.out
./cmake-build/index.out
Output:
text
Index created!
1) Set up and initialize the .NET/C# project.
In your terminal, navigate to where you want to create your application, then run the following command to create a directory called atlas-search-project and initialize your project in that directory:
```shell # Create a new directory and initialize the project mkdir atlas-search-project && cd atlas-search-project dotnet new console
# Add the MongoDB .NET/C# Driver to your project dotnet add package MongoDB.Driver ```
For more detailed installation instructions, see the MongoDB .NET/C# Driver documentation.
2) Define the index.
Paste the following code into the Program.cs file.
```csharp using MongoDB.Bson; using MongoDB.Driver;
// connect to your Atlas deployment
var uri = "
var client = new MongoClient(uri);
var db = client.GetDatabase("
// define your MongoDB Search index
var index = new CreateSearchIndexModel(
"default", new BsonDocument
{
{ "mappings", new BsonDocument
{
{ "dynamic", true|false },
{ "fields", new BsonDocument
{
{ "
var result = collection.SearchIndexes.CreateOne(index); Console.WriteLine($"New index name: {result}"); ```
Replace <connection-string> with the connection string for your Atlas cluster or local Atlas deployment.
To learn more about finding your connection string, see [Connect to a Cluster via Client Libraries.](https://www.mongodb.com/docs/atlas/driver-connection.md#std-label-connect-via-driver
Note:
For a local or self-managed deployment, your connection string should use the following format:
text
mongodb://localhost:<port-number>/?directConnection=true
To learn more, see [Connection Strings.](https://www.mongodb.com/docs/manual/reference/connection-string.md#std-label-mongodb-uri
3) Create the index.
shell
dotnet run Program.cs
Output:
text
New index name: default
- Set up the C++ project.
In your terminal, navigate to where you want to create your application, then run the following command to create a directory called atlas-search-project for this project:
shell
# Create a new directory for the project
mkdir atlas-search-project && cd atlas-search-project
For more detailed installation instructions, see the MongoDB C++ Driver documentation.
- Define the index.
Create a CreateIndex.cpp file in your project directory, and copy and paste the following code into the file.
```cpp
#include
#include
using bsoncxx::builder::basic::kvp; using bsoncxx::builder::basic::make_document;
int main(){
mongocxx::instance instance;
mongocxx::uri uri("<connection string>");
mongocxx::client client(uri);
auto db = client["<database>"];
auto collection = db["<collection>"];
// instantiate a ``mongocxx::search_index_view`` on your collection
auto siv = collection.search_indexes();
{
auto name = "default";
auto definition = make_document(
kvp("mappings", make_document(
kvp("dynamic", true|false),
kvp("fields", make_document(
kvp("<field-name>", make_document(
kvp("type", "vector"),
kvp("numDimensions", "<number-of-dimensions>"),
kvp("similarity", "euclidean | cosine | dotProduct"),
kvp("quantization", "none | scalar | binary"),
kvp("indexingMethod", "flat | hnsw"),
kvp("hnswOptions", make_document(
kvp("maxEdges", "<number-of-connected-neighbors>"),
kvp("numEdgeCandidates", "<number-of-nearest-neighbors>")
))
))
))
))
);
auto model = mongocxx::search_index_model(name, definition.view());
// Create the search index
auto result = siv.create_one(model);
std::cout << "New index name: " << result << std::endl;
}
} ```
Replace <connection-string> with the connection string for your Atlas cluster or local Atlas deployment.
To learn more about finding your connection string, see [Connect to a Cluster via Client Libraries.](https://www.mongodb.com/docs/atlas/driver-connection.md#std-label-connect-via-driver
Note:
For a local or self-managed deployment, your connection string should use the following format:
text
mongodb://localhost:<port-number>/?directConnection=true
To learn more, see [Connection Strings.](https://www.mongodb.com/docs/manual/reference/connection-string.md#std-label-mongodb-uri
- Create the index.
shell
c++ --std=c++17 CreateIndex.cpp $(pkg-config --cflags --libs libmongocxx) -o ./app.out
./app.out
Output:
text
New index name: default
Tip: MacOS Error
MacOS users might see the following error after running the preceding commands:
sh
dyld[54430]: Library not loaded: @rpath/libmongocxx._noabi.dylib
To resolve this error, use the -Wl,``-rpath`` linker option to set the @rpath, as shown in the following code:
sh
c++ --std=c++17 CreateIndex.cpp -Wl,-rpath,/usr/local/lib/ $(pkg-config --cflags --libs libmongocxx) -o ./app.out
./app.out
1) Set up and initialize the Go module.
In your terminal, navigate to where you want to create your application, then run the following command to create a directory called atlas-search-project and initialize your project in that directory:
```shell # Create a new directory and initialize the project mkdir atlas-search-project && cd atlas-search-project go mod init atlas-search-project
# Add the MongoDB Go Driver to your project go get go.mongodb.org/mongo-driver/v2/mongo ```
For more detailed installation instructions, see the [MongoDB Go Driver documentation.](https://www.mongodb.com/docs/drivers/go/current/get-started.md#std-label-go-get-started
2) Define the index.
Create a create_index.go file in your project directory, and copy and paste the following code into the file.
```go package main
import ( "context" "fmt" "log"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
)
func main() {
ctx := context.Background()
uri := "
defer func() {
if err := client.Disconnect(context.TODO()); err != nil {
panic(err)
}
}()
coll := client.Database("<database>").Collection("<collection>")
const indexName = "default"
opts := options.SearchIndexes().SetName(indexName).SetType("search")
// Define the MongoDB Search index for the vector field
searchIndexModel := mongo.SearchIndexModel{
Definition: bson.D{
{"mappings", bson.D{
{"dynamic", false},
{"fields", bson.D{
{"<field-name>", bson.D{
{"type", "vector"},
{"numDimensions", "<number-of-dimensions>"},
{"similarity", "euclidean | cosine | dotProduct"},
{"quantization", "none | scalar | binary"},
{"indexingMethod", "flat | hnsw"},
{"hnswOptions", bson.D{
{"maxEdges", "<number-of-connected-neighbors>"},
{"numEdgeCandidates", "<number-of-nearest-neighbors>"},
}},
}},
}},
}},
},
Options: opts,
}
// Create the index
searchIndexName, err := coll.SearchIndexes().CreateOne(ctx, searchIndexModel)
if err != nil {
log.Fatalf("Failed to create the Atlas Search index: %v", err)
}
fmt.Println("Name of index created: " + searchIndexName)
}
```
Replace <connection-string> with the connection string for your Atlas cluster or local Atlas deployment.
### Atlas Cluster
Your connection string should use the following format:
text
mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net
IMPORTANT: Ensure that your connection string includes your database user's credentials. To learn more about finding your connection string, see [Connect to a Cluster via Client Libraries.](https://www.mongodb.com/docs/atlas/driver-connection.md#std-label-connect-via-driver
3) Create the index.
shell
go run create_index.go
Output:
text
New index name: default
- Set up your Java project with the MongoDB Java driver.
In your IDE, create a new Maven or Gradle project. Add the Bill of Materials (BOM) for MongoDB JVM artifacts to your project to organize dependency versions. The BOM simplifies dependency management by ensuring that you maintain consistent and compatible versions of dependencies, such as between the Java driver and the core driver library. Use the BOM to avoid version conflicts and simplify upgrades.
Select from the following Maven and Gradle tabs to view instructions for adding the BOM for each dependency manager:
### Maven
Add the following code to the dependencyManagement list in your pom.xml file:
xml
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-bom</artifactId>
<version>5.5.1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
To view a list of dependencies that the BOM manages, see the mongodb-driver-bom dependency listing on the Maven Repository website.
After adding the BOM, select from the following Maven and Gradle tabs to view instructions for adding the MongoDB Java Sync Driver as a dependency in your project:
### Maven
Add the following code to the dependencies array in your Maven project's pom.xml file:
```xml
```
Run your package manager to install the dependencies to your project.
For more detailed installation instructions and version compatibility, see the MongoDB Java Driver documentation.
- Define the index.
In your project's base package directory, create a CreateIndex.java file and copy and paste the following code into this file.
```java import com.mongodb.client.MongoClient; import com.mongodb.client.MongoClients; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import org.bson.Document;
public class CreateIndex {
public static void main(String[] args) {
// connect to your Atlas cluster
String uri = "
try (MongoClient mongoClient = MongoClients.create(uri)) {
// set namespace
MongoDatabase database = mongoClient.getDatabase("<database>");
MongoCollection<Document> collection = database.getCollection("<collection>");
Document index = new Document("mappings",
new Document("dynamic", true|false)
.append("fields", new Document("<field-name>",
new Document("type", "vector")
.append("numDimensions", "<number-of-dimensions>")
.append("similarity", "euclidean | cosine | dotProduct")
.append("quantization", "none | scalar | binary")
.append("indexingMethod", "flat | hnsw")
.append("hnswOptions", new Document("maxEdges", "<number-of-connected-neighbors>")
.append("numEdgeCandidates", "<number-of-nearest-neighbors>"))
)));
String result = collection.createSearchIndex(index);
System.out.println("New index name: " + result);
}
}
} ```
Replace <connection-string> with the connection string for your Atlas cluster or local Atlas deployment.
To learn more about finding your connection string, see [Connect to a Cluster via Client Libraries.](https://www.mongodb.com/docs/atlas/driver-connection.md#std-label-connect-via-driver
Note:
For a local or self-managed deployment, your connection string should use the following format:
text
mongodb://localhost:<port-number>/?directConnection=true
To learn more, see [Connection Strings.](https://www.mongodb.com/docs/manual/reference/connection-string.md#std-label-mongodb-uri
- Compile and run the file to create the index.
Compile and run your application in your IDE or your shell.
shell
javac CreateIndex.java
java CreateIndex
Output:
text
New index name: default
1) Initialize your Node.js project.
```shell # Create a new directory and initialize the project mkdir atlas-search-project && cd atlas-search-project npm init -y
# Add the MongoDB Node.js Driver to your project npm install mongodb ```
For detailed installation instructions, see the MongoDB Node Driver documentation.
2) Define the index.
Create a create-index.js file in your project directory, and copy and paste the following code into the file.
```javascript import { MongoClient } from 'mongodb';
// connect to your Atlas deployment
const uri =
"
const client = new MongoClient(uri);
async function run() { try {
// set namespace
const database = client.db("<database>");
const collection = database.collection("<collection>");
// define your MongoDB Search index
const index = {
name: "default",
definition: {
/* search index definition fields */
"mappings": {
"dynamic": true|false,
"fields": {
"<field-name>": {
"type": "vector",
"numDimensions": "<number-of-dimensions>",
"similarity": "euclidean | cosine | dotProduct",
"quantization": "none | scalar | binary",
"indexingMethod": "flat | hnsw",
"hnswOptions": {
"maxEdges": "<number-of-connected-neighbors>",
"numEdgeCandidates": "<number-of-nearest-neighbors>"
}
}
}
}
}
}
// run the helper method
const result = await collection.createSearchIndex(index);
console.log("New index name: " + result);
} finally {
await client.close();
}
}
run().catch(console.dir); ```
Replace <connection-string> with the connection string for your Atlas cluster or local Atlas deployment.
To learn more about finding your connection string, see [Connect to a Cluster via Client Libraries.](https://www.mongodb.com/docs/atlas/driver-connection.md#std-label-connect-via-driver
Note:
For a local or self-managed deployment, your connection string should use the following format:
text
mongodb://localhost:<port-number>/?directConnection=true
To learn more, see [Connection Strings.](https://www.mongodb.com/docs/manual/reference/connection-string.md#std-label-mongodb-uri
3) Create the index.
shell
node create-index.js
Output:
text
New index name: default
- Set up the Python project.
```shell # Create a new directory for the project mkdir atlas-search-project && cd atlas-search-project
# Install PyMongo pip install pymongo ```
For detailed installation instructions, see [MongoDB Python Driver (PyMongo).](https://www.mongodb.com/docs/languages/python/pymongo-driver/get-started.md#std-label-pymongo-get-started-download-and-install
- Define the index.
Create a create_index.py file in your project directory, and copy and paste the following code into the file.
```python from pymongo import MongoClient from pymongo.operations import SearchIndexModel
# connect to your Atlas deployment
uri = "
# set namespace
database = client["
# define your MongoDB Search index
search_index_model = SearchIndexModel(
definition={
"mappings": {
"dynamic": true|false,
"fields": {
"
# create the index result = collection.create_search_index(model=search_index_model) print(f"New index name: {result}") ```
Replace <connection-string> with the connection string for your Atlas cluster or local Atlas deployment.
To learn more about finding your connection string, see [Connect to a Cluster via Client Libraries.](https://www.mongodb.com/docs/atlas/driver-connection.md#std-label-connect-via-driver
Note:
For a local or self-managed deployment, your connection string should use the following format:
text
mongodb://localhost:<port-number>/?directConnection=true
To learn more, see [Connection Strings.](https://www.mongodb.com/docs/manual/reference/connection-string.md#std-label-mongodb-uri
- Create the index.
shell
python create_index.py
Output:
text
New index name: default
Configure vector Field Properties
Configure vector Field Properties
The MongoDB Search vector type takes the following parameters:
| Option | Type | Necessity | Description |
|---|---|---|---|
type |
vector |
Required | Human-readable label that identifies this field type. Value must be vector. |
numDimensions |
Int | Required | Number of vector dimensions that MongoDB Search enforces at index-time and query-time. You can set this field only for vector-type fields. You must specify a value less than or equal to 8192. For indexing quantized vectors or [BinData](https://www.mongodb.com/docs/manual/reference/method/BinData.md#std-label-server-binData-method, you can specify one of the following values: 1 to 8192 for int8 vectors for ingestion.; Multiple of 8 for int1 vectors for ingestion.; 1 to 8192 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. The embedding model you choose determines the number of dimensions in your vector embeddings, with some models having multiple options for how many dimensions are output. To learn more, see [Choosing a Method to Create Embeddings.](https://www.mongodb.com/docs/vector-search/crud-embeddings/create-embeddings-manual.md#std-label-choose-embedding-method |
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. You can specify one of the following values: 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.](https://www.mongodb.com/docs/vector-search/indexes/vector-search-type.md#std-label-avs-similarity-functions |
quantization |
String | Optional | Type of automatic vector quantization for your vectors. Use this setting only if your embeddings are float or double vectors. You can specify one of the following values: 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 value, numDimensions must be a multiple of 8.If precision is critical, select none or scalar instead of binary. To learn more, see [About Quantization.](https://www.mongodb.com/docs/vector-search/indexes/vector-search-type.md#std-label-avs-quantization |
indexingMethod |
String | Optional | Index structure for the vector field. Value can be: hnsw - for graph-based index where similar vectors are connected; flat - for flat, non-graph, index If omitted, defaults to hnsw. If you specify hnsw, MongoDB Vector Search performs ANN (Approximate Nearest Neighbor) search over the Hierarchical Navigable Small Worlds graph and ENN (Exact Nearest Neighbor) search over full-fidelity vectors. You can also specify hnswOptions. If you specify flat, MongoDB Vector Search performs a full scan over full-fidelity or quantized vectors. During an ANN (Approximate Nearest Neighbor) search, MongoDB Vector Search ignores the settings for numCandidates. For ENN (Exact Nearest Neighbor) search, MongoDB Vector Search performs a full scan over full-fidelity vectors. |
hnswOptions |
Object | Optional | Parameters to use for Hierarchical Navigable Small Worlds graph construction. If omitted, uses the default values for the maxEdges and numEdgeCandidates parameters. IMPORTANT: This is available as a Preview feature. Modifying the default values might negatively impact your MongoDB Search index and queries. |
hnswOptions.``maxEdges |
Int | Optional | Maximum number of edges (or connections) that a node can have in the Hierarchical Navigable Small Worlds graph. Value can be between 16 and 64, both inclusive. If omitted, defaults to 16. For example, for a value of 16, each node can have a maximum of sixteen outgoing edges at each layer of the Hierarchical Navigable Small Worlds graph. A higher number improves :recall (accuracy of search results) because the graph is better connected. However, this also increases query and indexing time by increasing the number of neighbors to evaluate per graph node, and requires more memory to store the additional nodes for each connection in the Hierarchical Navigable Small Worlds graph. |
hnswOptions.``numEdgeCandidates |
Int | Optional | Analogous to numCandidates at query-time, this parameter controls the maximum number of nodes to evaluate to find the closest neighbors to connect to a new node. Value can be between 100 and 3200, both inclusive. If omitted, defaults to 100. A higher number provides a graph with high-quality connections, which can improve search quality (recall), but it can also increase query latency. |
Try an Example for the vector Type
The following index definition example uses the sample_mflix.embedded_movies collection in the [sample data](https://www.mongodb.com/docs/atlas/import/load-sample-data.md#std-label-sample-data. After you load the collection, you can use the following example to index the plot_embedding_voyage_3_large field as the vector type for running queries using the [vectorSearch (MongoDB Search Operator)](https://www.mongodb.com/docs/search/query/operators-collectors/vectorsearch.md#std-label-fts-vectorSearch-ref. For a sample query to run against this index, see [Examples.](https://www.mongodb.com/docs/search/query/operators-collectors/vectorsearch.md#std-label-fts-vectorSearch-egs
This index definition automatically indexes all the [dynamically](https://www.mongodb.com/docs/search/indexes/define-field-mappings.md#std-label-fts-dynamic-mappings indexable fields using the [default](https://www.mongodb.com/docs/search/indexes/define-field-mappings.md#std-label-fts-enable-dynamic-mappings typeSet and also indexes the plot_embedding_voyage_3_large field as vector type with the following settings:
-
2048number of dimensions -
dotProductsimilarity function -
scalarquantization -
hnsw(default) indexing method
curl --header "Authorization: Bearer ${ACCESS_TOKEN}" \
--header "Accept: application/vnd.atlas.2025-03-12+json" \
--header "Content-Type: application/json" \
-X POST "https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes" \
-d '{ "collectionName": "embedded_movies",
"database": "sample_mflix",
"name": "default",
"type": "search",
"definition": {
"mappings": {
"dynamic": true,
"fields": {
"plot_embedding_voyage_3_large": {
"numDimensions": 2048,
"quantization": "scalar",
"similarity": "dotProduct",
"type": "vector"
}
}
}
}
}'
Output:
{"collectionName":"embedded_movies","database":"sample_mflix","indexID":"687a8ce25532743c25aa2d34","latestDefinition":{"mappings":{"dynamic":true,"fields":{"plot_embedding_voyage_3_large":{"numDimensions":2048,"quantization":"scalar","similarity":"dotProduct","type":"vector"}}}},"latestDefinitionVersion":{"version":0},"name":"default","queryable":false,"status":"PENDING","type":"search"}
{
"name": "default",
"collectionName": "embedded_movies",
"database": "sample_mflix",
"definition": {
"mappings": {
"dynamic": true,
"fields": {
"plot_embedding_voyage_3_large": {
"numDimensions": 2048,
"quantization": "scalar",
"similarity": "dotProduct",
"type": "vector"
}
}
}
}
}
{
"mappings": {
"dynamic": true,
"fields": {
"plot_embedding_voyage_3_large": {
"numDimensions": 2048,
"quantization": "scalar",
"similarity": "dotProduct",
"type": "vector"
}
}
}
}
db.embedded_movies.createSearchIndex(
"default",
{
"mappings": {
"dynamic": true,
"fields": {
"plot_embedding_voyage_3_large": {
"numDimensions": 2048,
"quantization": "scalar",
"similarity": "dotProduct",
"type": "vector"
}
}
}
}
)
{
"mappings": {
"dynamic": true,
"fields": {
"plot_embedding_voyage_3_large": {
"numDimensions": 2048,
"quantization": "scalar",
"similarity": "dotProduct",
"type": "vector"
}
}
}
}
```c
include <mongoc/mongoc.h>
include <stdlib.h>
int main (void) { mongoc_client_t client = NULL; mongoc_collection_t collection = NULL; mongoc_database_t *database = NULL; bson_error_t error; bson_t cmd = BSON_INITIALIZER; bool ok = true;
mongoc_init();
// Connect to your Atlas deployment
client = mongoc_client_new("<connectionString>");
if (!client) {
fprintf(stderr, "Failed to create a MongoDB client.\n");
ok = false;
goto cleanup;
}
// Access your database and collection
database = mongoc_client_get_database(client, "sample_mflix");
collection = mongoc_database_get_collection(database, "embedded_movies");
// Specify the command and the new index
const char *cmd_str = BSON_STR({
"createSearchIndexes" : "movies",
"indexes" : [ {
"name" : "default",
"definition" : {
"mappings": {
"dynamic": true,
"fields": {
"plot_embedding_voyage_3_large" : {
"numDimensions": 2048,
"quantization": "scalar",
"sim
(本文超出站点单文档体积上限,已截断)
