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

MongoDB Vector Search

Neste guia, você verá como usar a funcionalidade Vector Search do MongoDB no driver Java . A classe de construtores Aggregates fornece o método assistente vectorSearch() que você pode usar para criar um estágio de pipeline $vectorSearch. Esse estágio do pipeline permite realizar uma pesquisa semântica em seus documentos. Uma pesquisa semântica é um tipo de pesquisa que localiza informações com significado semelhante, mas não necessariamente idênticas, ao termo ou frase de pesquisa fornecida.

Importante

Compatibilidade de recursos

Para saber quais versões do MongoDB Atlas suportam este recurso, consulte Limitações na documentação do MongoDB Atlas.

Para usar esse recurso, você deve criar um índice de pesquisa de vetor e indexar suas incorporações de vetor. Para aprender a criar programaticamente um índice de pesquisa vetorial, consulte a seção Índices do MongoDB Search e Vector Search no guia de Índices. Para saber mais sobre incorporações de vetor, consulte Como indexar incorporações de vetor para pesquisa vetorial na documentação do Atlas.

Depois de criar um índice de pesquisa vetorial nas incorporações vetoriais, você poderá fazer referência a esse índice no estágio do pipeline, conforme mostrado na seção a seguir.

O exemplo abaixo mostra como construir um aggregation pipeline que utiliza os métodos vectorSearch() e project() para calcular uma pontuação de pesquisa vetorial:

// 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")));

Dica

Tipo de vetor de query

O exemplo anterior cria uma instância de BinaryVector para servir como o vetor de consulta, mas você também pode criar um List de Double instâncias. No entanto, recomendamos que você use o tipo BinaryVector para melhorar a eficiência do armazenamento.

O exemplo a seguir mostra como executar a agregação e imprimir a meta-score do vector search a partir do resultado da agregação pipeline anterior:

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

Dica

Exemplos de Vector Search do driver Java

Visite a documentação do Atlas para encontrar mais tutoriais sobre como usar o driver Java para executar o Atlas Vector Search.

Você pode automatizar a geração de vetores para pesquisas de texto executando a query em um índice de incorporação automática do MongoDB Vector Search . Para saber mais sobre como criar um índice de incorporação automática, consulte Modelo de índice de pesquisa de incorporação automática do MongoDB .

O exemplo a seguir constrói uma query do MongoDB Vector Search que pesquisa similaridade semântica com a frase time travel no campo plot. A consulta utiliza um índice MongoDB Vector Search de incorporação automática no campo plot denominado 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.
---

Observação

Ao usar um índice de incorporação automática, forneça diretamente o texto a ser pesquisado, em vez de uma representação vetorial desse texto.

Para obter mais informações sobre a incorporação automática de índices do MongoDB Vector Search , consulte a seção Modelo de índice do MongoDB Auto-Embedding Search do guia Índices.

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

Voltar

MongoDB Search

Nesta página