Join us at MongoDB.local London on 7 May to unlock new possibilities for your data. Use WEB50 to save 50%.
Register now >
Docs Menu
Docs Home
/ /

MongoDB Search e MongoDB Vector Search Indexes

En esta guía, puedes aprender a crear y gestionar índices de MongoDB Search y MongoDB Vector Search. Estos índices te permiten utilizar las siguientes funcionalidades:

  • MongoDB Search: Realiza búsquedas rápidas de texto completo

  • MongoDB Vector Search: Realiza búsquedas semánticas (de similitud) en embeddings de vectores

MongoDB Search and MongoDB Vector Search indexes specify which fields to index, specify how these fields are indexed, and set other optional configurations.

Nota

Los métodos de gestión de índices de MongoDB Search se ejecutan de forma asíncrona. Los métodos del controlador pueden devolver un resultado antes de que la acción deseada se complete en el servidor.

This guide explains how to perform the following actions to manage your MongoDB Search and MongoDB Vector Search indexes:

  • Crear un modelo de índice de búsqueda

  • Create a Search Index

  • Crear múltiples índices de búsqueda

  • List Search Indexes

  • Actualizar un índice de búsqueda

  • Eliminar un índice de búsqueda

Nota

Datos de muestra

The examples in this guide use the embedded_movies colección en la base de datos sample_mflix, que es uno de los conjuntos de datos de muestra de Atlas. Consulta Cargar datos de muestra en la documentación de Atlas para obtener instrucciones sobre cómo importar los datos de muestra de Atlas.

Las siguientes secciones describen cómo crear modelos de índice para los índices de MongoDB Search y MongoDB Vector Search.

To create a MongoDB Search index, you must construct a CreateSearchIndexModel instance that sets your index specifications.

La clase CreateSearchIndexModel tiene las siguientes propiedades:

Propiedad
Tipo
Descripción

Definition

BsonDocument

Specifies the index definition. If you omit this setting, the driver creates a MongoDB Search index with dynamic mappings.

Name

string

Establece el nombre del índice. Si omite esta configuración, el controlador establece el nombre en default.

Type

SearchIndexType

Configura el tipo de índice. Si se omite esta configuración, el driver crea un índice de búsqueda de MongoDB de forma predeterminada.

El siguiente ejemplo crea una instancia CreateSearchIndexModel para proporcionar especificaciones para un índice denominado search_idx. El código especifica asignaciones estáticas de los campos title y released:

var def = new BsonDocument {
{ "mappings", new BsonDocument {
{ "dynamic", false },
{ "fields", new BsonDocument {
{ "title", new BsonDocument { {"type", "string" } } },
{ "released", new BsonDocument { { "type", "date" } } } } }
} }
};
var indexModel = new CreateSearchIndexModel(
"search_idx",
SearchIndexType.Search,
def
);

Para saber más sobre los mapeos de campos de búsqueda en MongoDB Search, consulta Definir mapeos de campos en la documentación de Atlas.

Para crear un índice de búsqueda vectorial en MongoDB Vector Search, debes crear una instancia de CreateVectorSearchIndexModel que establezca las especificaciones de tu índice.

The CreateVectorSearchIndexModel class inherits from the CreateSearchIndexModel class and has the following additional properties:

Propiedad
Tipo
Descripción

Field

FieldDefinition<TDocument>

Especifica el campo que contiene los vectores a indexar.

Similarity

VectorSimilarity

Sets the vector similarity function to use to search for the top K-nearest neighbors.

Dimensions

int

Especifica el número de dimensiones que la búsqueda aplica en el momento de indexación y en la query.

FilterFields

IReadOnlyList<FieldDefinition<TDocument>>

Especifica los campos que la búsqueda utiliza como filtros en la query vectorial.

Quantization

VectorQuantization?

Specifies the type of automatic vector quantization for the search vectors. If you don't set this property, the search uses no automatic quantization.

HnswMaxEdges

int?

Configura el número máximo de aristas que un nodo puede tener en el grafo Jerárquico de Mundos Navegables Pequeños.

HnswNumEdgeCandidates

int?

Establece el número máximo de nodos a evaluar para encontrar los vecinos más cercanos para conectarse a un nuevo nodo.

IncludedStoredFields

IReadOnlyList<FieldDefinition<TDocument>>

