Menu Docs
Página inicial do Docs
/ /

MongoDB Search and MongoDB Vector Search Indexes

In this guide, you can learn how to create and manage MongoDB Search and MongoDB Vector Search indexes. These indexes allow you to use the following features:

  • MongoDB Search: Perform fast, full-text searches

  • MongoDB Vector Search: Perform semantic (similarity) searches on vector embeddings

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

Observação

MongoDB Search index-management methods run asynchronously. The driver methods can return a result before the desired action completes on the server.

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

  • Crie um modelo de índice de pesquisa

  • Criar um índice de pesquisa

  • Criar múltiplos índices de pesquisa

  • Listar índices de pesquisa

  • Atualizar um Índice de Pesquisa

  • Excluir um índice de pesquisa

Observação

Dados de amostra

Os exemplos deste guia usam a coleção embedded_movies no banco de dados sample_mflix , que é um dos conjuntos de dados de amostra do Atlas . Para obter instruções sobre como importar os dados de amostra do Atlas, consulte Carregar dados de amostra na documentação do Atlas.

To create a MongoDB Search or MongoDB Vector Search index, you must first build a CreateSearchIndexModel instance that sets your index specifications.

O CreateSearchIndexModel tem as seguintes propriedades:

Propriedade
Tipo
Descrição

definition

BsonDocument

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

name

string

Define o nome do índice. Se você omitir esta configuração, o driver definirá o nome para default.

type

SearchIndexType

Sets the index type. If you omit this setting, the driver creates a MongoDB Search index by default.

To learn more about MongoDB Search field mappings, see Define Field Mappings in the Atlas documentation.

To learn more about defining MongoDB Vector Search indexes, see How to Index Fields for Vector Search in the Atlas documentation.

O exemplo seguinte cria uma instância CreateSearchIndexModel para fornecer especificações para um índice denominado search_idx. O código especifica mapeamentos estáticos dos campos title e 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
);

O exemplo a seguir cria uma instância de CreateSearchIndexModel para fornecer especificações para um índice chamado vs_idx. O código especifica o caminho de incorporação como plot_embedding, indexa 1536 dimensões e utiliza a função de similaridade vetorial "euclidean":

var def = new BsonDocument
{
{ "fields", new BsonArray
{
new BsonDocument
{
{ "type", "vector" },
{ "path", "plot_embedding" },
{ "numDimensions", 1536 },
{ "similarity", "euclidean" }
}
}
}
};
var indexModel = new CreateSearchIndexModel(
"vs_idx",
SearchIndexType.VectorSearch,
def
);

You can create a MongoDB Search or MongoDB Vector Search index on a collection by calling the SearchIndexes.CreateOne() method on an IMongoCollection instance. This method accepts an index model as a parameter, specified in a CreateSearchIndexModel instance.

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"

You can create multiple MongoDB Search and MongoDB Vector Search indexes by calling the SearchIndexes.CreateMany() method on an IMongoCollection instance. This method accepts an IEnumerable of CreateSearchIndexModel instances as a parameter.

Este exemplo executa as seguintes ações:

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

  2. Creates a CreateSearchIndexModel instance that specifies a MongoDB Vector Search index named vs_idx

  3. Passa um List de ambas as instâncias do CreateSearchIndexModel para o 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 CreateSearchIndexModel(
"vs_idx",
SearchIndexType.VectorSearch,
new BsonDocument
{
{ "fields", new BsonArray
{
new BsonDocument
{
{ "type", "vector" },
{ "path", "plot_embedding" },
{ "numDimensions", 1536 },
{ "similarity", "euclidean" }
}
}
}
}
);
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.

The following example accesses information about the MongoDB Search and MongoDB Vector Search indexes created in the Create Multiple Search Indexes section of this page. The code calls the SearchIndexes.List() method and prints a list of the MongoDB Search and MongoDB Vector Search indexes on the collection:

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": [...] }

You can update a MongoDB Search or MongoDB Vector Search index by calling the SearchIndexes.Update() method on an IMongoCollection instance. This method accepts the following parameters:

  • Nome do índice a ser atualizado

  • Documento de definição de índice modificado

O exemplo a seguir atualiza o índice do Vector Search denominado vs_index criado na seção Criar vários índices de pesquisa desta página. O código cria um novo documento de definição de índice que instrui o índice a usar "dotProduct" como a função de similaridade vetorial. Em seguida, o código chama o método SearchIndexes.Update() para atualizar o í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.

The following example deletes the MongoDB Search index named example_index created in the Create a Search Index section of this page. The code passes the index name to the SearchIndexes.DropOne() method to delete the index:

movieCollection.SearchIndexes.DropOne("example_index");

Para saber mais sobre outros índices que você pode criar usando o driver .NET/C#, consulte o guia Criar e gerenciar índices.

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

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

Para saber mais sobre os métodos e tipos mencionados neste guia, consulte a documentação da API abaixo:

Voltar

Indexes

Nesta página