Você pode configurar o MongoDB Vector Search para gerar e gerenciar automaticamente incorporações vetoriais para os dados de texto em seu cluster. Você pode criar um índice de pesquisa semântica de IA de um clique em seu cluster M10 ou Atlas superior e usar modelos de incorporação do Voyage AI, simplificando a indexação, a atualização e a query com vetores.
Quando você habilita as incorporações automatizadas, o MongoDB Vector Search gera automaticamente as incorporações usando o modelo de incorporação especificado no momento do índice para o campo de texto especificado em sua coleção Atlas e no momento da query para sua cadeia de caracteres em sua query em relação ao campo indexado para incorporações automatizadas.
Considerações
Importante
Você pode usar as incorporações automatizadas do MongoDB Vector Search em qualquer cluster M10 ou superior em qualquer provedor de nuvem. No entanto, o serviço que lida com o processo de inferência para gerar incorporações vetoriais é executado no Google Cloud Platform. Isso significa que seus dados são enviados para a Google Cloud Platform para geração e recuperação de incorporação, independentemente do provedor de nuvem do seu cluster. Fornecemos segurança de nível empresarial e, portanto, seus dados são armazenados apenas em seu cluster.
Os modelos de incorporação são executados em uma plataforma de inferência compartilhada e multilocatária. Portanto, durante o período de visualização, você deve usar conjuntos de dados com menos de 100k documento e executar queries somente para a avaliação do recurso e não para o teste de carga. Entre em contato com sua equipe de conta se você tiver um caso de uso com limites mais altos.
Embora não haja limites de taxa rígidos para sua carga de trabalho, existem limites globais. Se suas queries retornarem um erro de limite de taxa (erro 409), execute um backoff e tente novamente no código do seu aplicação . Isso permite que seu aplicação lide normalmente com os limites de taxa e garanta a funcionalidade contínua.
Pré-requisitos
Para habilitar a pesquisa vetorial usando incorporações automatizadas, você deve ter o seguinte:
M10ou cluster superiorUma coleção com um campo de texto que você deseja indexar para incorporações automatizadas.
Um dos seguintes clientes:
IU do Atlas para criação de índices
mongoshpara criar índices e executar queryDriver de nó 6.6.0 ou superior para criar índices e executar queries
Driver Python 4.7 ou superior para criar índices e executar query
Use o seguinte menu suspenso para definir o cliente para os procedimentos nesta página.
Índice de Vector Search do MongoDB para incorporações automatizadas
As seções a seguir descrevem a sintaxe e os campos do índice do MongoDB Vector Search para habilitar a geração automática de incorporações para campos de texto e orientam você nas etapas de configuração do índice para incorporações automatizadas.
Acesso necessário
Você precisa ter a função Project Data Access Admin ou superior para criar e gerenciar índices do MongoDB Vector Search.
Sintaxe do Índice
A seguir está a sintaxe para ativar a geração automática de incorporações:
1 { 2 "fields": [ 3 { 4 "type": "text", 5 "path": "<field-name>", 6 "model": "voyage-3-large | voyage-3.5 | voyage-3.5-lite" 7 } 8 ] 9 }
Campos do índice
Os seguintes campos são obrigatórios na definição do índice:
Campo | Tipo | Descrição |
| string | O tipo do campo. Para incorporações automatizadas, deve ser |
| string | O nome do campo na collection que você deseja indexar para incorporações automatizadas. |
| string | O modelo de incorporação de IA Voyage a ser usado para gerar as incorporações para o índice. Você pode especificar um dos seguintes modelos:
Depois de criar o índice, se você alterar o modelo de incorporação posteriormente, o MongoDB Vector Search gerará novas incorporações para o conjunto de dados. Enquanto o MongoDB Vector Search gera as incorporações, você pode continuar a consultar usando as incorporações antigas. Quando as incorporações antigas são substituídas por incorporações do novo modelo de incorporação, o MongoDB Vector Search remove as incorporações antigas. |
Considerações
Os campos de índice para incorporações automatizadas são mutuamente exclusivos com os seguintes campos de índice do tipo vector:
numDimensionssimilarityquantization
Se a sua coleção já tiver incorporações, você deve usar os campos de tipo vector para indexar as incorporações. Para aprender mais sobre como indexar campos com incorporações, consulte Como indexar campos para a pesquisa vetorial.
Você pode criar um índice com os tipos text e vector se quiser indexar um campo de texto para gerar automaticamente incorporações e também indexar um campo com suas próprias incorporações. O MongoDB Vector Search gerará automaticamente incorporações para consultas somente com o campo indexado como o tipo text . Você deve especificar incorporações na query para pesquisar o campo indexado como o tipo vector.
Você também pode indexar campos para pré-filtrar seus dados usando o tipo MongoDB Vector Search filter. A pré-filtragem reduz o número de documentos nos quais comparações de similaridade devem ser executadas, o que pode diminuir a latência da query e aumentar a precisão dos resultados da pesquisa. Para saber mais sobre como pré-filtrar seus dados, consulte Sobre o tipo filter.
Criar um índice para incorporações automatizadas
O procedimento a seguir percorre as etapas para ativar as incorporações automatizadas em seu índice do MongoDB Vector Search . Se você carregou o conjunto de dados sample_mflix.movies, o exemplo no procedimento demonstra como ativar as incorporações automatizadas para o campo fullplot na coleção.
No Atlas, VáGo para a Clusters página do seu projeto.
Se ainda não tiver sido exibido, selecione a organização que contém seu projeto no menu Organizations na barra de navegação.
Se ainda não estiver exibido, selecione o projeto desejado no menu Projects na barra de navegação.
Na barra lateral, clique em Clusters sob o título Database.
A página Clusters é exibida.
No Atlas, vá Search & Vector Search para a página para seu cluster.
Você pode acessar a página de pesquisa do MongoDB a partir da opção Search & Vector Search ou do Data Explorer.
Se ainda não tiver sido exibido, selecione a organização que contém seu projeto no menu Organizations na barra de navegação.
Se ainda não estiver exibido, selecione seu projeto no menu Projects na barra de navegação.
Na barra lateral, clique em Search & Vector Search sob o título Database.
Se você não tiver clusters, clique em Create cluster para criar um. Para saber mais, consulte Criar um cluster.
Se o seu projeto tiver vários clusters, selecione o cluster que deseja usar no menu suspenso Select cluster e clique em Go to Atlas Search.
A página Search & Vector Search é exibida.
Se ainda não tiver sido exibido, selecione a organização que contém seu projeto no menu Organizations na barra de navegação.
Se ainda não estiver exibido, selecione seu projeto no menu Projects na barra de navegação.
Na barra lateral, clique em Data Explorer sob o título Database.
Expanda o banco de dados e selecione a coleção.
Clique na guia Indexes da coleção.
A página Atlas Search é exibida.
Inicie a configuração do seu índice.
Faça as seguintes seleções na página e clique em Next.
Search Type | Selecione o tipo de índice Vector Search. |
Index Name and Data Source | Especifique as seguintes informações:
|
Configuration Method | Selecione JSON Editor. |
Exemplo
Por exemplo, insira movies_automated_embeddings para o nome do índice e selecione sample_mflix e movies no menu suspenso Database and Collection.
Defina seu índice.
No editor JSON, insira a seguinte definição de índice:
1 { 2 "fields": [ 3 { 4 "type": "text", 5 "path": "<FIELD-NAME>", 6 "model": "voyage-3-large | voyage-3.5 | voyage-3.5-lite" 7 } 8 ] 9 }
Exemplo
Por exemplo, para criar um índice que permita incorporações automatizadas usando o modelo voyage-3-large para o campo fullplot na coleção, insira o seguinte:
1 { 2 "fields": [ 3 { 4 "type": "text", 5 "path": "fullplot", 6 "model": "voyage-3-large" 7 } 8 ] 9 }
Crie seu índice.
Clique em Next.
Revise sua configuração de índice e clique em Create Vector Search Index.
Observação
A criação do índice pode levar algum tempo para ser concluída. Quando o índice está sendo criado, a coluna Status na IU do Atlas exibe Pending. Quando a criação do índice for concluída, a coluna Status na IU do Atlas exibirá Ready.
Conecte-se ao cluster do Atlas usando mongosh.
Para saber mais, consulte Conectar-se a um cluster via mongosh.
Alterne para o banco de dados que contém a collection para a qual você deseja criar o índice.
Para alternar, execute o seguinte comando:
use <DATABASE-NAME>
Aqui, <DATABASE-NAME> é o nome do banco de dados que você deseja usar.
Exemplo
Por exemplo, para alternar para o banco de dados sample_mflix , que contém a coleção movies, execute o seguinte comando:
use sample_mflix
Execute o método db.collection.createSearchIndex().
O método db.collection.createSearchIndex() tem a seguinte sintaxe:
1 db.<COLLECTION-NAME>.createSearchIndex( 2 "<INDEX-NAME>", 3 "vectorSearch", 4 { 5 "fields": [ 6 { 7 "type": "text", 8 "path": "<FIELD-NAME>", 9 "model": "voyage-3-large | voyage-3.5 | voyage-3.5-lite" 10 }, 11 { 12 "type": "filter", 13 "path": "<FIELD-NAME>" 14 }, 15 ... 16 ] 17 } 18 );
Exemplo
Por exemplo, para criar um índice que habilite incorporações automatizadas usando o modelo voyage-3-large para o campo fullplot na coleção, execute o seguinte comando em seu terminal:
1 db.movies.createSearchIndex( 2 "movies_automated_embeddings", 3 "vectorSearch", 4 { 5 "fields": [ 6 { 7 "type": "text", 8 "path": "fullplot", 9 "model": "voyage-3-large" 10 } 11 ] 12 } 13 );
Defina o índice no .js arquivo.
1 const { MongoClient } = require("mongodb"); 2 3 // connect to your Atlas deployment 4 const uri = "<CONNECTION-STRING>"; 5 const client = new MongoClient(uri); 6 7 async function run() { 8 try { 9 const database = client.db("<DATABASE-NAME>"); 10 const collection = database.collection("<COLLECTION-NAME>"); 11 12 // define your MongoDB Vector Search index 13 const index = { 14 "name": "<INDEX-NAME>", 15 "type": "vectorSearch", 16 "definition": { 17 "fields": [ 18 { 19 "type": "vector", 20 "path": "<FIELD-NAME>", 21 "model": "voyage-3-large | voyage-3.5 | voyage-3.5-lite" 22 }, 23 ] 24 } 25 } 26 // run the helper method 27 await collection.createSearchIndex("<INDEX-NAME>", index); 28 } finally { 29 await client.close(); 30 } 31 } 32 run().catch(console.dir);
Exemplo
Por exemplo, para criar um índice que habilite incorporações automatizadas usando o modelo voyage-3-large para o campo fullplot no namespace sample_mflix.movies, copie e cole o seguinte no arquivo create_index.js:
1 const { MongoClient } = require("mongodb"); 2 3 // connect to your Atlas deployment 4 const uri = "<CONNECTION-STRING>"; 5 const client = new MongoClient(uri); 6 7 async function run() { 8 try { 9 const database = client.db("sample_mflix"); 10 const collection = database.collection("movies"); 11 12 // define your MongoDB Vector Search index 13 const index = { 14 "name": "movies_automated_embeddings", 15 "type": "vectorSearch", 16 "definition": { 17 "fields": [ 18 { 19 "type": "text", 20 "path": "fullplot", 21 "model": "voyage-3-large" 22 } 23 ] 24 } 25 } 26 // run the helper method 27 await collection.createSearchIndex(index); 28 } finally { 29 await client.close(); 30 } 31 } 32 run().catch(console.dir);
Substitua os seguintes valores e salve o arquivo.
| A string de conexão do seu Atlas cluster. |
| O nome do banco de dados que contém a collection para a qual você deseja criar o índice. |
| O nome da coleção para a qual você deseja criar o índice. |
| O nome do campo na collection que você deseja indexar para incorporações automatizadas. |
| O nome do índice que você deseja criar. |
Defina o índice no .py arquivo.
1 from pymongo import MongoClient 2 from pymongo.operations import SearchIndexModel 3 4 client = pymongo.MongoClient("<CONNECTION-STRING>") 5 db = client["<DATABASE-NAME>"] 6 collection = db["<COLLECTION-NAME>"] 7 8 search_index_model = SearchIndexModel( 9 definition={ 10 "fields": [ 11 { 12 "type": "text", 13 "path": "<FIELD-NAME>", 14 "model": "voyage-3-large | voyage-3.5 | voyage-3.5-lite" 15 } 16 ] 17 }, 18 name="<INDEX-NAME>", 19 type="vectorSearch", 20 ) 21 result = collection.create_search_index(model=search_index_model) 22 print(result)
Exemplo
Por exemplo, para criar um índice que habilite incorporações automatizadas usando o modelo voyage-3-large para o campo fullplot no namespace sample_mflix.movies, copie e cole o seguinte no arquivo create_index.py:
1 from pymongo import MongoClient 2 from pymongo.operations import SearchIndexModel 3 4 client = MongoClient("<CONNECTION-STRING>") 5 db = client["sample_mflix"] 6 collection = db["movies"] 7 8 search_index_model = SearchIndexModel( 9 definition={ 10 "fields": [ 11 { 12 "type": "text", 13 "path": "fullplot", 14 "model": "voyage-3-large" 15 } 16 ] 17 }, 18 name="movies_automated_embeddings", 19 type="vectorSearch", 20 ) 21 result = collection.create_search_index(model=search_index_model) 22 print(result)
Substitua os seguintes valores e salve o arquivo.
| A string de conexão do seu Atlas cluster. |
| O nome do banco de dados que contém a collection para a qual você deseja criar o índice. |
| O nome da coleção para a qual você deseja criar o índice. |
| O nome do campo na collection que você deseja indexar para incorporações automatizadas. |
| O nome do índice que você deseja criar. |
Query de Vector Search do MongoDB com incorporações automatizadas
Depois de criar um índice com incorporações automatizadas, você pode executar queries de texto no campo indexado. O MongoDB Vector Search gera automaticamente incorporações para a cadeia de texto em sua consulta usando o mesmo modelo de incorporação especificado no índice. Ele usa as incorporações para pesquisar no índice documentos que sejam semanticamente semelhantes ao texto de query especificado.
The following sections describe the sintaxe e os campos do pipeline $vectorSearch para gerar automaticamente incorporações para seu texto de query em relação ao campo indexado para incorporações automatizadas e demonstram como executar consultas de pesquisa semântica nos campos indexados para incorporações automatizadas.
Sintaxe de consulta
A seguinte sintaxe demonstra como executar uma query em um campo indexado para incorporações automatizadas:
1 { 2 "$vectorSearch": { 3 "index": "<index-name>", 4 "limit": <number-of-results>, 5 "numCandidates": <number-of-candidates>, 6 "path": "<field-to-search>", 7 "query": "<query-string>" 8 } 9 }
Campos de query
Os campos a seguir são obrigatórios para uma query do MongoDB Vector Search usando incorporações automatizadas:
Campo | Tipo | necessidade | Descrição |
|---|---|---|---|
| booleano | Condicional | Este campo é obrigatório se Sinalizador que especifica se a pesquisa ENN ou ANN deve ser executada. O valor pode ser um dos seguintes:
Se omitido, o padrão é |
| string | Obrigatório | Nome do índice do MongoDB Vector Search a ser usado. A Vector Search do MongoDB não retorna resultados se você digitar incorretamente o nome do índice ou se o índice especificado ainda não existir no cluster. |
| número | Obrigatório | Número (somente do tipo |
| número | Condicional | Este campo é obrigatório se Número de vizinhos mais próximos a serem utilizados durante a pesquisa. O valor deve ser menor ou igual a ( |
| string | Obrigatório | Campo do tipo vetor indexado para pesquisa. |
| string | Obrigatório | Texto para o qual deverão ser geradas automaticamente as incorporações e realizar a pesquisa semântica. |
Considerações
Você pode executar uma query ANN ou ENN no campo indexado. Para aprender mais, consulte ANN Search e ENN Search.
Você não pode especificar embeddings de vetor em sua query em relação a campos indexados para embeddings automatizados. Em vez disso, você deve executar uma query de linguagem natural no campo. Quando você executa uma query de linguagem natural no campo indexado para incorporações automatizadas, o MongoDB Vector Search gera automaticamente as incorporações para o texto da query usando o mesmo modelo de incorporação do campo indexado. Em seguida, ele usa as incorporações geradas para realizar uma pesquisa semântica no campo indexado.
Opcionalmente, você pode especificar filter campos em sua query para pré-filtrar os documentos nos quais o MongoDB Vector Search executa a pesquisa semântica. Para saber mais, consulte Pré-filtro de Vector Search do MongoDB.
Opcionalmente, você também pode recuperar a pontuação dos documentos nos resultados. Para saber mais, consulte Pontuação de Vector Search do MongoDB.
Executar uma consulta usando incorporações automatizadas
Você não pode executar queries do MongoDB Vector Search na UI do Atlas . Utilize o mongosh ou um driver suportado para executar queries.
Conecte-se ao cluster do Atlas usando mongosh.
Para saber mais, consulte Conectar-se a um cluster via mongosh.
Execute o db.collection.aggregate() método com o $vectorSearch estágio.
O método db.collection.aggregate() tem a seguinte sintaxe:
1 db.<COLLECTION-NAME>.aggregate([ 2 { 3 "$vectorSearch": { 4 "index": "<INDEX-NAME>", 5 "path": "<FIELD-NAME>", 6 "query": "<QUERY-TEXT>", 7 "numCandidates": <NUMBER-OF-CANDIDATES-TO-CONSIDER>, 8 "limit": <NUMBER-OF-DOCUMENTS-TO-RETURN> 9 } 10 } 11 ])
Exemplo
Por exemplo, para executar uma consulta no campo fullplot na coleção movies para uma pesquisa semântica de filmes semanticamente semelhantes a young heroes caught
in epic struggles between light and darkness, copie, cole e execute a seguinte consulta.
1 db.movies.aggregate([ 2 { 3 "$vectorSearch": { 4 "index": "movies_automated_embeddings", 5 "path": "fullplot", 6 "query": "young heroes caught in epic struggles between light and darkness", 7 "numCandidates": 1000, 8 "limit": 10 9 } 10 }, 11 { 12 "$project": { 13 "_id": 0, 14 "title": 1, 15 "fullplot": 1, 16 "score": {"$meta": "vectorSearchScore"} 17 } 18 } 19 ])
1 [ 2 { 3 title: 'Day Watch', 4 fullplot: 'Anton belongs to the Forces of the Light as well as his powerful girlfriend and apprentice, but his son is a powerful teenager from the Darkness and Anton protects him. When the balance between Light and Darkness is affected by the death of some evil vampires, Anton is framed and accused of the murders, and he chases an ancient chalk that has the power of changing the destiny of its owner.', 5 score: 0.5449697971343994 6 }, 7 { 8 title: 'Dungeons & Dragons', 9 fullplot: "The Empire of Izmer has long been a divided land. The Mages - an elite group of magic-users - rule whilst the lowly commoners are powerless. Izmer's young Empress, Savina, wants equality and prosperity for all, but the evil Mage Profion is plotting to depose her and establish his own rule. The Empress possesses a scepter which controls Izmer's Golden Dragons. To challenge her rule, Profion must have the scepter, and tricks the Council of Mages into believing Savina is unfit to hold it. Knowing that Profion will bring death and destruction to Izmer, Savina must find the legendary Rod of Savrille, a mythical rod that has the power to control Red Dragons, a species even mightier than the Gold. Enter two thieves, Ridley and Snails, who unwittingly become instrumental in Savina's search for the Rod. Joined by a feisty Dwarf named Elwood, and helped by the Empress's expert tracker, the Elf Norda, the young heroes go in search of the Rod of Savrille. From the deadly maze of the Thieves Guild at Antius to an Elven Village, secret grotto and abandoned castles, Ridley and his band must outwit Profion's chief henchman Damodar at every turn while, back in Izmer, Profion prepares to do battle with the Empress. All depends on the Rod, but the outcome of the race to reach it first is far from certain, and Izmar's very survival hangs in the balance.", 10 score: 0.5414832830429077 11 }, 12 { 13 title: 'Brave Story', 14 fullplot: 'A young boy attempts to change his destiny by entering a magic gateway to another world; but on his quest to find the Tower of Fortune and be granted any wish, he must conjure up all his bravery to battle demons, his friends, and ultimately himself.', 15 score: 0.5404887795448303 16 }, 17 { 18 title: 'Justin and the Knights of Valour', 19 fullplot: 'Justin lives in a kingdom where bureaucrats rule and knights have been ousted. His dream is to be become one of the Knights of Valour, like his grandfather was, but his father Reginald, the chief counsel to the Queen, wants his son to follow in his footsteps and become a lawyer. After an inspiring visit to his beloved Grandmother and bidding farewell to his supposed lady-love Lara, Justin leaves home and embarks on a quest to become a knight. Along the way he meets the beautiful, feisty Talia, a quirky wizard called Melquiades, and the handsome Sir Clorex and is mentored by three monks; Blucher, Legantir and Braulio, who teach and test him in the ancient ways of the Knights of Valour. Whilst an unlikely candidate for knighthood, Justin must rise to the challenge quickly when banished former knight Sir Heraclio and his army, lead by Sota, return and threaten to destroy the Kingdom.', 20 score: 0.5374966859817505 21 }, 22 { 23 title: 'Forest Warrior', 24 fullplot: 'John McKenna is a spiritual being who is able to transform into bear, wolf or eagle. He lives in the forests of Tanglewood and has dedicated his life to protect them. One day a gang of evil lumberjacks led by Travis Thorne arrive Tanglewood to chop the forest down. McKenna cannot let this happen, and together with his new friends - Lords of the Tanglewood, a band of children who love to play in the forest - he battles against Thorne and his evil gang.', 25 score: 0.5331881642341614 26 }, 27 { 28 title: 'Forest Warrior', 29 fullplot: 'John McKenna is a spiritual being who is able to transform into bear, wolf or eagle. He lives in the forests of Tanglewood and has dedicated his life to protect them. One day a gang of evil lumberjacks led by Travis Thorne arrive Tanglewood to chop the forest down. McKenna cannot let this happen, and together with his new friends - Lords of the Tanglewood, a band of children who love to play in the forest - he battles against Thorne and his evil gang.', 30 score: 0.5331881642341614 31 }, 32 { 33 title: 'Catatan (Harian) si Boy', 34 fullplot: "A circle of friends risking their Friendship, Trust, Love and Hope in search of a legend. A young and privileged teenager with a golden heart, beset with challenges and tribulations we face today with the goal to open many young people's mind with inspirations and hopes that drive them in achieving their dreams. To get out of their comfort zone and finish what they started.", 35 score: 0.5322973728179932 36 }, 37 { 38 title: 'Bionicle: Mask of Light', 39 fullplot: "In a land of living machines, two young ones are chosen to seek the legendary Mask of Light to reveal the savior of all the lands from the dark forces of the Makuta. During the course of their adventure, they will call on the heroes of their people, the great Toa. These Toa, masters of nature's forces such as Fire, Wind, Earth & Water, try to protect the chosen ones as they seek their destiny.", 40 score: 0.5315042734146118 41 }, 42 { 43 title: 'Fear No Evil', 44 fullplot: 'High school student turns out to be personification of Lucifer. Two arch angels in human form (as women) take him on.', 45 score: 0.5295513868331909 46 }, 47 { 48 title: 'Tales of Vesperia: The First Strike', 49 fullplot: 'In a mythical kingdom, the mighty Imperial Knights harness a magical substance known as Aer to power their weapons and protect humanity from the monsters of the forest. But something strange is afoot. The Aer is somehow changing, causing the wilderness to waste away and stirring the woodland beasts to attack with greater frequency. As danger creeps steadily closer to civilization, two young recruits - Flynn, the rigid son of a fallen hero, and the rebellious and brash Yuri - must ride with their fellow Imperial Knights to distant ruins in hopes of uncovering the truth behind the transforming Aer. Some will not survive the thrilling journey. Some will be betrayed. If Flynn and Yuri cannot overcome their differences and learn to fight together, all will be lost for the people of the realm.', 50 score: 0.5276793241500854 51 } 52 ]
Defina a query no arquivo.
1 const { MongoClient } = require("mongodb"); 2 3 // connect to your Atlas cluster 4 const uri = "<CONNECTION-STRING>"; 5 6 const client = new MongoClient(uri); 7 8 async function run() { 9 try { 10 await client.connect(); 11 12 // set namespace 13 const database = client.db("<DATABASE-NAME>"); 14 const coll = database.collection("<COLLECTION-NAME>"); 15 16 // define pipeline 17 const agg = [ 18 { 19 '$vectorSearch': { 20 'index': '<INDEX-NAME>', 21 'path': '<FIELD-NAME>', 22 'query': "<QUERY-TEXT>", 23 'numCandidates': <NUMBER-OF-CANDIDATES-TO-CONSIDER>, 24 'limit': <NUMBER-OF-DOCUMENTS-TO-RETURN> 25 } 26 } 27 ]; 28 // run pipeline 29 const result = coll.aggregate(agg); 30 31 // print results 32 await result.forEach((doc) => console.dir(JSON.stringify(doc))); 33 } finally { 34 await client.close(); 35 } 36 } 37 run().catch(console.dir);
Exemplo
Por exemplo, no arquivo automated-embeddings-query.js , copie e cole o seguinte código para definir uma query no campo fullplot na collection movies para uma pesquisa semântica de filmes semanticamente semelhantes a young heroes caught in epic struggles
between light and darkness.
1 const { MongoClient } = require("mongodb"); 2 3 // connect to your Atlas cluster 4 const uri = "<CONNECTION-STRING>"; 5 6 const client = new MongoClient(uri); 7 8 async function run() { 9 try { 10 await client.connect(); 11 12 // set namespace 13 const database = client.db("sample_mflix"); 14 const coll = database.collection("movies"); 15 16 // define pipeline 17 const agg = [ 18 { 19 '$vectorSearch': { 20 'index': 'movies_automated_embeddings', 21 'path': 'fullplot', 22 'query': "young heroes caught in epic struggles between light and darkness", 23 'numCandidates': 1000, 24 'limit': 10 25 } 26 }, { 27 '$project': { 28 '_id': 0, 29 'fullplot': 1, 30 'title': 1, 31 'score': { 32 '$meta': 'vectorSearchScore' 33 } 34 } 35 } 36 ]; 37 // run pipeline 38 const result = coll.aggregate(agg); 39 40 // print results 41 await result.forEach((doc) => console.dir(JSON.stringify(doc))); 42 } finally { 43 await client.close(); 44 } 45 } 46 run().catch(console.dir);
Substitua o seguinte na query.
| Você cluster string de conexão. |
| Nome do banco de dados que contém a coleção. |
| Nome da collection que contém o campo indexado. |
| Nome do índice. |
| Nome do campo indexado. |
| String de texto para gerar incorporações e usar na pesquisa semântica. |
| Número de vizinhos mais próximos a serem considerados. |
| Número de documentos a retornar nos resultados. |
Execute a consulta.
node <FILE-NAME>.js
Aqui <FILE-NAME> está o nome do arquivo .js que você criou.
Exemplo
Por exemplo, para executar a query de exemplo no arquivo automated-embeddings-query.js, execute o seguinte comando:
node automated-embeddings-query.js
'{"title":"Day Watch","fullplot":"Anton belongs to the Forces of the Light as well as his powerful girlfriend and apprentice, but his son is a powerful teenager from the Darkness and Anton protects him. When the balance between Light and Darkness is affected by the death of some evil vampires, Anton is framed and accused of the murders, and he chases an ancient chalk that has the power of changing the destiny of its owner.","score":0.5449697971343994}' `{"title":"Dungeons & Dragons","fullplot":"The Empire of Izmer has long been a divided land. The Mages - an elite group of magic-users - rule whilst the lowly commoners are powerless. Izmer's young Empress, Savina, wants equality and prosperity for all, but the evil Mage Profion is plotting to depose her and establish his own rule. The Empress possesses a scepter which controls Izmer's Golden Dragons. To challenge her rule, Profion must have the scepter, and tricks the Council of Mages into believing Savina is unfit to hold it. Knowing that Profion will bring death and destruction to Izmer, Savina must find the legendary Rod of Savrille, a mythical rod that has the power to control Red Dragons, a species even mightier than the Gold. Enter two thieves, Ridley and Snails, who unwittingly become instrumental in Savina's search for the Rod. Joined by a feisty Dwarf named Elwood, and helped by the Empress's expert tracker, the Elf Norda, the young heroes go in search of the Rod of Savrille. From the deadly maze of the Thieves Guild at Antius to an Elven Village, secret grotto and abandoned castles, Ridley and his band must outwit Profion's chief henchman Damodar at every turn while, back in Izmer, Profion prepares to do battle with the Empress. All depends on the Rod, but the outcome of the race to reach it first is far from certain, and Izmar's very survival hangs in the balance.","score":0.5414832830429077}` '{"title":"Brave Story","fullplot":"A young boy attempts to change his destiny by entering a magic gateway to another world; but on his quest to find the Tower of Fortune and be granted any wish, he must conjure up all his bravery to battle demons, his friends, and ultimately himself.","score":0.5404887795448303}' '{"title":"Justin and the Knights of Valour","fullplot":"Justin lives in a kingdom where bureaucrats rule and knights have been ousted. His dream is to be become one of the Knights of Valour, like his grandfather was, but his father Reginald, the chief counsel to the Queen, wants his son to follow in his footsteps and become a lawyer. After an inspiring visit to his beloved Grandmother and bidding farewell to his supposed lady-love Lara, Justin leaves home and embarks on a quest to become a knight. Along the way he meets the beautiful, feisty Talia, a quirky wizard called Melquiades, and the handsome Sir Clorex and is mentored by three monks; Blucher, Legantir and Braulio, who teach and test him in the ancient ways of the Knights of Valour. Whilst an unlikely candidate for knighthood, Justin must rise to the challenge quickly when banished former knight Sir Heraclio and his army, lead by Sota, return and threaten to destroy the Kingdom.","score":0.5374966859817505}' '{"title":"Forest Warrior","fullplot":"John McKenna is a spiritual being who is able to transform into bear, wolf or eagle. He lives in the forests of Tanglewood and has dedicated his life to protect them. One day a gang of evil lumberjacks led by Travis Thorne arrive Tanglewood to chop the forest down. McKenna cannot let this happen, and together with his new friends - Lords of the Tanglewood, a band of children who love to play in the forest - he battles against Thorne and his evil gang.","score":0.5331881642341614}' '{"title":"Forest Warrior","fullplot":"John McKenna is a spiritual being who is able to transform into bear, wolf or eagle. He lives in the forests of Tanglewood and has dedicated his life to protect them. One day a gang of evil lumberjacks led by Travis Thorne arrive Tanglewood to chop the forest down. McKenna cannot let this happen, and together with his new friends - Lords of the Tanglewood, a band of children who love to play in the forest - he battles against Thorne and his evil gang.","score":0.5331881642341614}' `{"title":"Catatan (Harian) si Boy","fullplot":"A circle of friends risking their Friendship, Trust, Love and Hope in search of a legend. A young and privileged teenager with a golden heart, beset with challenges and tribulations we face today with the goal to open many young people's mind with inspirations and hopes that drive them in achieving their dreams. To get out of their comfort zone and finish what they started.","score":0.5322973728179932}` `{"title":"Bionicle: Mask of Light","fullplot":"In a land of living machines, two young ones are chosen to seek the legendary Mask of Light to reveal the savior of all the lands from the dark forces of the Makuta. During the course of their adventure, they will call on the heroes of their people, the great Toa. These Toa, masters of nature's forces such as Fire, Wind, Earth & Water, try to protect the chosen ones as they seek their destiny.","score":0.5315042734146118}` '{"title":"Fear No Evil","fullplot":"High school student turns out to be personification of Lucifer. Two arch angels in human form (as women) take him on.","score":0.5295513868331909}' '{"title":"Tales of Vesperia: The First Strike","fullplot":"In a mythical kingdom, the mighty Imperial Knights harness a magical substance known as Aer to power their weapons and protect humanity from the monsters of the forest. But something strange is afoot. The Aer is somehow changing, causing the wilderness to waste away and stirring the woodland beasts to attack with greater frequency. As danger creeps steadily closer to civilization, two young recruits - Flynn, the rigid son of a fallen hero, and the rebellious and brash Yuri - must ride with their fellow Imperial Knights to distant ruins in hopes of uncovering the truth behind the transforming Aer. Some will not survive the thrilling journey. Some will be betrayed. If Flynn and Yuri cannot overcome their differences and learn to fight together, all will be lost for the people of the realm.","score":0.5276793241500854}'
Defina a query no arquivo.
1 import pymongo 2 3 # connect to your Atlas cluster 4 client = pymongo.MongoClient("<CONNECTION-STRING>") 5 6 # define pipeline 7 pipeline = [ 8 { 9 '$vectorSearch': { 10 'index': '<INDEX-NAME>', 11 'path': '<FIELD-NAME>', 12 'query': '<QUERY-TEXT>', 13 'numCandidates': <NUMBER-OF-CANDIDATES-TO-CONSIDER>, 14 'limit': <NUMBER-OF-DOCUMENTS-TO-RETURN> 15 } 16 } 17 ] 18 19 # run pipeline 20 result = client["<DATABASE-NAME>"]["<COLLECTION-NAME>"].aggregate(pipeline) 21 22 # print results 23 for i in result: 24 print(i) 25
Exemplo
Por exemplo, no arquivo automated-embeddings-query.py , copie e cole o seguinte código para definir uma query no campo fullplot na collection movies para uma pesquisa semântica de filmes semanticamente semelhantes a young heroes caught in epic struggles
between light and darkness.
1 import pymongo 2 3 # connect to your Atlas cluster 4 client = pymongo.MongoClient("<CONNECTION-STRING>") 5 6 # define pipeline 7 pipeline = [ 8 { 9 '$vectorSearch': { 10 'index': 'movies_automated_embeddings', 11 'path': 'fullplot', 12 'query': "young heroes caught in epic struggles between light and darkness", 13 'numCandidates': 1000, 14 'limit': 10 15 }, 16 }, 17 { 18 '$project': { 19 '_id': 0, 20 'title': 1, 21 'fullplot': 1, 22 'score': {'$meta': 'vectorSearchScore'} 23 } 24 } 25 ] 26 27 # run pipeline 28 result = client["sample_mflix"]["movies"].aggregate(pipeline) 29 30 # print results 31 for i in result: 32 print(i) 33
Substitua o seguinte na query.
| Você cluster string de conexão. |
| Nome do banco de dados que contém a coleção. |
| Nome da collection que contém o campo indexado. |
| Nome do índice. |
| Nome do campo indexado. |
| String de texto para gerar incorporações e usar na pesquisa semântica. |
| Número de vizinhos mais próximos a serem considerados. |
| Número de documentos a retornar nos resultados. |
Execute a consulta.
python <FILE-NAME>.py
Aqui <FILE-NAME> está o nome do arquivo .py que você criou.
Exemplo
Por exemplo, para executar a query de exemplo no arquivo automated-embeddings-query.py, execute o seguinte comando:
python automated-embeddings-query.js
{'title': 'Day Watch', 'fullplot': 'Anton belongs to the Forces of the Light as well as his powerful girlfriend and apprentice, but his son is a powerful teenager from the Darkness and Anton protects him. When the balance between Light and Darkness is affected by the death of some evil vampires, Anton is framed and accused of the murders, and he chases an ancient chalk that has the power of changing the destiny of its owner.', 'score': 0.5449697971343994} {'title': 'Dungeons & Dragons', 'fullplot': "The Empire of Izmer has long been a divided land. The Mages - an elite group of magic-users - rule whilst the lowly commoners are powerless. Izmer's young Empress, Savina, wants equality and prosperity for all, but the evil Mage Profion is plotting to depose her and establish his own rule. The Empress possesses a scepter which controls Izmer's Golden Dragons. To challenge her rule, Profion must have the scepter, and tricks the Council of Mages into believing Savina is unfit to hold it. Knowing that Profion will bring death and destruction to Izmer, Savina must find the legendary Rod of Savrille, a mythical rod that has the power to control Red Dragons, a species even mightier than the Gold. Enter two thieves, Ridley and Snails, who unwittingly become instrumental in Savina's search for the Rod. Joined by a feisty Dwarf named Elwood, and helped by the Empress's expert tracker, the Elf Norda, the young heroes go in search of the Rod of Savrille. From the deadly maze of the Thieves Guild at Antius to an Elven Village, secret grotto and abandoned castles, Ridley and his band must outwit Profion's chief henchman Damodar at every turn while, back in Izmer, Profion prepares to do battle with the Empress. All depends on the Rod, but the outcome of the race to reach it first is far from certain, and Izmar's very survival hangs in the balance.", 'score': 0.5414832830429077} {'title': 'Brave Story', 'fullplot': 'A young boy attempts to change his destiny by entering a magic gateway to another world; but on his quest to find the Tower of Fortune and be granted any wish, he must conjure up all his bravery to battle demons, his friends, and ultimately himself.', 'score': 0.5404887795448303} {'title': 'Justin and the Knights of Valour', 'fullplot': 'Justin lives in a kingdom where bureaucrats rule and knights have been ousted. His dream is to be become one of the Knights of Valour, like his grandfather was, but his father Reginald, the chief counsel to the Queen, wants his son to follow in his footsteps and become a lawyer. After an inspiring visit to his beloved Grandmother and bidding farewell to his supposed lady-love Lara, Justin leaves home and embarks on a quest to become a knight. Along the way he meets the beautiful, feisty Talia, a quirky wizard called Melquiades, and the handsome Sir Clorex and is mentored by three monks; Blucher, Legantir and Braulio, who teach and test him in the ancient ways of the Knights of Valour. Whilst an unlikely candidate for knighthood, Justin must rise to the challenge quickly when banished former knight Sir Heraclio and his army, lead by Sota, return and threaten to destroy the Kingdom.', 'score': 0.5374966859817505} {'title': 'Forest Warrior', 'fullplot': 'John McKenna is a spiritual being who is able to transform into bear, wolf or eagle. He lives in the forests of Tanglewood and has dedicated his life to protect them. One day a gang of evil lumberjacks led by Travis Thorne arrive Tanglewood to chop the forest down. McKenna cannot let this happen, and together with his new friends - Lords of the Tanglewood, a band of children who love to play in the forest - he battles against Thorne and his evil gang.', 'score': 0.5331881642341614} {'title': 'Forest Warrior', 'fullplot': 'John McKenna is a spiritual being who is able to transform into bear, wolf or eagle. He lives in the forests of Tanglewood and has dedicated his life to protect them. One day a gang of evil lumberjacks led by Travis Thorne arrive Tanglewood to chop the forest down. McKenna cannot let this happen, and together with his new friends - Lords of the Tanglewood, a band of children who love to play in the forest - he battles against Thorne and his evil gang.', 'score': 0.5331881642341614} {'title': 'Catatan (Harian) si Boy', 'fullplot': "A circle of friends risking their Friendship, Trust, Love and Hope in search of a legend. A young and privileged teenager with a golden heart, beset with challenges and tribulations we face today with the goal to open many young people's mind with inspirations and hopes that drive them in achieving their dreams. To get out of their comfort zone and finish what they started.", 'score': 0.5322973728179932} {'title': 'Bionicle: Mask of Light', 'fullplot': "In a land of living machines, two young ones are chosen to seek the legendary Mask of Light to reveal the savior of all the lands from the dark forces of the Makuta. During the course of their adventure, they will call on the heroes of their people, the great Toa. These Toa, masters of nature's forces such as Fire, Wind, Earth & Water, try to protect the chosen ones as they seek their destiny.", 'score': 0.5315042734146118} {'title': 'Fear No Evil', 'fullplot': 'High school student turns out to be personification of Lucifer. Two arch angels in human form (as women) take him on.', 'score': 0.5295513868331909} {'title': 'Tales of Vesperia: The First Strike', 'fullplot': 'In a mythical kingdom, the mighty Imperial Knights harness a magical substance known as Aer to power their weapons and protect humanity from the monsters of the forest. But something strange is afoot. The Aer is somehow changing, causing the wilderness to waste away and stirring the woodland beasts to attack with greater frequency. As danger creeps steadily closer to civilization, two young recruits - Flynn, the rigid son of a fallen hero, and the rebellious and brash Yuri - must ride with their fellow Imperial Knights to distant ruins in hopes of uncovering the truth behind the transforming Aer. Some will not survive the thrilling journey. Some will be betrayed. If Flynn and Yuri cannot overcome their differences and learn to fight together, all will be lost for the people of the realm.', 'score': 0.5276793241500854}