Importante
Los índices de búsqueda vectorial de MongoDB de text Este tipo de datos está en desuso, ya que nos preparamos para pasar de la vista previa privada a la vista previa pública. Para obtener más información, consulte las funciones de vista previa.
Puedes configurar MongoDB Vector Search para que genere y gestione automáticamente las incrustaciones vectoriales de los datos de texto en tu clúster. Puedes crear un índice de búsqueda semántica de IA con un solo clic en tu clúster de Atlas M10 o superior y utilizar modelos de embedding de Voyage AI, simplificando la indexación, actualización y consulta con vectores.
Cuando habilita la incrustación automatizada, MongoDB Vector Search genera automáticamente las incrustaciones utilizando el modelo de incrustación especificado en el momento de indexación para el campo de texto especificado en su colección Atlas y en el momento de la consulta para su string de texto en su query contra el campo indexado para incrustaciones automatizadas.
Considerations
Importante
Puedes utilizar el Embedding Automatizado de Búsqueda Vectorial de MongoDB en cualquier clúster M10 o superior en cualquier proveedor de nube. Sin embargo, el servicio que gestiona el proceso de inferencia para generar incrustaciones vectoriales se ejecuta en Google Cloud. Esto significa que tus datos se envían a Google Cloud para la generación y recuperación de incrustaciones, independientemente del proveedor de nube de tu clúster. Proporcionamos seguridad de nivel empresarial y, por lo tanto, sus datos sólo se almacenan en su clúster.
Los modelos de embedding se ejecutan en una plataforma de inferencia compartida y multi-inquilino. Por lo tanto, durante el período de vista previa, debe utilizar conjuntos de datos con menos de 100k documentos y ejecutar queries solo para la evaluación de la funcionalidad y no para las pruebas de carga. Contacta con tu equipo de cuenta si tienes un caso de uso con límites superiores.
Aunque no hay límites estrictos de velocidad para tu carga de trabajo, hay límites globales. Si tus queries devuelven un error de límite de velocidad (error 409), realiza un backoff y vuelve a intentarlo en el código de tu aplicación. Esto permite que tu aplicación gestione adecuadamente los límites de velocidad y garantice su funcionalidad continua.
Requisitos previos
Para habilitar la búsqueda vectorial utilizando la Incorporación Automática, debes contar con lo siguiente:
M10o clúster superiorUna colección con un campo de texto que deseas indexar para incrustaciones automáticas.
Uno de los siguientes clientes:
Interfaz de usuario de Atlas para crear índices
mongoshpara crear índices y ejecutar consultasnodo Driver 6.6.0 o superior para crear índices y ejecutar queries
Controlador 4.7 de Python o superior para crear índices y ejecutar consultas
Utiliza el siguiente menú desplegable para establecer el cliente para los procedimientos de esta página.
Índice de MongoDB Vector Search para embedding automatizado
Las siguientes secciones describen la sintaxis y los campos del índice de búsqueda vectorial de MongoDB para habilitar la generación automática de embeddings para campos de texto, y le guiarán a través de los pasos para configurar su índice para la incrustación automática.
Acceso requerido
Necesitas el Project Data Access Admin o un rol superior para crear y gestionar índices de MongoDB Vector Search.
Sintaxis del índice
La siguiente es la sintaxis para habilitar la generación automática de incrustaciones:
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 de índices
Se requieren los siguientes campos en la definición del índice:
Campo | Tipo | Descripción |
|---|---|---|
| string | El tipo del campo. Para el embedding automatizado, esto debe ser |
| string | El nombre del campo en la colección que desea indexar para la inserción automatizada. |
| string | El modelo de incrustación de IA de Voyage que se utilizará para generar las incrustaciones para el índice. Puede especificar uno de los siguientes modelos:
Tras crear el índice, si cambia el modelo de incrustación posteriormente, MongoDB Vector Search genera nuevas incrustaciones para el conjunto de datos. Mientras MongoDB Vector Search genera las incrustaciones, puede continuar consultando utilizando las incrustaciones antiguas. Cuando las incrustaciones antiguas se reemplazan con incrustaciones del nuevo modelo, MongoDB Vector Search las elimina. |
Considerations
Los campos de índices para la inserción automatizada son mutuamente excluyentes con los siguientes campos de índice de tipo vector:
numDimensionssimilarityquantization
Si tu colección ya tiene embeddings, debes usar los campos de tipo vector para indexar los embeddings. Para obtener más información sobre indexar campos con incrustaciones,
consulta Cómo indexar campos para la búsqueda vectorial.
Puede crear un índice con ambos tipos text y vector si desea indexar un campo de texto para generar incrustaciones automáticamente y también indexar un campo con sus propias incrustaciones. MongoDB Vector Search generará automáticamente embeddings para las consultas solo contra el campo indexado como el tipo text. Debe especificar embeddings en la query para buscar en el campo indexado como tipo vector.
También puede indexar campos para prefiltrar sus datos mediante el tipo de búsqueda filter vectorial de MongoDB. El prefiltrado reduce la cantidad de documentos con los que se realizan comparaciones de similitud, lo que puede disminuir la latencia de las consultas y aumentar la precisión de los resultados de búsqueda. Para obtener más información sobre el prefiltrado de sus datos, consulte Acerca del filter tipo.
Crear un índice para incrustación automatizada
El siguiente procedimiento explica los pasos para habilitar incrustaciones automatizadas en tu índice de MongoDB Vector Search. Si ha cargado el conjunto de datos sample_mflix.movies, el ejemplo del procedimiento demuestra cómo activar la incorporación automática para el campo fullplot en la colección.
En Atlas, ve a Clusters página para tu proyecto.
Si aún no se muestra, seleccione la organización que contiene su proyecto deseado en el menú Organizations de la barra de navegación.
Si aún no aparece, selecciona el proyecto deseado en el menú Projects de la barra de navegación.
En la barra lateral, haz clic en Clusters en la sección Database.
La página de clústeres se muestra.
En Atlas, vaya a la Search & Vector Search página de su clúster.
Puedes ir a la página de búsqueda de MongoDB desde la opción Search & Vector Search o desde el Data Explorer.
Si aún no aparece, se debe seleccionar la organización que contiene el proyecto en el menú Organizations de la barra de navegación.
Si aún no se muestra, seleccione su proyecto en el menú Projects de la barra de navegación.
En la barra lateral, haz clic en Search & Vector Search en la sección Database.
Si no tienes clústeres, haz clic en Create cluster para crear uno. Para obtener más información, consulta Crear un clúster.
Si el proyecto tiene varios clústeres, se debe seleccionar el clúster que se desea usar en el menú desplegable Select cluster y luego se debe hacer clic en Go to Search.
Aparece la página de Búsqueda y Búsqueda Vectorial.
Si aún no aparece, se debe seleccionar la organización que contiene el proyecto en el menú Organizations de la barra de navegación.
Si aún no se muestra, seleccione su proyecto en el menú Projects de la barra de navegación.
En la barra lateral, haz clic en Data Explorer en la sección Database.
Expanda la base de datos y seleccione la colección.
Haga clic en la pestaña Indexes para la colección.
Haga clic en el enlace Search and Vector Search en el banner.
Aparece la página de Búsqueda y Búsqueda Vectorial.
Se debe iniciar la configuración del índice.
Realiza las siguientes selecciones en la página y luego haz clic en Next.
Search Type | Seleccione el tipo de índice Vector Search. |
Index Name and Data Source | Especifique la siguiente información:
|
Configuration Method | Seleccione JSON Editor. |
Ejemplo
Por ejemplo, introduzca movies_automated_embeddings para el nombre del índice y seleccione sample_mflix y movies del desplegable Database and Collection.
Define tu índice.
En el editor JSON, ingrese la siguiente definición 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 }
Ejemplo
Por ejemplo, para crear un índice que habilite incrustaciones automatizadas usando el modelo voyage-3-large para el campo fullplot de la colección, ingrese lo siguiente:
1 { 2 "fields": [ 3 { 4 "type": "text", 5 "path": "fullplot", 6 "model": "voyage-3-large" 7 } 8 ] 9 }
Crea tu índice.
Haga clic en Next.
Revise la configuración de su índice y haga clic en Create Vector Search Index.
Nota
La creación del índice puede tardar algún tiempo en completarse. Cuando se está creando el índice, la columna Status en la Atlas Interfaz de Usuario muestra Pending. Cuando se complete la creación del índice, la columna Status en la Interfaz de Usuario de Atlas mostrará Ready.
Conéctate al clúster Atlas usando mongosh.
Para obtener más información, consulte Conectarse a un clúster a través de mongosh.
Cambie a la base de datos que contiene la colección para la que desea crear el índice.
Para cambiar, ejecute el siguiente comando:
use <DATABASE-NAME>
Aquí, <DATABASE-NAME> es el nombre de la base de datos que desea utilizar.
Ejemplo
Por ejemplo, para cambiar a la base de datos sample_mflix, que contiene la colección movies, ejecuta el siguiente comando:
use sample_mflix
Ejecute el método db.collection.createSearchIndex().
El método db.collection.createSearchIndex() tiene la siguiente sintaxis:
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 );
Ejemplo
Por ejemplo, para crear un índice que permita incorporaciones automáticas mediante el uso del modelo voyage-3-large para el campo fullplot en la colección, ejecute el siguiente comando en su 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 );
Define el índice en el archivo .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("<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);
Ejemplo
Por ejemplo, para crear un índice que permita incorporaciones automáticas mediante el uso del modelo voyage-3-large para el campo fullplot en el espacio de nombres sample_mflix.movies, copie y pegue lo siguiente en el archivo 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);
Sustituye los siguientes valores y guarda el archivo.
| La cadena de conexión para tu clúster de Atlas. |
| El nombre de la base de datos que contiene la colección para la que deseas crear el índice. |
| El nombre de la colección para la que se quiere crear el índice. |
| El nombre del campo en la colección que desea indexar para la inserción automatizada. |
| El nombre del índice que deseas crear. |
Define el índice en el archivo .py.
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)
Ejemplo
Por ejemplo, para crear un índice que permita incorporaciones automáticas mediante el uso del modelo voyage-3-large para el campo fullplot en el espacio de nombres sample_mflix.movies, copie y pegue lo siguiente en el archivo 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)
Sustituye los siguientes valores y guarda el archivo.
| La cadena de conexión para tu clúster de Atlas. |
| El nombre de la base de datos que contiene la colección para la que deseas crear el índice. |
| El nombre de la colección para la que se quiere crear el índice. |
| El nombre del campo en la colección que desea indexar para la inserción automatizada. |
| El nombre del índice que deseas crear. |
query vectorial de MongoDB con embedding automatizado
Tras crear un índice con la función de incrustación automatizada, puede ejecutar consultas de texto en el campo indexado. MongoDB Vector Search genera automáticamente incrustaciones para la cadena de texto de su consulta utilizando el mismo modelo de incrustación especificado en el índice. Utiliza las incrustaciones para buscar en el índice documentos semánticamente similares al texto de la consulta especificado.
Las siguientes secciones describen la $vectorSearch sintaxis y campos de la canalización para la generación automática de embeddings para tu texto de query en el campo indexado para Embeddings Automáticos y demuestran cómo ejecutar consultas de búsqueda semántica en los campos indexados para Embeddings Automáticos.
Query sintaxis
La siguiente sintaxis demuestra cómo ejecutar una query en un campo indexado para Embedding Automatizado:
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 consulta
Los siguientes campos son necesarios para una query de MongoDB Vector Search utilizando embeddings automáticos:
Campo | Tipo | Necesidad | Descripción |
|---|---|---|---|
| booleano | Condicional | Este campo es obligatorio si se omite Bandera que especifica si se debe ejecutar ENN or ANN search. El valor puede ser uno de los siguientes:
Si se omite, es por defecto |
| string | Requerido | Nombre del índice de búsqueda vectorial de MongoDB que se utilizará. La búsqueda vectorial de MongoDB no devuelve resultados si escribe mal el nombre del índice o si el índice especificado no existe ya en el clúster. |
| Número | Requerido | Número de documentos (solo de tipo |
| Número | Condicional | Este campo es obligatorio si Número de vecinos más cercanos a utilizar durante la búsqueda. El valor debe ser menor o igual a ( |
| string | Requerido | Campo de tipo vector indexado para la búsqueda. |
| string | Requerido | Texto para el que generar automáticamente embeddings y realizar la búsqueda semántica. |
Considerations
Puede ejecutar una consulta ANN o ENN en el campo indexado. Para obtener más información, consulte Búsqueda ANN y Búsqueda ENN.
No se pueden especificar incrustaciones vectoriales en la query de campos indexados para la incrustación automatizada. En su lugar, debes ejecutar una query en lenguaje natural contra el campo. Cuando ejecutes una query en lenguaje natural contra el campo indexado para embedding automatizado, MongoDB Vector Search genera automáticamente los embeddings para el texto de la query utilizando el mismo modelo de embeddings que el campo indexado. Luego utiliza las incrustaciones generadas para llevar a cabo una búsqueda semántica en el campo indexado.
Opcionalmente, puede especificar filter campos en su consulta para prefiltrar los documentos en los que MongoDB Vector Search realiza la búsqueda semántica. Para obtener más información, consulte Prefiltrado de MongoDB Vector Search.
También puedes, de manera opcional, recuperar la puntuación de los documentos en los resultados. Para obtener más información, consulta MongoDB Vector Search Scoring.
Ejecutar una consulta mediante incrustación automatizada
No puede ejecutar consultas de MongoDB Vector Search en la Interfaz de Usuario de Atlas. Use el mongosh o un driver compatible para ejecutar querys.
Conéctate al clúster Atlas usando mongosh.
Para obtener más información, consulte Conectarse a un clúster a través de mongosh.
Ejecuta el método db.collection.aggregate() con la etapa $vectorSearch.
El método db.collection.aggregate() tiene la siguiente sintaxis:
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 ])
Ejemplo
Por ejemplo, para ejecutar una query en el campo fullplot de la colección movies para una búsqueda semántica de películas semánticamente similares a young heroes caught
in epic struggles between light and darkness, copie, pegue y ejecute la siguiente query.
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 ]
Define la consulta en el archivo.
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);
Ejemplo
Por ejemplo, en el archivo automated-embeddings-query.js, copia y pega el siguiente código para definir una query sobre el campo fullplot de la colección movies para una búsqueda semántica de películas semánticamente similares 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': 100, 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);
Reemplaza lo siguiente en la query.
| Cadena de conexión del clúster. |
| Nombre de la base de datos que contiene la colección. |
| Nombre de la colección que contiene el campo indexado. |
| Nombre del índice. |
| Nombre del campo indexado. |
| Cadena de texto para la cual se generarán incrustaciones y se usará en la búsqueda semántica. |
| Número de vecinos más próximos a considerar. |
| Número de documentos que deben devolverse en los resultados. |
Ejecuta la query.
node <FILE-NAME>.js
Aquí <FILE-NAME> es el nombre del archivo .js que usted creó.
Ejemplo
Por ejemplo, para ejecutar la query de ejemplo en el archivo automated-embeddings-query.js, ejecuta el siguiente 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}'
Define la consulta en el archivo.
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
Ejemplo
Por ejemplo, en el archivo automated-embeddings-query.py, copia y pega el siguiente código para definir una query sobre el campo fullplot de la colección movies para una búsqueda semántica de películas semánticamente similares 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': 100, 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
Reemplaza lo siguiente en la query.
| Cadena de conexión del clúster. |
| Nombre de la base de datos que contiene la colección. |
| Nombre de la colección que contiene el campo indexado. |
| Nombre del índice. |
| Nombre del campo indexado. |
| Cadena de texto para la cual se generarán incrustaciones y se usará en la búsqueda semántica. |
| Número de vecinos más próximos a considerar. |
| Número de documentos que deben devolverse en los resultados. |
Ejecuta la query.
python <FILE-NAME>.py
Aquí <FILE-NAME> es el nombre del archivo .py que usted creó.
Ejemplo
Por ejemplo, para ejecutar la query de ejemplo en el archivo automated-embeddings-query.py, ejecuta el siguiente 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}