vector-search-with-rankfusion
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: cloud, local, maven, gradle, similar-terms-same-field, same-term-multiple-fields, same-term-multiple-models -->
How to Combine Multiple $vectorSearch Queries
The MongoDB $rankFusion aggregation stage supports [$vectorSearch](https://www.mongodb.com/docs/vector-search/query/aggregation-stages/vector-search-stage.md#mongodb-pipeline-pipe.-vectorSearch inside the input pipeline. You can use $rankFusion to combine multiple [$vectorSearch](https://www.mongodb.com/docs/vector-search/query/aggregation-stages/vector-search-stage.md#mongodb-pipeline-pipe.-vectorSearch queries against the same collection in the same pipeline. [$rankFusion](https://www.mongodb.com/docs/manual/reference/operator/aggregation/rankFusion.md#mongodb-pipeline-pipe.-rankFusion first executes all input pipelines independently, and then de-duplicates and combines the input pipeline results into a final ranked results set. To run multiple [$vectorSearch](https://www.mongodb.com/docs/vector-search/query/aggregation-stages/vector-search-stage.md#mongodb-pipeline-pipe.-vectorSearch queries against multiple collections in a single pipeline, use [$unionWith.](https://www.mongodb.com/docs/manual/reference/operator/aggregation/unionWith.md#mongodb-pipeline-pipe.-unionWith
Use Cases and Benefits
You can run the following types of [$vectorSearch](https://www.mongodb.com/docs/vector-search/query/aggregation-stages/vector-search-stage.md#mongodb-pipeline-pipe.-vectorSearch queries by using the $rankFusion pipeline:
- Run multiple [
$vectorSearch](https://www.mongodb.com/docs/vector-search/query/aggregation-stages/vector-search-stage.md#mongodb-pipeline-pipe.-vectorSearch queries for similar terms against the same field.
This allows you to perform a comprehensive search of your dataset for similar terms in the same query.
- Run multiple [
$vectorSearch](https://www.mongodb.com/docs/vector-search/query/aggregation-stages/vector-search-stage.md#mongodb-pipeline-pipe.-vectorSearch queries for the same term against multiple fields.
This allows you to search multiple fields in your dataset to determine which fields return the best results for the query.
- Run multiple [
$vectorSearch](https://www.mongodb.com/docs/vector-search/query/aggregation-stages/vector-search-stage.md#mongodb-pipeline-pipe.-vectorSearch queries for the same term against embeddings from different embedding models.
This allows you to search embeddings from different embedding models to determine the semantic interpretation differences between the different models.
About the Tutorial
This tutorial demonstrates how to run different [$vectorSearch](https://www.mongodb.com/docs/vector-search/query/aggregation-stages/vector-search-stage.md#mongodb-pipeline-pipe.-vectorSearch queries against the collections in the sample_mflix database. You can use the vector embeddings in the embedded_movies collection to try the sample queries or use Automated Embedding to generate embeddings for the sample data.
The example queries in this tutorial use the following fields in the embedded_movies collection in the sample_mflix database:
-
fullplot, which contains the summary of a movie's plot as a text string. -
title, which contains the title of the movie as a text string. -
text-embedding-ada-002, which contains embeddings created by using OpenAI'stext-embedding-ada-002embedding model.
This tutorial walks you through the following steps:
-
Set up a MongoDB Vector Search index on the
sample_mflix.embedded_moviescollection. -
Run [
$vectorSearch](https://www.mongodb.com/docs/vector-search/query/aggregation-stages/vector-search-stage.md#mongodb-pipeline-pipe.-vectorSearch query with$rankFusionto perform the following searches: -
Search the
fullfield for movie plots that contain movies with plots similar tolight-hearted comedy with ghostsandslapstick humor with paranormal events. -
Search the
fullplotandtitlefields for movies with plots similar tobattle between good and evilusing embeddings from Voyage AI. -
Search the
plot_embeddingandfullplotfields for movies with plots similar tojourney across landsusing embeddings from OpenAI and Voyage AI respectively.
The example queries in this tutorial use the following fields in the embedded_movies collection in the sample_mflix database:
-
fullplot, which contains the summary of a movie's plot as a text string. -
title, which contains the title of the movie as a text string. -
text-embedding-ada-002, which contains embeddings created by using OpenAI'stext-embedding-ada-002embedding model.
This tutorial walks you through the following steps:
-
Set up a MongoDB Vector Search index on the
sample_mflix.embedded_moviescollection. -
Run [
$vectorSearch](https://www.mongodb.com/docs/vector-search/query/aggregation-stages/vector-search-stage.md#mongodb-pipeline-pipe.-vectorSearch query with$rankFusionto perform the following searches: -
Search the
fullfield for movie plots that contain movies with plots similar tolight-hearted comedy with ghostsandslapstick humor with paranormal events. -
Search the
fullplotandtitlefields for movies with plots similar tobattle between good and evilusing embeddings from Voyage AI. -
Search the
plot_embeddingandfullplotfields for movies with plots similar tojourney across landsusing embeddings from OpenAI and Voyage AI respectively.
The example queries in this tutorial use the following fields in the embedded_movies collection in the sample_mflix database:
-
fullplot, which contains the summary of a movie's plot as a text string. -
title, which contains the title of the movie as a text string. -
text-embedding-ada-002, which contains embeddings created by using OpenAI'stext-embedding-ada-002embedding model.
This tutorial walks you through the following steps:
-
Set up a MongoDB Vector Search index on the
sample_mflix.embedded_moviescollection. -
Run [
$vectorSearch](https://www.mongodb.com/docs/vector-search/query/aggregation-stages/vector-search-stage.md#mongodb-pipeline-pipe.-vectorSearch query with$rankFusionto perform the following searches: -
Search the
fullfield for movie plots that contain movies with plots similar tolight-hearted comedy with ghostsandslapstick humor with paranormal events. -
Search the
fullplotandtitlefields for movies with plots similar tobattle between good and evilusing embeddings from Voyage AI. -
Search the
plot_embeddingandfullplotfields for movies with plots similar tojourney across landsusing embeddings from OpenAI and Voyage AI respectively.
The example queries in this tutorial use the following fields in the embedded_movies collection in the sample_mflix database:
-
fullplot, which contains the summary of a movie's plot as a text string. -
title, which contains the title of the movie as a text string. -
text-embedding-ada-002, which contains embeddings created by using OpenAI'stext-embedding-ada-002embedding model.
This tutorial walks you through the following steps:
-
Set up a MongoDB Vector Search index on the
sample_mflix.embedded_moviescollection. -
Run [
$vectorSearch](https://www.mongodb.com/docs/vector-search/query/aggregation-stages/vector-search-stage.md#mongodb-pipeline-pipe.-vectorSearch query with$rankFusionto perform the following searches: -
Search the
fullfield for movie plots that contain movies with plots similar tolight-hearted comedy with ghostsandslapstick humor with paranormal events. -
Search the
fullplotandtitlefields for movies with plots similar tobattle between good and evilusing embeddings from Voyage AI. -
Search the
plot_embeddingandfullplotfields for movies with plots similar tojourney across landsusing embeddings from OpenAI and Voyage AI respectively.
The example queries in this tutorial use the following fields in the embedded_movies collection in the sample_mflix database:
-
fullplot, which contains the summary of a movie's plot as a text string. -
title, which contains the title of the movie as a text string. -
text-embedding-ada-002, which contains embeddings created by using OpenAI'stext-embedding-ada-002embedding model.
This tutorial walks you through the following steps:
-
Set up a MongoDB Vector Search index on the
sample_mflix.embedded_moviescollection. -
Run [
$vectorSearch](https://www.mongodb.com/docs/vector-search/query/aggregation-stages/vector-search-stage.md#mongodb-pipeline-pipe.-vectorSearch query with$rankFusionto perform the following searches: -
Search the
fullfield for movie plots that contain movies with plots similar tolight-hearted comedy with ghostsandslapstick humor with paranormal events. -
Search the
fullplotandtitlefields for movies with plots similar tobattle between good and evilusing embeddings from Voyage AI. -
Search the
plot_embeddingandfullplotfields for movies with plots similar tojourney across landsusing embeddings from OpenAI and Voyage AI respectively.
The example queries in this tutorial use the following fields in the embedded_movies collection in the sample_mflix database:
-
plot_embedding, which contains embeddings created by using OpenAI'stext-embedding-ada-002embedding model. -
plot_embedding_voyage_4_large, which contains embeddings created by using Voyage AI'svoyage-4-largeembedding model. You use this field for all sample queries in this tutorial.
For the second query listed in [Use Cases and Benefits](https://www.mongodb.com/docs/vector-search/hybrid-search/vector-search-with-rankfusion.md#std-label-avs-unionwith-use-cases, you must generate embeddings for another field. To try the sample query for this use case, complete the steps in [Generate the Embeddings.](https://www.mongodb.com/docs/vector-search/hybrid-search/vector-search-with-rankfusion.md#std-label-avs-unionwith-generate-embeddings
This tutorial walks you through the following steps:
-
Set up a MongoDB Vector Search index on the
sample_mflix.embedded_moviescollection. -
Run [
$vectorSearch](https://www.mongodb.com/docs/vector-search/query/aggregation-stages/vector-search-stage.md#mongodb-pipeline-pipe.-vectorSearch query with$rankFusionto perform the following searches: -
Search the
plot_embedding_voyage_4_largefield for movie plots that contain movies with plots similar tolight-hearted comedy with ghostsandslapstick humor with paranormal events. -
Search the
plot_embedding_voyage_4_largeandtitle_embeddingfields for movies with plots similar tobattle between good and evilusing embeddings from Voyage AI. -
Search the
plot_embeddingandplot_embedding_voyage_4_largefields for movies with plots similar tojourney across landsusing embeddings from OpenAI and Voyage AI respectively.
The example queries in this tutorial use the following fields in the embedded_movies collection in the sample_mflix database:
-
plot_embedding, which contains embeddings created by using OpenAI'stext-embedding-ada-002embedding model. -
plot_embedding_voyage_4_large, which contains embeddings created by using Voyage AI'svoyage-4-largeembedding model. You use this field for all sample queries in this tutorial.
For the second query listed in [Use Cases and Benefits](https://www.mongodb.com/docs/vector-search/hybrid-search/vector-search-with-rankfusion.md#std-label-avs-unionwith-use-cases, you must generate embeddings for another field. To try the sample query for this use case, complete the steps in [Generate the Embeddings.](https://www.mongodb.com/docs/vector-search/hybrid-search/vector-search-with-rankfusion.md#std-label-avs-unionwith-generate-embeddings
This tutorial walks you through the following steps:
-
Set up a MongoDB Vector Search index on the
sample_mflix.embedded_moviescollection. -
Run [
$vectorSearch](https://www.mongodb.com/docs/vector-search/query/aggregation-stages/vector-search-stage.md#mongodb-pipeline-pipe.-vectorSearch query with$rankFusionto perform the following searches: -
Search the
plot_embedding_voyage_4_largefield for movie plots that contain movies with plots similar tolight-hearted comedy with ghostsandslapstick humor with paranormal events. -
Search the
plot_embedding_voyage_4_largeandtitle_embeddingfields for movies with plots similar tobattle between good and evilusing embeddings from Voyage AI. -
Search the
plot_embeddingandplot_embedding_voyage_4_largefields for movies with plots similar tojourney across landsusing embeddings from OpenAI and Voyage AI respectively.
The example queries in this tutorial use the following fields in the embedded_movies collection in the sample_mflix database:
-
plot_embedding, which contains embeddings created by using OpenAI'stext-embedding-ada-002embedding model. -
plot_embedding_voyage_4_large, which contains embeddings created by using Voyage AI'svoyage-4-largeembedding model. You use this field for all sample queries in this tutorial.
For the second query listed in [Use Cases and Benefits](https://www.mongodb.com/docs/vector-search/hybrid-search/vector-search-with-rankfusion.md#std-label-avs-unionwith-use-cases, you must generate embeddings for another field. To try the sample query for this use case, complete the steps in [Generate the Embeddings.](https://www.mongodb.com/docs/vector-search/hybrid-search/vector-search-with-rankfusion.md#std-label-avs-unionwith-generate-embeddings
This tutorial walks you through the following steps:
-
Set up a MongoDB Vector Search index on the
sample_mflix.embedded_moviescollection. -
Run [
$vectorSearch](https://www.mongodb.com/docs/vector-search/query/aggregation-stages/vector-search-stage.md#mongodb-pipeline-pipe.-vectorSearch query with$rankFusionto perform the following searches: -
Search the
plot_embedding_voyage_4_largefield for movie plots that contain movies with plots similar tolight-hearted comedy with ghostsandslapstick humor with paranormal events. -
Search the
plot_embedding_voyage_4_largeandtitle_embeddingfields for movies with plots similar tobattle between good and evilusing embeddings from Voyage AI. -
Search the
plot_embeddingandplot_embedding_voyage_4_largefields for movies with plots similar tojourney across landsusing embeddings from OpenAI and Voyage AI respectively.
The example queries in this tutorial use the following fields in the embedded_movies collection in the sample_mflix database:
-
plot_embedding, which contains embeddings created by using OpenAI'stext-embedding-ada-002embedding model. -
plot_embedding_voyage_4_large, which contains embeddings created by using Voyage AI'svoyage-4-largeembedding model. You use this field for all sample queries in this tutorial.
For the second query listed in [Use Cases and Benefits](https://www.mongodb.com/docs/vector-search/hybrid-search/vector-search-with-rankfusion.md#std-label-avs-unionwith-use-cases, you must generate embeddings for another field. To try the sample query for this use case, complete the steps in [Generate the Embeddings.](https://www.mongodb.com/docs/vector-search/hybrid-search/vector-search-with-rankfusion.md#std-label-avs-unionwith-generate-embeddings
This tutorial walks you through the following steps:
-
Set up a MongoDB Vector Search index on the
sample_mflix.embedded_moviescollection. -
Run [
$vectorSearch](https://www.mongodb.com/docs/vector-search/query/aggregation-stages/vector-search-stage.md#mongodb-pipeline-pipe.-vectorSearch query with$rankFusionto perform the following searches: -
Search the
plot_embedding_voyage_4_largefield for movie plots that contain movies with plots similar tolight-hearted comedy with ghostsandslapstick humor with paranormal events. -
Search the
plot_embedding_voyage_4_largeandtitle_embeddingfields for movies with plots similar tobattle between good and evilusing embeddings from Voyage AI. -
Search the
plot_embeddingandplot_embedding_voyage_4_largefields for movies with plots similar tojourney across landsusing embeddings from OpenAI and Voyage AI respectively.
The example queries in this tutorial use the following fields in the embedded_movies collection in the sample_mflix database:
-
plot_embedding, which contains embeddings created by using OpenAI'stext-embedding-ada-002embedding model. -
plot_embedding_voyage_4_large, which contains embeddings created by using Voyage AI'svoyage-4-largeembedding model. You use this field for all sample queries in this tutorial.
For the second query listed in [Use Cases and Benefits](https://www.mongodb.com/docs/vector-search/hybrid-search/vector-search-with-rankfusion.md#std-label-avs-unionwith-use-cases, you must generate embeddings for another field. To try the sample query for this use case, complete the steps in [Generate the Embeddings.](https://www.mongodb.com/docs/vector-search/hybrid-search/vector-search-with-rankfusion.md#std-label-avs-unionwith-generate-embeddings
This tutorial walks you through the following steps:
-
Set up a MongoDB Vector Search index on the
sample_mflix.embedded_moviescollection. -
Run [
$vectorSearch](https://www.mongodb.com/docs/vector-search/query/aggregation-stages/vector-search-stage.md#mongodb-pipeline-pipe.-vectorSearch query with$rankFusionto perform the following searches: -
Search the
plot_embedding_voyage_4_largefield for movie plots that contain movies with plots similar tolight-hearted comedy with ghostsandslapstick humor with paranormal events. -
Search the
plot_embedding_voyage_4_largeandtitle_embeddingfields for movies with plots similar tobattle between good and evilusing embeddings from Voyage AI. -
Search the
plot_embeddingandplot_embedding_voyage_4_largefields for movies with plots similar tojourney across landsusing embeddings from OpenAI and Voyage AI respectively.
Prerequisites
Before you begin, ensure that your cluster meets the requirements described in the [Prerequisites](https://www.mongodb.com/docs/vector-search/hybrid-search/hybrid-search-overview.md#std-label-avs-hybrid-search-prereqs. In addition, you must have the following installed:
-
MongoDB Compass version 1.37.0 or later.
-
[
mongosh](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh version 2.0 or later. -
Go version 1.16 or later.
-
MongoDB Go Driver version 1.8 or later.
-
Java Development Kit (JDK) version 8 or later.
-
MongoDB Java Driver version 4.11 or later.
-
Node.js version 14.17.0 or later.
-
MongoDB Node.js Driver version 4.11 or later.
-
Python version 3.8 or later.
-
PyMongo version 4.7 or later.
-
Ruby version 2.7 or later.
-
MongoDB Ruby Driver version 3.0 or later.
Generate the Embeddings
To query for the same term against multiple fields, you must prepare the dataset to include embeddings for different fields. This section demonstrates how to generate embeddings for the title field in the collection by using Voyage AI's voyage-4-large embedding model.
You can skip this section if you want to only try the other sample use cases.
Prerequisites
-
An environment to run interactive Python notebooks such as VS Code or Colab.
-
API key for Voyage AI embedding models.
Procedure
In this section, you generate embeddings for the title field in the embedded_movies collection by using Voyage AI's voyage-4-large embedding model.
- Set up the environment.
Create an interactive Python notebook by saving a file with the .ipynb extension, and then run the following command in the notebook to install the dependencies:
python
pip install --quiet voyageai pymongo
- Define and use a function to generate vector embeddings.
Paste and run the following code in your notebook after replacing the following placeholder values:
<api-key> |
Your Voyage AI API (Application Programming Interface) key (line 6). |
|---|---|
<connection-string> |
Your MongoDB cluster connection string (line 18). |
The following code defines a function that generates vector embeddings by using a proprietary embedding model from Voyage AI. Specifically, this code does the following:
-
Specifies the
voyage-4-largeembedding model. -
Creates a function named
get_embedding()that calls the model's API (Application Programming Interface) to generate2048dimension embedding for a given text input. -
Connects to the cluster and fetches
3500documents from thesample_mflix.embedded_moviesnamespace. -
Generates embeddings from each document's
titlefield by using theget_embedding()function. -
Updates each document with a new field named
title_embedding_voyage_4_largethat contains the embedding value by using the MongoDB PyMongo Driver.
```python import os import pymongo import voyageai
# Specify your Voyage API key and embedding model
os.environ["VOYAGE_API_KEY"] = "
model = "voyage-4-large" outputDimension = 2048 vo = voyageai.Client() # Define a function to generate embeddings def get_embedding(data, input_type = "document"): embeddings = vo.embed( data, model = model, output_dimension = outputDimension, input_type = input_type ).embeddings return embeddings[0]
# Connect to your MongoDB cluster
mongo_client = pymongo.MongoClient("
# Filter to exclude null or empty plot fields filter = {"title": {"$nin": [None, ""]}}
# Get a subset of documents in the collection documents = collection.find(filter).limit(3500)
# Update each document with a new embedding field updated_doc_count = 0 for doc in documents: embedding = get_embedding(doc["title"]) if embedding is not None: collection.update_one({"_id": doc["_id"]}, {"$set": {"title_embedding_voyage_4_large": embedding}}) updated_doc_count += 1
print(f"Updated {updated_doc_count} documents.") ```
Output:
sh
Updated 3500 documents.
Note:
It might take up to 15 minutes for the operation to complete.
Create the MongoDB Vector Search Index
In this section, you create the MongoDB Vector Search index on the sample_mflix.embedded_movies namespace. The section demonstrates the index definitions that can be used for running various queries.
Before creating the index, complete the procedure to [generate the embeddings.](https://www.mongodb.com/docs/vector-search/hybrid-search/vector-search-with-rankfusion.md#std-label-avs-unionwith-generate-embeddings
- Connect to your cluster using MongoDB Compass.
To learn more, 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, expand the name of the database, sample_mflix, then click the name of the collection, embedded_movies.
- Create the MongoDB Vector Search index.
Click the Indexes tab, then select Search Indexes.
Click Create, then select Search Index from the dropdown.
Enter multiple-vector-search as the name of the index.
Select Vector Search to define the MongoDB Vector Search index.
json
{
"fields": [
{
"type": "vector",
"path": "plot_embedding",
"numDimensions": 1536,
"similarity": "dotProduct"
},
{
"type": "vector",
"path": "plot_embedding_voyage_4_large",
"numDimensions": 2048,
"similarity": "dotProduct"
},
{
"type": "vector",
"path": "title_embedding_voyage_4_large",
"numDimensions": 2048,
"similarity": "dotProduct"
}
]
}
The multiple-vector-search index definition indexes the following fields:
-
plot_embedding_voyage_4_largefield, which contains vector embeddings generated by thevoyage-4-largeembedding model that represent the summary of a movie's plot. The index definition specifies2048[vector dimensions.](https://www.mongodb.com/docs/vector-search/index.md#std-term-vectorThis field mapping is required for all the use cases in this tutorial.
-
title_embedding_voyage_4_largefield, which contains vector embeddings generated by thevoyage-4-largeembedding model that represent the title of the movie. The index definition specifies2048[vector dimensions.](https://www.mongodb.com/docs/vector-search/index.md#std-term-vectorThis field mapping is required for the [second use case.](https://www.mongodb.com/docs/vector-search/hybrid-search/vector-search-with-rankfusion.md#std-label-avs-unionwith-use-cases
-
plot_embeddingfield, which contains vector embeddings generated by the OpenAItext-embedding-ada-002embedding model that represent the summary of a movie's plot. The index definition specifies1536[vector dimensions.](https://www.mongodb.com/docs/vector-search/index.md#std-term-vectorThis field mapping is required for the [third use case.](https://www.mongodb.com/docs/vector-search/hybrid-search/vector-search-with-rankfusion.md#std-label-avs-unionwith-use-cases
All three fields use the vector [type](https://www.mongodb.com/docs/vector-search/indexes/vector-search-type.md#std-label-avs-types-vector and dotProduct [similarity.](https://www.mongodb.com/docs/vector-search/indexes/vector-search-type.md#std-label-avs-similarity-functions
Click Create Search Index.
Before creating the index, complete the procedure to [generate the embeddings.](https://www.mongodb.com/docs/vector-search/hybrid-search/vector-search-with-rankfusion.md#std-label-avs-unionwith-generate-embeddings
- Connect to the cluster using [
mongosh](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh.
Open [mongosh](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh in a terminal window and connect to your Atlas cluster. For detailed instructions on connecting, see [Connect via mongosh.](https://www.mongodb.com/docs/atlas/mongo-shell-connection.md#std-label-connect-mongo-shell
- Switch to the database that contains the collection for which you want to create the index.
Example:
shell
use sample_mflix
Output:
shell
switched to db sample_mflix
- Run the
db.collection.createSearchIndex()method.
shell
db.embedded_movies.createSearchIndex(
"multiple-vector-search",
"vectorSearch",
{
"fields": [
{
"type": "vector",
"path": "plot_embedding",
"numDimensions": 1536,
"similarity": "dotProduct"
},
{
"type": "vector",
"path": "plot_embedding_voyage_4_large",
"numDimensions": 2048,
"similarity": "dotProduct"
},
{
"type": "vector",
"path": "title_embedding_voyage_4_large",
"numDimensions": 2048,
"similarity": "dotProduct"
}
]
}
);
The multiple-vector-search index definition indexes the following fields:
-
plot_embedding_voyage_4_largefield, which contains vector embeddings generated by thevoyage-4-largeembedding model that represent the summary of a movie's plot. The index definition specifies2048[vector dimensions.](https://www.mongodb.com/docs/vector-search/index.md#std-term-vectorThis field mapping is required for all the use cases in this tutorial.
-
title_embedding_voyage_4_largefield, which contains vector embeddings generated by thevoyage-4-largeembedding model that represent the title of the movie. The index definition specifies2048[vector dimensions.](https://www.mongodb.com/docs/vector-search/index.md#std-term-vectorThis field mapping is required for the [second use case.](https://www.mongodb.com/docs/vector-search/hybrid-search/vector-search-with-rankfusion.md#std-label-avs-unionwith-use-cases
-
plot_embeddingfield, which contains vector embeddings generated by the OpenAItext-embedding-ada-002embedding model that represent the summary of a movie's plot. The index definition specifies1536[vector dimensions.](https://www.mongodb.com/docs/vector-search/index.md#std-term-vectorThis field mapping is required for the [third use case.](https://www.mongodb.com/docs/vector-search/hybrid-search/vector-search-with-rankfusion.md#std-label-avs-unionwith-use-cases
All three fields use the vector [type](https://www.mongodb.com/docs/vector-search/indexes/vector-search-type.md#std-label-avs-types-vector and dotProduct [similarity.](https://www.mongodb.com/docs/vector-search/indexes/vector-search-type.md#std-label-avs-similarity-functions
Before creating the index, complete the procedure to [generate the embeddings.](https://www.mongodb.com/docs/vector-search/hybrid-search/vector-search-with-rankfusion.md#std-label-avs-unionwith-generate-embeddings
- Initialize your Go module.
sh
mkdir go-vector-quickstart && cd go-vector-quickstart
go mod init go-vector-quickstart
- Add the Go Driver as a dependency in your project.
sh
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
- Define the index.
Create a file named vector-index.go. Copy and paste the following code into the file.
```go package main
import ( "context" "log" "time"
"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()
// Replace the placeholder with your connection string
const uri = "<connectionString>"
// Connect to your cluster
clientOptions := options.Client().ApplyURI(uri)
client, err := mongo.Connect(clientOptions)
if err != nil {
log.Fatalf("failed to connect to the server: %v", err)
}
defer func() { _ = client.Disconnect(ctx) }()
// Set the namespace
coll := client.Database("sample_mflix").Collection("embedded_movies")
// Define the index details
type vectorDefinitionField struct {
Type string `bson:"type"`
Path string `bson:"path"`
NumDimensions int `bson:"numDimensions"`
Similarity string `bson:"similarity"`
}
type vectorDefinition struct {
Fields []vectorDefinitionField `bson:"fields"`
}
indexName := "multiple-vector-search"
opts := options.SearchIndexes().SetName(indexName).SetType("vectorSearch")
indexModel := mongo.SearchIndexModel{
Definition: vectorDefinition{
Fields: []vectorDefinitionField{
{
Type: "vector",
Path: "plot_embedding",
NumDimensions: 1536,
Similarity: "dotProduct",
},
{
Type: "vector",
Path: "plot_embedding_voyage_4_large",
NumDimensions: 2048,
Similarity: "dotProduct",
},
{
Type: "vector",
Path: "title_embedding_voyage_4_large",
NumDimensions: 2048,
Similarity: "dotProduct",
},
},
},
Options: opts,
}
// Create the index
log.Println("Creating the index.")
searchIndexName, err := coll.SearchIndexes().CreateOne(ctx, indexModel)
if err != nil {
log.Fatalf("failed to create the search index: %v", err)
}
// Await the creation of the index.
log.Println("Polling to confirm successful index creation.")
log.Println("NOTE: This may take up to a minute.")
searchIndexes := coll.SearchIndexes()
var doc bson.Raw
for doc == nil {
cursor, err := searchIndexes.List(ctx, options.SearchIndexes().SetName(searchIndexName))
if err != nil {
log.Fatalf("failed to list search indexes: %v", err)
}
if !cursor.Next(ctx) {
break
}
name := cursor.Current.Lookup("name").StringValue()
queryable := cursor.Current.Lookup("queryable").Boolean()
if name == searchIndexName && queryable {
doc = cursor.Current
} else {
time.Sleep(5 * time.Second)
}
}
log.Println("Name of Index Created: " + searchIndexName)
} ```
The multiple-vector-search index definition indexes the following fields:
-
plot_embedding_voyage_4_largefield, which contains vector embeddings generated by thevoyage-4-largeembedding model that represent the summary of a movie's plot. The index definition specifies2048[vector dimensions.](https://www.mongodb.com/docs/vector-search/index.md#std-term-vectorThis field mapping is required for all the use cases in this tutorial.
-
title_embedding_voyage_4_largefield, which contains vector embeddings generated by thevoyage-4-largeembedding model that represent the title of the movie. The index definition specifies2048[vector dimensions.](https://www.mongodb.com/docs/vector-search/index.md#std-term-vectorThis field mapping is required for the [second use case.](https://www.mongodb.com/docs/vector-search/hybrid-search/vector-search-with-rankfusion.md#std-label-avs-unionwith-use-cases
-
plot_embeddingfield, which contains vector embeddings generated by the OpenAItext-embedding-ada-002embedding model that represent the summary of a movie's plot. The index definition specifies1536[vector dimensions.](https://www.mongodb.com/docs/vector-search/index.md#std-term-vectorThis field mapping is required for the [third use case.](https://www.mongodb.com/docs/vector-search/hybrid-search/vector-search-with-rankfusion.md#std-label-avs-unionwith-use-cases
All three fields use the vector [type](https://www.mongodb.com/docs/vector-search/indexes/vector-search-type.md#std-label-avs-types-vector and dotProduct [similarity.](https://www.mongodb.com/docs/vector-search/indexes/vector-search-type.md#std-label-avs-similarity-functions
This code also includes a polling mechanism to check if the index is ready to use.
- Specify the
<connectionString>.
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
- Create the index.
shell
go run vector-index.go
Output:
console
2026/07/14 18:06:39 Creating the index.
2026/07/14 18:06:41 Polling to confirm successful index creation.
2026/07/14 18:06:41 NOTE: This may take up to a minute.
2026/07/14 18:08:20 Name of Index Created: multiple-vector-search
Before creating the index, complete the procedure to [generate the embeddings.](https://www.mongodb.com/docs/vector-search/hybrid-search/vector-search-with-rankfusion.md#std-label-avs-unionwith-generate-embeddings
- Add the Java driver version 5.2 or later as a dependency in your project.
Select one of the following tabs, depending on your package manager:
### Maven
If you are using Maven, add the following dependencies to the dependencies array in your project's pom.xml file:
xml
<dependencies>
<!-- MongoDB Java Sync Driver v5.2.0 or later -->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version>[5.2.0,)</version> </dependency> </dependencies> 2. 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.](https://www.mongodb.com/docs/drivers/java/sync/current/quick-start/#std-label-add-mongodb-dependency
- Create a file named
VectorIndex.java. Copy and paste the following code into the file.
```java import com.mongodb.client.MongoClient; import com.mongodb.client.MongoClients; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.SearchIndexModel; import com.mongodb.client.model.SearchIndexType; import org.bson.Document; import org.bson.conversions.Bson;
import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.stream.StreamSupport;
public class VectorIndex {
public static void main(String[] args) {
// Replace the placeholder with your connection string
String uri = “<connectionString>”;
// Connect to your cluster
try (MongoClient mongoClient = MongoClients.create(uri)) {
// Set the namespace
MongoDatabase database = mongoClient.getDatabase(“sample_mflix”);
MongoCollection<Document> collection = database.getCollection(“embedded_movies”);
// Define the index details
String indexName = “multiple-vector-search”;
Bson definition = new Document(
“fields”,
Arrays.asList(
new Document(“type”, “vector”)
.append(“path”, “plot_embedding”)
.append(“numDimensions”, 1536)
.append(“similarity”, “dotProduct”),
new Document(“type”, “vector”)
.append(“path”, “plot_embedding_voyage_4_large”)
.append(“numDimensions”, 2048)
.append(“similarity”, “dotProduct”),
new Document(“type”, “vector”)
.append(“path”, “title_embedding_voyage_4_large”)
.append(“numDimensions”, 2048)
.append(“similarity”, “dotProduct”)));
// Define the index model
SearchIndexModel indexModel = new SearchIndexModel(
indexName,
definition,
SearchIndexType.vectorSearch()
);
// Create the index using the defined model
List<String> result = collection.createSearchIndexes(Collections.singletonList(indexModel));
System.out.println(“Successfully created vector index named: ” + result.get(0));
System.out.println(“Wait for the index to leave the BUILDING status and become queryable.”);
// Wait for index to build and become queryable
System.out.println(“Polling to confirm the index has left the BUILDING status.”);
// No special handling in case of a timeout. Custom handling can be implemented.
waitForIndex(collection, indexName);
}
}
/**
* Polls the collection to check whether the specified index is ready to query.
*/
public static <T> boolean waitForIndex(final MongoCollection<T> collection, final String indexName) {
long startTime = System.nanoTime();
long timeoutNanos = TimeUnit.SECONDS.toNanos(60);
while (System.nanoTime() - startTime < timeoutNanos) {
Document indexRecord = StreamSupport.stream(collection.listSearchIndexes().spliterator(), false)
.filter(index -> indexName.equals(index.getString(“name”)))
.findAny().orElse(null);
if (indexRecord != null) {
if (“FAILED”.equals(indexRecord.getString(“status”))) {
throw new RuntimeException(“Search index has FAILED status.”);
}
if (indexRecord.getBoolean(“queryable”)) {
System.out.println(indexName + “ index is ready to query”);
return true;
}
}
try {
Thread.sleep(100); // busy-wait, avoid in production
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
}
return false;
}
} ```
The multiple-vector-search index definition indexes the following fields:
-
plot_embedding_voyage_4_largefield, which contains vector embeddings generated by thevoyage-4-largeembedding model that represent the summary of a movie's plot. The index definition specifies2048[vector dimensions.](https://www.mongodb.com/docs/vector-search/index.md#std-term-vectorThis field mapping is required for all the use cases in this tutorial.
-
title_embedding_voyage_4_largefield, which contains vector embeddings generated by thevoyage-4-largeembedding model that represent the title of the movie. The index definition specifies2048[vector dimensions.](https://www.mongodb.com/docs/vector-search/index.md#std-term-vectorThis field mapping is required for the [second use case.](https://www.mongodb.com/docs/vector-search/hybrid-search/vector-search-with-rankfusion.md#std-label-avs-unionwith-use-cases
-
plot_embeddingfield, which contains vector embeddings generated by the OpenAItext-embedding-ada-002embedding model that represent the summary of a movie's plot. The index definition specifies1536[vector dimensions.](https://www.mongodb.com/docs/vector-search/index.md#std-term-vectorThis field mapping is required for the [third use case.](https://www.mongodb.com/docs/vector-search/hybrid-search/vector-search-with-rankfusion.md#std-label-avs-unionwith-use-cases
All three fields use the vector [type](https://www.mongodb.com/docs/vector-search/indexes/vector-search-type.md#std-label-avs-types-vector and dotProduct [similarity.](https://www.mongodb.com/docs/vector-search/indexes/vector-search-type.md#std-label-avs-similarity-functions
This code also includes a polling mechanism to check if the index is ready to use.
- Specify the
<connectionString>.
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
- Run the file in your IDE, or execute a command from the command line to run the code.
shell
javac VectorIndex.java
java VectorIndex
Output:
console
New search index named multiple-vector-search is building.
Polling to check if the index is ready. This may take up to a minute.
multiple-vector-search is ready for querying.
Before creating the index, complete the procedure to [generate the embeddings.](https://www.mongodb.com/docs/vector-search/hybrid-search/vector-search-with-rankfusion.md#std-label-avs-unionwith-generate-embeddings
- Add the MongoDB Node Driver as a dependency in your project:
sh
npm install mongodb
Tip:
The examples on this page assume your project manages modules as CommonJS modules. If you're using ES modules, instead, you mu
(本文超出站点单文档体积上限,已截断)
