Make the MongoDB docs better! We value your opinion. Share your feedback for a chance to win $100.
Click here >
Docs Menu
Docs Home
/ /

Búsqueda vectorial de MongoDB

En esta guía, puede aprender a usar la funcionalidad Búsqueda Vectorial de MongoDB en el driver Java. La Aggregates La clase desarrolladores proporciona el método asistente vectorSearch() que puede usar para crear una etapa de pipeline $vectorSearch. Esta etapa del pipeline permite realizar una búsqueda semántica en los documentos. Una búsqueda semántica es un tipo de búsqueda que localiza información con un significado similar, pero no necesariamente idéntica, al término o frase de búsqueda proporcionada.

Importante

Compatibilidad de características

Para aprender qué versiones de MongoDB Atlas admiten esta funcionalidad, consulte Limitaciones en la documentación de MongoDB Atlas.

Para usar esta funcionalidad, debes crear un índice de búsqueda vectorial e indexar tus incrustaciones vectoriales. Para aprender cómo crear programáticamente un índice de búsqueda vectorial, consulta la MongoDB Search e Índices de búsqueda de vectores sección en la guía de Índices. Para aprender más sobre incrustaciones vectoriales, revisa Cómo indexar vector embeddings para búsqueda vectorial en la documentación de Atlas.

Una vez que hayas creado un índice de búsqueda vectorial en tus incrustaciones vectoriales, puedes hacer referencia a este índice en la etapa de tu pipeline, como se muestra en la siguiente sección.

El siguiente ejemplo muestra cómo compilar un pipeline de agregación que utiliza los métodos vectorSearch() y project() para calcular una puntuación de búsqueda vectorial:

// Create an instance of the BinaryVector class as the query vector
BinaryVector queryVector = BinaryVector.floatVector(
new float[]{0.0001f, 1.12345f, 2.23456f, 3.34567f, 4.45678f});
// Specify the index name for the vector embedding index
String indexName = "mflix_movies_embedding_index";
// Specify the path of the field to search on
FieldSearchPath fieldSearchPath = fieldPath("plot_embedding");
// Limit the number of matches to 1
int limit = 1;
// Create a pre-filter to only search within a subset of documents
VectorSearchOptions options = exactVectorSearchOptions()
.filter(gte("year", 2016));
// Create the vectorSearch pipeline stage
List<Bson> pipeline = asList(
vectorSearch(
fieldSearchPath,
queryVector,
indexName,
limit,
options),
project(
metaVectorSearchScore("vectorSearchScore")));

Tip

Query Vector Type

El ejemplo anterior crea una instancia de BinaryVector para que sirva como vector de query, pero también puedes crear un List de instancias de Double. Sin embargo, se recomienda usar el tipo BinaryVector para mejorar la eficiencia del almacenamiento.

El siguiente ejemplo muestra cómo ejecutar la agregación e imprimir la meta-puntuación de búsqueda vectorial a partir del resultado de la anterior pipeline de agregación:

Document found = collection.aggregate(pipeline).first();
double score = found.getDouble("vectorSearchScore").doubleValue();
System.out.println("vectorSearch score: " + score);

Tip

Ejemplos de búsqueda vectorial con Java Driver

Visite la documentación de Atlas para encontrar más tutoriales sobre el uso del controlador Java para realizar búsquedas vectoriales en Atlas.

Se pueden automatizar la generación de vectores para búsquedas de texto consultando un índice de búsqueda vectorial de MongoDB con autoembebido. Para saber cómo crear un índice de auto-embebimiento, consulta el Model de Índice de Búsqueda de Auto-Embebimiento de MongoDB.

El siguiente ejemplo construye una query de búsqueda vectorial de MongoDB que busca similitud semántica con la frase time travel en el campo plot. La query utiliza un índice de búsqueda vectorial de MongoDB de auto-incrustación en el campo plot llamado auto_embedding_index:

List<Bson> pipeline = asList(
vectorSearch(
fieldPath("plot"),
textQuery("time travel"),
"auto_embedding_index",
10L,
approximateVectorSearchOptions(150L)
),
project(
fields(include("title", "plot"), excludeId())
)
);
List<Document> results = collection.aggregate(pipeline).into(new ArrayList<>());
for (Document doc : results) {
System.out.println("Title: " + doc.getString("title"));
System.out.println("Plot: " + doc.getString("plot"));
System.out.println("---");
}
Title: Manuel on the Island of Wonders
Plot: Manuel's fantasy travel through Time goes from Long Ago (Episode 1 - O jardim proibido / Le Jardin interdit) through Now (Episode 2 - O pique-nique dos sonhos / Le Pique-nique des rèves), ...
---
Title: 11 Minutes Ago
Plot: Traveling in 11-minute increments, a time-tumbler from 48-years in the future spends two years of his life weaving through a two-hour wedding reception.
---
Title: Time Freak
Plot: A neurotic inventor creates a time machine and gets lost traveling around yesterday.
---
Title: Timecrimes
Plot: A man accidentally gets into a time machine and travels back in time nearly an hour. Finding himself will be the first of a series of disasters of unforeseeable consequences.
---
Title: The Little Girl Who Conquered Time
Plot: A high-school girl acquires the ability to time travel.
---
Title: Time Traveller
Plot: A high-school girl acquires the ability to time travel.
---
Title: Je t'aime je t'aime
Plot: Recovering from an attempted suicide, a man is selected to participate in a time travel experiment that has only been tested on mice. A malfunction in the experiment causes the man to ...
---
Title: A.P.E.X.
Plot: A time-travel experiment in which a robot probe is sent from the year 2073 to the year 1973 goes terribly wrong thrusting one of the project scientists, a man named Nicholas Sinclair into a...
---
Title: The Ah of Life
Plot: Theoretical mathematician, Nigel Kline finds himself the subject of his own vertical time study. Entering into Einstein's relativity, three versions of Nigel face off with each other, weaving time and space in a world of fluid moments.
---
Title: About Time
Plot: At the age of 21, Tim discovers he can travel in time and change what happens and has happened in his own life. His decision to make his world a better place by getting a girlfriend turns out not to be as easy as you might think.
---

Nota

Al utilizar un índice de auto-incrustación, proporciona directamente el texto a buscar en lugar de una representación vectorial de ese texto.

Para obtener más información sobre los índices de búsqueda vectorial de autoincrustación de MongoDB, consulta la sección model de índice de búsqueda de Autoincrustación de MongoDB de la guía de índices.

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

MongoDB búsqueda

En esta página