Specifies the fields to store in the index. MongoDB Vector Search returns only these fields when you set ReturnStoredSource to true in your query options. You cannot set both IncludedStoredFields and ExcludedStoredFields.

ExcludedStoredFields

IReadOnlyList<FieldDefinition<TDocument>>

Specifies the fields to exclude from being stored in the index. MongoDB Vector Search stores all other fields. When you set ReturnStoredSource to true in your query options, MongoDB Vector Search returns those stored fields. You cannot set both IncludedStoredFields and ExcludedStoredFields.

The following example creates a CreateVectorSearchIndexModel instance to provide specifications for an index named vs_idx. The code specifies the embedding path as PlotEmbedding, a class property that corresponds to the plot_embedding field in MongoDB. It also indexes 1536 dimensions, and uses the Euclidean vector similarity function.

var model = new CreateVectorSearchIndexModel<Movie> (
model => model.PlotEmbedding,
"vs_idx",
VectorSimilarity.Euclidean,
1536);

Para obtener más información sobre cómo definir índices de MongoDB Vector Search, consulta Cómo crear índices de campos para búsqueda vectorial en la documentación de Atlas.

Puedes utilizar un modelo de índices CreateAutoEmbeddingVectorSearchIndexModel para crear un índice de MongoDB Vector Search que automáticamente genere incrustaciones de vectores para los campos de texto.

The CreateAutoEmbeddingVectorSearchIndexModel has the following properties:

Propiedad
Tipo
Descripción

AutoEmbeddingModelName

string

Especifica el nombre del modelo de embedding que se utilizará para generar embeddings vectoriales. Para obtener una lista de los modelos compatibles, consulte Incrustaciones de texto en la documentación de VoyageAI.

Modality

VectorEmbeddingModality

Especifica el tipo de dato a insertar. Actualmente, la única modalidad admitida es VectorEmbeddingModality.Text.

Similarity

VectorSimilarity?

Sets the vector similarity function to search for the top K-nearest neighbors. If you don't set this property, the default depends on Quantization: DotProduct when Quantization is None or Scalar, and Euclidean when Quantization is Binary or BinaryNoRescore.

Dimensions

int

Specifies the number of output dimensions for the embedding model. If you don't set this property, the driver uses the embedding model's default dimensions.

Quantization

VectorQuantization?

Specifies the type of automatic vector quantization for the search vectors. If you don't set this property, the search uses no automatic quantization.

HnswMaxEdges

int?

Sets the maximum number of edges that a node can have in the Hierarchical Navigable Small Worlds graph. The default value is 16.

HnswNumEdgeCandidates

int?

Sets the maximum number of nodes to evaluate when finding the closest neighbors to connect to a new node. The default value is 100.

El siguiente ejemplo crea una instancia de CreateAutoEmbeddingVectorSearchIndexModel que proporciona especificaciones para un índice denominado auto_embedded_index. Este índice utiliza el modelo de embedding "voyage-4" para generar automáticamente embeddings vectoriales para el campo plot, e incluye también filtros opcionales para los campos runtime y year:

var model = new CreateAutoEmbeddingVectorSearchIndexModel<EmbeddedMovie>(
m => m.Plot,
"auto_embedding_index",
"voyage-4",
m => m.Runtime, m => m.Year // Optional filter fields
);

Puedes crear un índice de MongoDB Search o MongoDB Vector Search en una colección llamando al método SearchIndexes.CreateOne() en una instancia IMongoCollection. Este método acepta un modelo de índice como parámetro, especificado en una instancia de CreateSearchIndexModel o CreateVectorSearchIndexModel.

The following example creates a MongoDB Search index on the embedded_movies collection. The code creates a CreateSearchIndexModel that sets the index name and enables dynamic mapping. Then, the code passes the CreateSearchIndexModel instance to the SearchIndexes.CreateOne() method to create the MongoDB Search index:

var indexModel = new CreateSearchIndexModel(
"example_index",
SearchIndexType.Search,
new BsonDocument {
{ "mappings", new BsonDocument {
{ "dynamic", true },
} }
}
);
var result = movieCollection.SearchIndexes.CreateOne(indexModel);
Console.WriteLine("Created MongoDB Search index:\n{0}", result);
Created MongoDB Search index:
"example_index"

