vector-search-with-full-text-search

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 -->

This tutorial demonstrates a hybrid search that is an aggregation of full-text and semantic search for the same query criteria. While full-text is effective in finding exact matches for query terms, semantic search provides the added benefit of identifying semantically similar documents even if the documents don't contain the exact query term. This ensures that synonymous and contextually similar matches are also included in the combined results of both methods of search.

Conversely, if you have tokens for proper nouns or specific keywords in your dataset that you don't expect to be considered in the training of an embedding model in the same context that they are used in your dataset, your vector search might benefit from being combined with a full-text search.

You can also set weights for each method of search per query. Based on whether full-text or semantic search results are most relevant and appropriate for a query, you can increase the weight for that search method per query.

You can reorder the documents in the results based on the relevance to the query by using the [$rerank](https://www.mongodb.com/docs/vector-search/query/aggregation-stages/rerank.md#mongodb-pipeline-pipe.-rerank stage after the [$rankFusion](https://www.mongodb.com/docs/manual/reference/operator/aggregation/rankFusion.md#mongodb-pipeline-pipe.-rankFusion or [$scoreFusion](https://www.mongodb.com/docs/manual/reference/operator/aggregation/scoreFusion.md#mongodb-pipeline-pipe.-scoreFusion stage. The $rerank stage reorders the documents based on a Voyage AI reranker model.

About the Tutorial

This tutorial demonstrates how to run a hybrid search combining MongoDB Vector Search and MongoDB Search queries on the sample_mflix.embedded_movies collection, which contains details about movies, for unified search results. Specifically, this tutorial takes you through the following steps:

  1. Create a MongoDB Vector Search index on the plot_embedding_voyage_4_large field. This field contains vector embeddings that represent the summary of a movie's plot.

  2. Create a MongoDB Search index on the fullplot field in the sample_mflix.embedded_movies collection. This field contains the movie's name as a text string.

  3. Run a query that uses [$rankFusion](https://www.mongodb.com/docs/manual/reference/operator/aggregation/rankFusion.md#mongodb-pipeline-pipe.-rankFusion or [$scoreFusion](https://www.mongodb.com/docs/manual/reference/operator/aggregation/scoreFusion.md#mongodb-pipeline-pipe.-scoreFusion to combine the results from a [$vectorSearch](https://www.mongodb.com/docs/vector-search/query/aggregation-stages/vector-search-stage.md#mongodb-pipeline-pipe.-vectorSearch query against the plot_embedding_voyage_4_large field and a [$search](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search query against the fullplot field and then reorder the documents in the results based on the relevance to the query by using the [$rerank](https://www.mongodb.com/docs/vector-search/query/aggregation-stages/rerank.md#mongodb-pipeline-pipe.-rerank stage.

Prerequisites

Before you begin, complete the [prerequisites.](https://www.mongodb.com/docs/vector-search/hybrid-search/hybrid-search-overview.md#std-label-avs-hybrid-search-prereqs

Procedures

Create the MongoDB Vector Search and MongoDB Search Indexes

This section demonstrates how to create the following indexes on the fields in the sample_mflix.embedded_movies collection:

  • A MongoDB Vector Search index on the plot_embedding_voyage_4_large field for running vector queries against that field.

  • A MongoDB Search index on the fullplot field for running full-text search against that field.

  • 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

  1. Specify the database and collection.

On the Database screen, click the name of the database, then click the name of the collection.

  1. Create the MongoDB Vector Search index.

In the Indexes tab, then select Search Indexes.

From the Create dropdown, select Search Index.

In the Name of Search Index field, enter hybrid-vector-search.

Your MongoDB Vector Search index is named vector_index by default. If you use this name, then your index will be the default MongoDB Vector Search index for any MongoDB Vector Search query that does not specify a different index name in the pipeline. If you are creating multiple indexes, we recommend that you maintain a consistent, descriptive naming convention across your indexes.

Under Vector Search, specify the JSON (Javascript Object Notation) MongoDB Vector Search index definition.

json { "fields": [{ "type": "vector", "path": "plot_embedding_voyage_4_large", "numDimensions": 2048, "similarity": "dotProduct" }] }

Click Create Search Index.

  1. Create the MongoDB Search index.

In the Indexes tab, then select Search Indexes.

From the Create dropdown, select Search Index.

In the Name of Search Index field, enter hybrid-full-text-search.

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.

Under Search, specify the JSON (Javascript Object Notation) MongoDB Vector Search index definition.

json { "mappings": { "dynamic": true } }

Click Create Search Index.

This section demonstrates how to create the following indexes on the fields in the sample_mflix.embedded_movies collection:

  • A MongoDB Vector Search index on the plot_embedding_voyage_4_large field for running vector queries against that field.

  • A MongoDB Search index on the fullplot field for running full-text search against that field.

  • Connect to the cluster using [mongosh](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh.

To learn more, see [Connect to a Cluster via mongosh.](https://www.mongodb.com/docs/atlas/mongo-shell-connection.md#std-label-connect-mongo-shell

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

shell use sample_mflix

Output:

shell switched to db sample_mflix

  1. Define the MongoDB Vector Search index.

Run the following command. This index definition indexes the plot_embedding_voyage_4_large field as the MongoDB Vector Search field when querying the collection.

shell db.embedded_movies.createSearchIndex( "hybrid-vector-search", "vectorSearch", { "fields": [ { "type": "vector", "path": "plot_embedding_voyage_4_large", "numDimensions": 2048, "similarity": "dotProduct" } ] } );

  1. Define the MongoDB Search index.

The following index definition automatically indexes all the dynamically indexable fields in the collection.

shell db.embedded_movies.createSearchIndex( "hybrid-full-text-search", "search", { "mappings": { "dynamic": true } } );

This section demonstrates how to create the following indexes on the fields in the sample_mflix.embedded_movies collection:

  • A MongoDB Vector Search index on the plot_embedding_voyage_4_large field for running vector queries against that field.

  • A MongoDB Search index on the fullplot field for running full-text search against that field.

  • 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.

  1. Define the MongoDB Vector Search index.

The following index definition indexes the plot_embedding_voyage_4_large field as the MongoDB Vector Search field when querying the collection.

Create a file named vector-search-index.js, and paste the following code into it:

```javascript const { MongoClient } = require("mongodb");

// Connect to your MongoDB deployment const MONGODB_URI = ""; const client = new MongoClient(MONGODB_URI);

async function run() { try { const database = client.db("sample_mflix"); const collection = database.collection("embedded_movies");

     // Define your vector search index
     const index = {
         name: "hybrid-vector-search",
         type: "vectorSearch",
         definition: {
           "fields": [
             {
               "type": "vector",
               "numDimensions": 2048,
               "path": "plot_embedding_voyage_4_large",
               "similarity": "dotProduct"
             }
           ]
         }
     }

     // Call the method to create the index
     const result = await collection.createSearchIndex(index);
     console.log(result);
   } finally {
     await client.close();
   }

} run().catch(console.dir);

```

Run the following command to execute the code:

javascript node vector-search-index.js

Output:

javascript hybrid-vector-search

MongoDB Vector Search might take few minutes to create the index.

  1. Define the MongoDB Search index.

The following index definition automatically indexes all dynamically indexable field types in the collection.

Create a file named text-search-index.js, and paste the following code into it:

```javascript const { MongoClient } = require("mongodb");

// Connect to your MongoDB deployment const MONGODB_URI = ""; const client = new MongoClient(MONGODB_URI);

async function run() { try { const database = client.db("sample_mflix"); const collection = database.collection("embedded_movies");

     // Define your search index
     const index = {
         name: "hybrid-full-text-search",
         type: "search",
         definition: {
           "mappings": {
             "dynamic": true
           }
         }
     }

     // Call the method to create the index
     const result = await collection.createSearchIndex(index);
     console.log(result);
   } finally {
     await client.close();
   }

} run().catch(console.dir); ```

Run the following command to execute the code:

javascript node text-search-index.js

Output:

javascript hybrid-full-text-search

MongoDB Search might take few minutes to create the index.

This section demonstrates how to create the following indexes on the fields in the sample_mflix.embedded_movies collection:

  • A MongoDB Vector Search index on the plot_embedding_voyage_4_large field for running vector queries against that field.

  • A MongoDB Search index on the fullplot field for running full-text search against that field.

  • 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

  1. Define the MongoDB Vector Search index.

Create a create_vector_index.py file in your project directory, and copy and paste the following code into the file.

```python from pymongo.mongo_client import MongoClient from pymongo.operations import SearchIndexModel import time

# Connect to your Atlas deployment uri = "" client = MongoClient(uri)

# Access your database and collection database = client["sample_mflix"] collection = database["embedded_movies"]

# Define your index search_index_model = SearchIndexModel( definition={ "fields": [ { "type": "vector", "path": "plot_embedding_voyage_4_large", "numDimensions": 2048, "similarity": "dotProduct" } ] }, name="hybrid-vector-search", type="vectorSearch" )

# Create the index result = collection.create_search_index(model=search_index_model) print("New search index named " + result + " is building.")

# Wait for initial sync to complete print("Polling to check if the index is ready. This may take up to a minute.") predicate=None if predicate is None: predicate = lambda index: index.get("queryable") is True

while True: indices = list(collection.list_search_indexes(result)) if len(indices) and predicate(indices[0]): break time.sleep(5) print(result + " is ready for querying.")

client.close() ```

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

  1. Create the MongoDB Vector Search index.

shell python create_vector_index.py

Output:

text New search index named hybrid-vector-search is building. Polling to check if the index is ready. This may take up to a minute. hybrid-vector-search is ready for querying.

  1. Define the MongoDB Vector Search index.

Create a create_search_index.py file in your project directory, and copy and paste the following code into the file.

```python from pymongo.mongo_client import MongoClient from pymongo.operations import SearchIndexModel import time

# Connect to your Atlas deployment uri = "" client = MongoClient(uri)

# Access your database and collection database = client["sample_mflix"] collection = database["embedded_movies"]

# Define your index search_index_model = SearchIndexModel( definition={ "mappings": { "dynamic": True, }, }, name="hybrid-full-text-search", )

# Create the index result = collection.create_search_index(model=search_index_model) print("New search index named " + result + " is building.")

# Wait for initial sync to complete print("Polling to check if the index is ready. This may take up to a minute.") predicate=None if predicate is None: predicate = lambda index: index.get("queryable") is True

while True: indices = list(collection.list_search_indexes(result)) if len(indices) and predicate(indices[0]): break time.sleep(5) print(result + " is ready for querying.")

client.close() ```

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

  1. Create the MongoDB Vector Search index.

shell python create_search_index.py

Output:

text New search index named hybrid-full-text-search is building. Polling to check if the index is ready. This may take up to a minute. hybrid-full-text-search is ready for querying.

This section demonstrates how to create the following indexes on the fields in the sample_mflix.embedded_movies collection:

  • A MongoDB Vector Search index on the plot_embedding_voyage_4_large field for running vector queries against that field.

  • A MongoDB Search index on the fullplot field for running full-text search against that field.

  • 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

  1. Specify the database and collection.

On the Database screen, click the name of the database, then click the name of the collection.

  1. Create the MongoDB Vector Search index.

In the Indexes tab, then select Search Indexes.

From the Create dropdown, select Search Index.

In the Name of Search Index field, enter hybrid-vector-search.

Your MongoDB Vector Search index is named vector_index by default. If you use this name, then your index will be the default MongoDB Vector Search index for any MongoDB Vector Search query that does not specify a different index name in the pipeline. If you are creating multiple indexes, we recommend that you maintain a consistent, descriptive naming convention across your indexes.

Under Vector Search, specify the JSON (Javascript Object Notation) MongoDB Vector Search index definition.

json { "fields": [{ "type": "vector", "path": "plot_embedding_voyage_4_large", "numDimensions": 2048, "similarity": "dotProduct" }] }

Click Create Search Index.

  1. Create the MongoDB Search index.

In the Indexes tab, then select Search Indexes.

From the Create dropdown, select Search Index.

In the Name of Search Index field, enter hybrid-full-text-search.

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.

Under Search, specify the JSON (Javascript Object Notation) MongoDB Vector Search index definition.

json { "mappings": { "dynamic": true } }

Click Create Search Index.

This section demonstrates how to create the following indexes on the fields in the sample_mflix.embedded_movies collection:

  • A MongoDB Vector Search index on the plot_embedding_voyage_4_large field for running vector queries against that field.

  • A MongoDB Search index on the fullplot field for running full-text search against that field.

  • Connect to the cluster using [mongosh](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh.

To learn more, see [Connect to a Cluster via mongosh.](https://www.mongodb.com/docs/atlas/mongo-shell-connection.md#std-label-connect-mongo-shell

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

shell use sample_mflix

Output:

shell switched to db sample_mflix

  1. Define the MongoDB Vector Search index.

Run the following command. This index definition indexes the plot_embedding_voyage_4_large field as the MongoDB Vector Search field when querying the collection.

shell db.embedded_movies.createSearchIndex( "hybrid-vector-search", "vectorSearch", { "fields": [ { "type": "vector", "path": "plot_embedding_voyage_4_large", "numDimensions": 2048, "similarity": "dotProduct" } ] } );

  1. Define the MongoDB Search index.

The following index definition automatically indexes all the dynamically indexable fields in the collection.

shell db.embedded_movies.createSearchIndex( "hybrid-full-text-search", "search", { "mappings": { "dynamic": true } } );

This section demonstrates how to create the following indexes on the fields in the sample_mflix.embedded_movies collection:

  • A MongoDB Vector Search index on the plot_embedding_voyage_4_large field for running vector queries against that field.

  • A MongoDB Search index on the fullplot field for running full-text search against that field.

  • 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.

  1. Define the MongoDB Vector Search index.

The following index definition indexes the plot_embedding_voyage_4_large field as the MongoDB Vector Search field when querying the collection.

Create a file named vector-search-index.js, and paste the following code into it:

```javascript const { MongoClient } = require("mongodb");

// Connect to your MongoDB deployment const MONGODB_URI = ""; const client = new MongoClient(MONGODB_URI);

async function run() { try { const database = client.db("sample_mflix"); const collection = database.collection("embedded_movies");

     // Define your vector search index
     const index = {
         name: "hybrid-vector-search",
         type: "vectorSearch",
         definition: {
           "fields": [
             {
               "type": "vector",
               "numDimensions": 2048,
               "path": "plot_embedding_voyage_4_large",
               "similarity": "dotProduct"
             }
           ]
         }
     }

     // Call the method to create the index
     const result = await collection.createSearchIndex(index);
     console.log(result);
   } finally {
     await client.close();
   }

} run().catch(console.dir);

```

Run the following command to execute the code:

javascript node vector-search-index.js

Output:

javascript hybrid-vector-search

MongoDB Vector Search might take few minutes to create the index.

  1. Define the MongoDB Search index.

The following index definition automatically indexes all dynamically indexable field types in the collection.

Create a file named text-search-index.js, and paste the following code into it:

```javascript const { MongoClient } = require("mongodb");

// Connect to your MongoDB deployment const MONGODB_URI = ""; const client = new MongoClient(MONGODB_URI);

async function run() { try { const database = client.db("sample_mflix"); const collection = database.collection("embedded_movies");

     // Define your search index
     const index = {
         name: "hybrid-full-text-search",
         type: "search",
         definition: {
           "mappings": {
             "dynamic": true
           }
         }
     }

     // Call the method to create the index
     const result = await collection.createSearchIndex(index);
     console.log(result);
   } finally {
     await client.close();
   }

} run().catch(console.dir); ```

Run the following command to execute the code:

javascript node text-search-index.js

Output:

javascript hybrid-full-text-search

MongoDB Search might take few minutes to create the index.

This section demonstrates how to create the following indexes on the fields in the sample_mflix.embedded_movies collection:

  • A MongoDB Vector Search index on the plot_embedding_voyage_4_large field for running vector queries against that field.

  • A MongoDB Search index on the fullplot field for running full-text search against that field.

  • 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

  1. Define the MongoDB Vector Search index.

Create a create_vector_index.py file in your project directory, and copy and paste the following code into the file.

```python from pymongo.mongo_client import MongoClient from pymongo.operations import SearchIndexModel import time

# Connect to your Atlas deployment uri = "" client = MongoClient(uri)

# Access your database and collection database = client["sample_mflix"] collection = database["embedded_movies"]

# Define your index search_index_model = SearchIndexModel( definition={ "fields": [ { "type": "vector", "path": "plot_embedding_voyage_4_large", "numDimensions": 2048, "similarity": "dotProduct" } ] }, name="hybrid-vector-search", type="vectorSearch" )

# Create the index result = collection.create_search_index(model=search_index_model) print("New search index named " + result + " is building.")

# Wait for initial sync to complete print("Polling to check if the index is ready. This may take up to a minute.") predicate=None if predicate is None: predicate = lambda index: index.get("queryable") is True

while True: indices = list(collection.list_search_indexes(result)) if len(indices) and predicate(indices[0]): break time.sleep(5) print(result + " is ready for querying.")

client.close() ```

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

  1. Create the MongoDB Vector Search index.

shell python create_vector_index.py

Output:

text New search index named hybrid-vector-search is building. Polling to check if the index is ready. This may take up to a minute. hybrid-vector-search is ready for querying.

  1. Define the MongoDB Vector Search index.

Create a create_search_index.py file in your project directory, and copy and paste the following code into the file.

```python from pymongo.mongo_client import MongoClient from pymongo.operations import SearchIndexModel import time

# Connect to your Atlas deployment uri = "" client = MongoClient(uri)

# Access your database and collection database = client["sample_mflix"] collection = database["embedded_movies"]

# Define your index search_index_model = SearchIndexModel( definition={ "mappings": { "dynamic": True, }, }, name="hybrid-full-text-search", )

# Create the index result = collection.create_search_index(model=search_index_model) print("New search index named " + result + " is building.")

# Wait for initial sync to complete print("Polling to check if the index is ready. This may take up to a minute.") predicate=None if predicate is None: predicate = lambda index: index.get("queryable") is True

while True: indices = list(collection.list_search_indexes(result)) if len(indices) and predicate(indices[0]): break time.sleep(5) print(result + " is ready for querying.")

client.close() ```

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

  1. Create the MongoDB Vector Search index.

shell python create_search_index.py

Output:

text New search index named hybrid-full-text-search is building. Polling to check if the index is ready. This may take up to a minute. hybrid-full-text-search is ready for querying.

This section demonstrates how to create the following indexes on the fullplot field in the sample_mflix.embedded_movies collection:

  • A MongoDB Vector Search autoEmbed type index for generating embeddings and running semantic search queries against that field.

  • A MongoDB Search index on the fullplot field for running full-text search against that field.

  • 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

  1. Specify the database and collection.

On the Database screen, click the name of the database, then click the name of the collection.

  1. Create the MongoDB Vector Search index.

In the Indexes tab, then select Search Indexes.

From the Create dropdown, select Search Index.

In the Name of Search Index field, enter hybrid-vector-search.

Under Vector Search, specify the JSON (Javascript Object Notation) MongoDB Vector Search index definition.

json { "fields": [ { "type": "autoEmbed", "modality": "text", "path": "fullplot", "model": "voyage-4" } ] }

This index definition indexes the fullplot field as the autoEmbed field, for which MongoDB Vector Search automatically generates embeddings using the voyage-4 embedding model.

Click Create Search Index.

  1. Create the MongoDB Search index.

In the Indexes tab, then select Search Indexes.

From the Create dropdown, select Search Index.

In the Name of Search Index field, enter hybrid-full-text-search.

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.

Under Search, specify the JSON (Javascript Object Notation) MongoDB Vector Search index definition.

json { "mappings": { "dynamic": true } }

Click Create Search Index.

This section demonstrates how to create the following indexes on the fullplot field in the sample_mflix.embedded_movies collection:

  • A MongoDB Vector Search autoEmbed type index for generating embeddings and running semantic search queries against that field.

  • A MongoDB Search index on the fullplot field for running full-text search against that field.

  • Connect to the cluster using [mongosh](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh.

To learn more, see [Connect to a Cluster via mongosh.](https://www.mongodb.com/docs/atlas/mongo-shell-connection.md#std-label-connect-mongo-shell

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

shell use sample_mflix

Output:

shell switched to db sample_mflix

  1. Define the MongoDB Vector Search index.

Run the following command. This index definition indexes the fullplot field as the MongoDB Vector Search field, for which MongoDB Vector Search automatically generates embeddings using the voyage-4 embedding model.

shell db.embedded_movies.createSearchIndex( "hybrid-vector-search", "vectorSearch", { "fields": [ { "type": "autoEmbed", "modality": "text", "path": "fullplot", "model": "voyage-4" } ] } );

  1. Define the MongoDB Search index.

The following index definition automatically indexes all the dynamically indexable fields in the collection.

shell db.embedded_movies.createSearchIndex( "hybrid-full-text-search", "search", { "mappings": { "dynamic": true } } );

This section demonstrates how to create the following indexes on the fullplot field in the sample_mflix.embedded_movies collection:

  • A MongoDB Vector Search autoEmbed type index for generating embeddings and running semantic search queries against that field.

  • A MongoDB Search index on the fullplot field for running full-text search against that field.

  • 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.

  1. Define the MongoDB Vector Search index.

The following index definition indexes the fullplot field as the autoEmbed type field, for which MongoDB Vector Search automatically generates embeddings using the voyage-4 embedding model.

Create a file named vector-search-index.js, and paste the following code into it:

```javascript const { MongoClient } = require("mongodb");

// Connect to your MongoDB deployment const MONGODB_URI = ""; const client = new MongoClient(MONGODB_URI);

async function run() { try { const database = client.db("sample_mflix"); const collection = database.collection("embedded_movies");

     // Define your vector search index
     const index = {
         name: "hybrid-vector-search",
         type: "vectorSearch",
         definition: {
           "fields": [
             {
               "type": "autoEmbed",
               "modality": "text",
               "path": "fullplot",
               "model": "voyage-4"
             }
           ]
         }
     }

     // Call the method to create the index
     const result = await collection.createSearchIndex(index);
     console.log(result);
   } finally {
     await client.close();
   }

} run().catch(console.dir);

```

Run the following command to execute the code:

javascript node vector-search-index.js

Output:

javascript hybrid-vector-search

MongoDB Vector Search might take few minutes to create the index.

  1. Define the MongoDB Search index.

The following index definition automatically indexes all dynamically indexable field types in the collection.

Create a file named text-search-index.js, and paste the following code into it:

```javascript const { MongoClient } = require("mongodb");

// Connect to your MongoDB deployment const MONGODB_URI = ""; const client = new MongoClient(MONGODB_URI);

async function run() { try { const database = client.db("sample_mflix"); const collection = database.collection("embedded_movies");

     // Define your search index
     const index = {
         name: "hybrid-full-text-search",
         type: "search",
         definition: {
           "mappings": {
             "dynamic": true
           }
         }
     }

     // Call the method to create the index
     const result = await collection.createSearchIndex(index);
     console.log(result);
   } finally {
     await client.close();
   }

} run().catch(console.dir); ```

This index definition indexes the fullplot field as the autoEmbed field, for which MongoDB Vector Search automatically generates embeddings using the voyage-4 embedding model.

Run the following command to execute the code:

javascript node text-search-index.js

Output:

javascript hybrid-full-text-search

MongoDB Search might take few minutes to create the index.

This section demonstrates how to create the following indexes on the fullplot field in the sample_mflix.embedded_movies collection:

  • A MongoDB Vector Search autoEmbed type index for generating embeddings and running semantic search queries against that field.

  • A MongoDB Search index on the fullplot field for running full-text search against that field.

  • 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

  1. Define the MongoDB Vector Search index.

Create a create_vector_index.py file in your project directory, and copy and paste the following code into the file.

```python from pymongo.mongo_client import MongoClient from pymongo.operations import SearchIndexModel import time

# Connect to your Atlas deployment uri = "" client = MongoClient(uri)

# Access your database and collection database = client["sample_mflix"] collection = database["embedded_movies"]

# Define your index search_index_model = SearchIndexModel( definition={ "fields": [ { "type": "autoEmbed", "modality": "text", "path": "fullplot", "model": "voyage-4" } ] }, name="hybrid-vector-search", type="vectorSearch" )

# Create the index result = collection.create_search_index(model=search_index_model) print("New search index named " + result + " is building.")

# Wait for initial sync to complete print("Polling to check if the index is ready. This may take up to a minute.") predicate=None if predicate is None: predicate = lambda index: index.get("queryable") is True

while True: indices = list(collection.list_search_indexes(result)) if len(indices) and predicate(indices[0]): break time.sleep(5) print(result + " is ready for querying.")

client.close() ```

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

  1. Create the MongoDB Vector Search index.

shell python create_vector_index.py

Output:

text New search index named hybrid-vector-search is building. Polling to check if the index is ready. This may take up to a minute. hybrid-vector-search is ready for querying.

  1. Define the MongoDB Vector Search index.

Create a create_search_index.py file in your project directory, and copy and paste the following code into the file.

```python from pymongo.mongo_client import MongoClient from pymongo.operations import SearchIndexModel import time

# Connect to your Atlas deployment uri = "" client = MongoClient(uri)

# Access your database and collection database = client["sample_mflix"] collection = database["embedded_movies"]

# Define your index search_index_model = SearchIndexModel( definition={ "mappings": { "dynamic": True, }, }, name="hybrid-full-text-search", )

# Create the index result = collection.create_search_index(model=search_index_model) print("New search index named " + result + " is building.")

# Wait for initial sync to complete print("Polling to check if the index is ready. This may take up to a minute.") predicate=None if predicate is None: predicate = lambda index: index.get("queryable") is True

while True: indices = list(collection.list_search_indexes(result)) if len(indices) and predicate(indices[0]): break time.sleep(5) print(result + " is ready for querying.")

client.close() ```

This index definition indexes the fullplot field as the autoEmbed field, for which MongoDB Vector Search automatically generates embeddings using the voyage-4 embedding model.

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

  1. Create the MongoDB Vector Search index.

shell python create_search_index.py

Output:

text New search index named hybrid-full-text-search is building. Polling to check if the index is ready. This may take up to a minute. hybrid-full-text-search is ready for querying.

This section demonstrates how to create the following indexes on the fullplot field in the sample_mflix.embedded_movies collection:

  • A MongoDB Vector Search autoEmbed type index for generating embeddings and running semantic search queries against that field.

  • A MongoDB Search index on the fullplot field for running full-text search against that field.

  • 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

  1. Specify the database and collection.

On the Database scree

(本文超出站点单文档体积上限,已截断)