Puedes crear varios índices de MongoDB Search y MongoDB Vector Search llamando al método SearchIndexes.CreateMany() en una instancia IMongoCollection. Este método acepta un IEnumerable de instancias CreateSearchIndexModel o CreateVectorSearchIndexModel como parámetro.

Este ejemplo realiza las siguientes acciones:

  1. Creates a CreateSearchIndexModel instance that specifies a MongoDB Search index named as_idx

  2. Crea una instancia de CreateVectorSearchIndexModel que especifica un índice de MongoDB Vector Search llamado vs_idx

  3. Pasa un List de las instancias CreateSearchIndexModel y CreateVectorSearchIndexModel al método SearchIndexes.CreateMany()

  4. Creates the MongoDB Search and MongoDB Vector Search indexes on the embedded_movies collection

var searchModel = new CreateSearchIndexModel(
"as_idx",
SearchIndexType.Search,
new BsonDocument {
{ "mappings", new BsonDocument {
{ "dynamic", true },
} }
}
);
var vectorModel = new CreateVectorSearchIndexModel<Movie>(
m => m.PlotEmbedding,
"vs_idx",
VectorSimilarity.Euclidean,
1536);
var models = new List<CreateSearchIndexModel> { searchModel, vectorModel };
var indexes = movieCollection.SearchIndexes.CreateMany(models);
Console.WriteLine("Created Search indexes:\n{0} {1}", indexes.ToArray());
Created Search indexes:
as_idx vs_idx

You can access information about a collection's existing MongoDB Search and MongoDB Vector Search indexes by calling the SearchIndexes.List() method on the collection.

El siguiente ejemplo accede a información sobre los índices de MongoDB Search y MongoDB Vector Search creados en la sección Crear múltiples índices de búsqueda de esta página. El código llama al método SearchIndexes.List() e imprime una lista de los índices de MongoDB Search y MongoDB Vector Search en la colección:

var indexesList = movieCollection.SearchIndexes.List().ToList();
foreach (var i in indexesList)
{
Console.WriteLine(i);
}
{ "id": "...", "name": "as_idx", "status": "READY", "queryable":
true, "latestDefinitionVersion": {...}, "latestDefinition": {
"mappings": { "dynamic": true } }, "statusDetail": [...] }
{ "id": "...", "name": "vs_idx", "type": "vectorSearch", "status":
"READY", "queryable": true, ..., "latestDefinition": { "fields": [{
"type": "vector", "path": "plot_embedding", "numDimensions": 1536,
"similarity": "euclidean" }] }, "statusDetail": [...] }

Puedes actualizar un índice de MongoDB Search o MongoDB Vector Search llamando al método SearchIndexes.Update() en una instancia de IMongoCollection. Este método acepta los siguientes parámetros:

  • Nombre del índice que se actualizará

  • Modified index definition document

El siguiente ejemplo actualiza el índice de Vector Search llamado vs_index, creado en la sección Crear múltiples índices de búsqueda de esta página. El código crea un nuevo documento de definición de índice que instruye al índice a utilizar "dotProduct" como la función vectorial de similitud. Luego, el código llama al método SearchIndexes.Update() para actualizar el índice:

var updatedDef = new BsonDocument
{
{ "fields", new BsonArray
{
new BsonDocument
{
{ "type", "vector" },
{ "path", "plot_embedding" },
{ "numDimensions", 1536 },
{ "similarity", "dotProduct" }
}
}
}
};
movieCollection.SearchIndexes.Update("vs_index", updatedDef);

You can delete a MongoDB Search or MongoDB Vector Search index by calling the SearchIndexes.DropOne() method on an IMongoCollection instance. This method accepts the name of the index to delete as a parameter.

El siguiente ejemplo borra el índice de MongoDB Search llamado example_index creado en la sección Crear un índice de búsqueda de esta página. El código pasa el nombre del índice al método SearchIndexes.DropOne() para borrar el índice:

movieCollection.SearchIndexes.DropOne("example_index");

To learn about other indexes you can create by using the .NET/C# Driver, see the Create and Manage Indexes guide.

To learn more about MongoDB Search, see the following Atlas documentation:

Para obtener más información sobre MongoDB Vector Search, consulta la siguiente documentación de Atlas:

Para obtener más información sobre los métodos y tipos mencionados en esta guía, vea la siguiente documentación de la API:

Volver

Indexes

En esta página