Definición
Sintaxis
queryString tiene la siguiente sintaxis:
1 { 2 "$search": { 3 "index": <index name>, // optional, defaults to "default" 4 "queryString": { 5 "defaultPath": "<default-field-to-search>", 6 "query": "(<field-to-search>: (<search-values>) AND|OR (<search-values>)) AND|OR (<search-values>)" 7 } 8 } 9 }
opciones
queryString utiliza los siguientes términos para construir una query:
Campo | Tipo | Descripción | Necesidad | ||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| string | El campo indexado que se buscará de forma predeterminada. MongoDB Search solo busca el campo en | Sí | ||||||||||||||||||||
| string | Uno o más campos indexados y valores para buscar. Los campos y valores están delimitados por dos puntos. Por ejemplo, para buscar en el campo Puedes combinar los campos y valores usando lo siguiente:
Puede ejecutar queries comodín y expresiones regulares usando lo siguiente:
| Sí | ||||||||||||||||||||
| Objeto | La puntuación asignada a los resultados de búsqueda coincidentes. Puedes modificar la puntuación por defecto usando las siguientes opciones:
Cuando se consultan valores en arreglos, MongoDB Search asigna mayores puntuaciones si más valores en el arreglo coinciden con la query. Para obtener información sobre el uso de | no |
Comportamiento de la puntuación
De forma por defecto, la El operador queryString utiliza el algoritmo de similitud bm25 para puntuar los documentos dependiendo de su relevancia para la query.
Puede cambiar el algoritmo de similitud utilizado especificando uno diferente en la similarity.type propiedad para los string campos de la definición del índice de MongoDB Search. Para aprender a configurar un índice de MongoDB Search para el string tipo, consulte Cómo indexar campos de cadena.
Para obtener más información sobre los algoritmos de similitud admitidos, consulta Detalles de la puntuación.
Ejemplos
Los siguientes ejemplos utilizan la colección movies en la base de datos sample_mflix. Si tienes el conjunto de datos de muestra en tu clúster, puedes crear el índice de búsqueda de MongoDB llamado default con mapeos dinámicos y ejecutar las consultas de ejemplo en tu clúster.
Consultas de operadores booleanos
Ejemplos básicos
El siguiente ejemplo utiliza el operador queryString para query películas con el título Rocky y IV, 4 o Four en la ruta title en la colección movies. En la siguiente query, un campo se especifica en el defaultPath, pero no hay campos especificados en el query. La query incluye una etapa $project para excluir todos los campos excepto title.
1 db.movies.aggregate([ 2 { 3 $search: { 4 "queryString": { 5 "defaultPath": "title", 6 "query": "Rocky AND (IV OR 4 OR Four)" 7 } 8 } 9 }, 10 { 11 $project: { 12 "_id": 0, 13 "title": 1 14 } 15 } 16 ])
Para esta consulta, MongoDB Search realiza una búsqueda en defaultPath porque no hay campos en query. Devuelve los siguientes resultados:
{ "title" : "Rocky IV" }
El siguiente ejemplo utiliza el queryString operador para consultar películas con el título Rocky y ninguna de las formas de 2 los3 4números,, o 5 en la ruta title de la movies colección. En la siguiente consulta, se especifica un campo defaultPath en, pero no se especifica ningún campo query en. La consulta incluye una etapa para excluir todos los $project campos title excepto.
1 db.movies.aggregate([ 2 { 3 $search: { 4 "queryString": { 5 "defaultPath": "title", 6 "query": "Rocky AND NOT ((II OR 2 OR Two) OR (III OR 3 OR Three) OR (IV OR 4 OR Four) OR (V OR 5 OR Five))" 7 } 8 } 9 }, 10 { 11 $project: { 12 "_id": 0, 13 "title": 1 14 } 15 } 16 ])
[ { title: 'Rocky' }, { title: 'Rocky Marciano' }, { title: 'Rocky Balboa' }, { title: 'The Rocky Horror Picture Show' }, { title: 'The Adventures of Rocky & Bullwinkle' } ]
El siguiente ejemplo utiliza el operador queryString para consultar una combinación de campos de películas con el título The
Italian en el género Drama. El campo plot del defaultPath se buscará solo si no se encuentran resultados coincidentes en ninguno de los campos especificados en el campo query. El campo query contiene comillas dobles de escape como delimitadores de la frase a buscar.
La consulta incluye una etapa $project para:
Excluir todos los campos excepto
_id,title,plotygenresAgregue un campo llamado
score
1 db.movies.aggregate([ 2 { 3 $search: { 4 "queryString": { 5 "defaultPath": "plot", 6 "query": "title:\"The Italian\" AND genres:Drama" 7 } 8 } 9 }, 10 { 11 $project: { 12 "_id": 1, 13 "title": 1, 14 "plot": 1, 15 "genres": 1, 16 score: { $meta: "searchScore" } 17 } 18 } 19 ])
{ "_id" : ObjectId("573a1390f29313caabcd56df"), "plot" : "An immigrant leaves his sweetheart in Italy to find a better life across the sea in the grimy slums of New York. They are eventually reunited and marry. But life in New York is hard and ...", "genres" : [ "Drama" ], "title" : "The Italian", "score" : 4.975106716156006 } { "_id" : ObjectId("573a13b3f29313caabd3e36c"), "plot" : "Set in 2002, an abandoned 5-year-old boy living in a rundown orphanage in a small Russian village is adopted by an Italian family.", "genres" : [ "Drama" ], "title" : "The Italian", "score" : 4.975106716156006 } { "_id" : ObjectId("573a13c7f29313caabd756ee"), "plot" : "A romantic fairy tale about a 19-year old orphan girl who, as her sole inheritance, gets an antique key that unlocks both an old Italian villa and the secrets of her family history.", "genres" : [ "Comedy", "Drama", "Romance" ], "title" : "The Italian Key", "score" : 4.221206188201904 } { "_id" : ObjectId("573a13caf29313caabd7d1e4"), "plot" : "A chronicle of the 1969 bombing at a major national bank in Milan and its aftermath.", "genres" : [ "Drama" ], "title" : "Piazza Fontana: The Italian Conspiracy", "score" : 3.4441356658935547 }
El siguiente ejemplo utiliza el operador queryString para consultar una combinación de términos, captain o kirk y enterprise, en el campo plot. Incluye una etapa $limit para limitar el resultado a 3 resultados y una etapa $project para:
Excluir todos los campos excepto
title,plotyfullplotAgregue un campo llamado
score
1 db.movies.aggregate([ 2 { 3 $search: { 4 "queryString": { 5 "defaultPath": "fullplot", 6 "query": "plot:(captain OR kirk) AND enterprise" 7 } 8 } 9 }, 10 { 11 $limit: 3 12 }, 13 { 14 $project: { 15 "_id": 0, 16 "title": 1, 17 "plot": 1, 18 "fullplot": 1, 19 score: { $meta: "searchScore" } 20 } 21 } 22 ])
{ "plot" : "Captain Picard, with the help of supposedly dead Captain Kirk, must stop a madman willing to murder on a planetary scale in order to enter an energy ribbon.", "fullplot" : "In the late 23rd century, the gala maiden voyage of the third Starship Enterprise (NCC-1701-B) boasts such luminaries as Pavel Chekov, Montgomery Scott and the legendary Captain James T. Kirk as guests. But the maiden voyage turns to disaster as the unprepared ship is forced to rescue two transport ships from a mysterious energy ribbon. The Enterprise manages to save a handful of the ships' passengers and barely makes it out intact... but at the cost of Captain Kirk's life. Seventy-eight years later, Captain Jean-Luc Picard and the crew of the Enterprise-D find themselves at odds with the renegade scientist Tolian Soran... who is destroying entire star systems. Only one man can help Picard stop Soran's scheme... and he's been dead for seventy-eight years.", "title" : "Star Trek: Generations", "score" : 11.274821281433105 } { "plot" : "Captain Kirk and his crew must deal with Mr. Spock's long-lost half-brother who hijacks the Enterprise for an obsessive search for God at the center of the galaxy.", "fullplot" : "When the newly-christened starship Enterprise's shakedown cruise goes poorly, Captain Kirk and crew put her into Spacedock for repairs. But an urgent mission interrupts their Earth-bound shore leave. A renegade Vulcan named Sybok has taken three ambassadors hostage on Nimbus III, the Planet of Galactic Peace. This event also attracts the attention of a Klingon captain who wants to make a name for himself and sets out to pursue the Enterprise. Sybok's ragtag army captures the Enterprise and takes her on a journey to the center of the galaxy in search of the Supreme Being.", "title" : "Star Trek V: The Final Frontier", "score" : 9.889547348022461 } { "plot" : "When an alien spacecraft of enormous power is spotted approaching Earth, Admiral Kirk resumes command of the Starship Enterprise in order to intercept, examine and hopefully stop the intruder.", "fullplot" : "A massive alien spacecraft of enormous power is approaching Earth, destroying everything in its path. The only star ship in range is the USS Enterprise still in dry-dock after a major overhaul. As Captain Willard Decker readies his ship and his crew to face this menace, Admiral James T. Kirk arrives with orders to take command of the Enterprise and intercept the alien intruder. But it has been three years since Kirk last commanded the Enterprise on its historic five year mission... is he up to the task of saving the Earth?", "title" : "Star Trek: The Motion Picture", "score" : 8.322310447692871 }
Los documentos en los resultados coinciden porque:
En el primer documento, el campo
plot, que es el campo de búsqueda segúnquery, contiene tantocaptaincomokirk, aunque solo se requiere uno para cumplir con los criterios de una coincidencia. Para el términoenterprise, MongoDB Search busca en el campofullplot, que es eldefaultPath, porque el campoplotno contieneenterprisey encuentraenterpriseen el campofullplot.En el segundo documento, el campo
plotcontiene los tres términos de búsqueda.En el tercer documento, el campo
plotcontienekirkyenterprise.
Ejemplos avanzados
Los ejemplos en esta sección utilizan el operador queryString para query tramas de películas que contengan los términos captain, kirk y chess. Este ejemplo muestra cómo diferentes agrupaciones de los mismos términos de búsqueda mediante paréntesis pueden dar lugar a que se incluyan diferentes documentos en los resultados de la búsqueda.
Las consultas también incluyen una $project etapa para:
Excluir todos los campos excepto
title,plotyfullpathAgregue un campo llamado
score
La siguiente query busca chess y captain o kirk en el campo plot.
1 db.movies.aggregate([ 2 { 3 $search: { 4 "queryString": { 5 "defaultPath": "fullplot", 6 "query": "plot:(captain OR kirk) AND chess" 7 } 8 } 9 }, 10 { 11 $project: { 12 "_id": 0, 13 "title": 1, 14 "plot": 1, 15 "fullplot": 1, 16 score: { $meta: "searchScore" } 17 } 18 } 19 ])
{ "fullplot" : "When the crew of the Enterprise is called back home, they find an unstoppable force of terror from within their own organization has detonated the fleet and everything it stands for, leaving our world in a state of crisis. With a personal score to settle, Captain Kirk leads a manhunt to a war-zone world to capture a one-man weapon of mass destruction. As our heroes are propelled into an epic chess game of life and death, love will be challenged, friendships will be torn apart, and sacrifices must be made for the only family Kirk has left: his crew.", "plot" : "After the crew of the Enterprise find an unstoppable force of terror from within their own organization, Captain Kirk leads a manhunt to a war-zone world to capture a one-man weapon of mass destruction.", "title" : "Star Trek Into Darkness", "score" : 7.968792915344238 }
El documento en los resultados coincide porque el plot contiene los términos captain y kirk, aunque solo se necesita uno para cumplir con los criterios para una coincidencia, y el término chess, aunque no está en el plot, aparece en el fullplot, que es el defaultPath.
La siguiente consulta busca captain o kirk y chess en el campo plot.
1 db.movies.aggregate([ 2 { 3 $search: { 4 "queryString": { 5 "defaultPath": "fullplot", 6 "query": "plot:captain OR (kirk AND chess)" 7 } 8 } 9 }, 10 { 11 $limit: 5 12 }, 13 { 14 $project: { 15 "_id": 0, 16 "title": 1, 17 "plot": 1, 18 "fullplot": 1, 19 score: { $meta: "searchScore" } 20 } 21 } 22 ])
{ "fullplot" : "When the crew of the Enterprise is called back home, they find an unstoppable force of terror from within their own organization has detonated the fleet and everything it stands for, leaving our world in a state of crisis. With a personal score to settle, Captain Kirk leads a manhunt to a war-zone world to capture a one-man weapon of mass destruction. As our heroes are propelled into an epic chess game of life and death, love will be challenged, friendships will be torn apart, and sacrifices must be made for the only family Kirk has left: his crew.", "plot" : "After the crew of the Enterprise find an unstoppable force of terror from within their own organization, Captain Kirk leads a manhunt to a war-zone world to capture a one-man weapon of mass destruction.", "title" : "Star Trek Into Darkness", "score" : 9.227973937988281 } { "plot" : "Captain Picard, with the help of supposedly dead Captain Kirk, must stop a madman willing to murder on a planetary scale in order to enter an energy ribbon.", "title" : "Star Trek: Generations", "fullplot" : "In the late 23rd century, the gala maiden voyage of the third Starship Enterprise (NCC-1701-B) boasts such luminaries as Pavel Chekov, Montgomery Scott and the legendary Captain James T. Kirk as guests. But the maiden voyage turns to disaster as the unprepared ship is forced to rescue two transport ships from a mysterious energy ribbon. The Enterprise manages to save a handful of the ships' passengers and barely makes it out intact... but at the cost of Captain Kirk's life. Seventy-eight years later, Captain Jean-Luc Picard and the crew of the Enterprise-D find themselves at odds with the renegade scientist Tolian Soran... who is destroying entire star systems. Only one man can help Picard stop Soran's scheme... and he's been dead for seventy-eight years.", "score" : 3.3556222915649414 } { "plot" : "An army cadet accompanies an irascible, blind captain on a week-long trip from Turin to Naples. The captain, Fausto, who wants no pity, brooks no disagreement, and charges into every ...", "title" : "Scent of a Woman", "fullplot" : "An army cadet accompanies an irascible, blind captain on a week-long trip from Turin to Naples. The captain, Fausto, who wants no pity, brooks no disagreement, and charges into every situation, nicknames the youth Ciccio (\"Babyfat\"), and spends the next few days ordering him about and generally behaving badly in public. In Rome, Fausto summons a priest to ask for his blessing; in Naples, where Fausto joins a blind lieutenant for drinking and revelry, the two soldiers talk quietly and seriously about \"going through with it.\" Also in Naples is Sara, in love with Fausto, but treated cruelly by him. What do the blind soldiers plan? Can Sara soften Fausto's hardened heart?", "score" : 3.2553727626800537 } { "plot" : "A seductive woman falls in love with a mysterious ship's captain.", "title" : "Pandora and the Flying Dutchman", "fullplot" : "Albert Lewin's interpretation of the legend of the Flying Dutchman. In a little Spanish seaport named Esperanza, during the 30s, appears Hendrick van der Zee, the mysterious captain of a yacht (he is the only one aboard). Pandora is a beautiful woman (who men kill and die for). She's never really fallen in love with any man, but she feels very attracted to Hendrick... We are soon taught that Hendrick is the Flying Dutchman, this sailor of the 17th century that has been cursed by God to wander over the seas until the Doomsday... unless a woman is ready to die for him...", "score" : 3.2536067962646484 } { "plot" : "The adventures of pirate Captain Red and his first mate Frog.", "title" : "Pirates", "fullplot" : "Captain Red runs a hardy pirate ship with the able assistance of Frog, a dashing young French sailor. One day Capt. Red is captured and taken aboard a Spanish galleon, but thanks to his inventiveness, he raises the crew to mutiny, takes over the ship, and kidnaps the niece of the governor of Maracaibo. The question is, can he keep this pace up?", "score" : 3.2536067962646484 }
Los documentos en los resultados coinciden porque el campo plot contiene el término captain. El primer documento obtiene una puntuación más alta porque MongoDB Search también encuentra los términos kirk y chess en el campo fullplot, aunque no se requiere la presencia de los términos para cumplir con los criterios de coincidencia.
Consultas de rango
El siguiente ejemplo utiliza el operador queryString para query los títulos de películas, cubriendo un rango de valores textuales desde los caracteres count hasta cualquier carácter (definido usando el carácter comodín *), en orden alfabético ascendente.
1 db.movies.aggregate([ 2 { 3 "$search": { 4 "queryString": { 5 "defaultPath": "plot", 6 "query": "title:[count TO *]" 7 } 8 } 9 }, 10 { 11 "$limit": 10 12 }, 13 { 14 "$project": { 15 "_id": 0, 16 "title": 1 17 } 18 } 19 ])
1 [ 2 { title: 'Blacksmith Scene' }, 3 { title: 'The Great Train Robbery' }, 4 { title: 'The Land Beyond the Sunset' }, 5 { title: 'A Corner in Wheat' }, 6 { title: 'Winsor McCay, the Famous Cartoonist of the N.Y. Herald and His Moving Comics' }, 7 { title: 'Traffic in Souls' }, 8 { title: 'Gertie the Dinosaur' }, 9 { title: 'In the Land of the Head Hunters' }, 10 { title: 'The Perils of Pauline' }, 11 { title: 'The Birth of a Nation' } 12 ]
Los resultados de MongoDB Search incluyen películas con los títulos Blacksmith Scene y A Corner in Wheat, aunque el rango en la query comienza desde el carácter count. Cuando indexas con el analizador por defecto, lucene.standard, MongoDB Search crea tokens separados para los términos en el campo title y coincide el query term con los tokens individuales. Específicamente, MongoDB Search crea los siguientes tokens, al menos uno de los cuales (indicado por √) coincide con los criterios de la query:
Título | Tokens de analizador estándar |
|---|---|
Escena del herrero |
|
A Corner in Wheat (Una esquina en el trigo) |
|
Si indexas utilizando el analizador lucene.keyword, MongoDB Search crearía un único token para toda la cadena en el campo title, dando lugar a resultados similares a los siguientes para la misma query:
[ { title: 'è Nous la Libertè' }, { title: 'tom thumb' }, { title: 'è nos amours' }, { title: 'èke och hans vèrld' }, { title: 'èdipussi' }, { title: 's/y Glèdjen' }, { title: 'èAy, Carmela!' }, { title: 'èlisa' }, { title: 'èxtasis' }, { title: 'eXistenZ' } ]
El siguiente ejemplo utiliza el operador queryString para query los géneros de películas de drama y los títulos para un rango de valores textuales entre man y men, incluidos ambos, en orden alfabético ascendente.
1 db.movies.aggregate([ 2 { 3 "$search": { 4 "queryString": { 5 "defaultPath": "plot", 6 "query": "title:[man TO men] AND genres: Drama" 7 } 8 } 9 }, 10 { 11 "$limit": 10 12 }, 13 { 14 "$project": { 15 "_id": 0, 16 "title": 1, 17 "genres": 1 18 } 19 } 20 ])
1 [ 2 { genres: [ 'Drama' ], title: 'The Wedding March' }, 3 { genres: [ 'Drama' ], title: 'Maria Chapdelaine' }, 4 { genres: [ 'Drama' ], title: 'Of Mice and Men' }, 5 { genres: [ 'Drama' ], title: 'All the King's Men' }, 6 { genres: [ 'Drama' ], title: 'Wuya yu maque' }, 7 { genres: [ 'Drama' ], title: 'The Men' }, 8 { genres: [ 'Drama' ], title: 'The Member of the Wedding' }, 9 { genres: [ 'Drama' ], title: 'The Great Man' }, 10 { genres: [ 'Drama' ], title: 'A Matter of Dignity' }, 11 { genres: [ 'Drama' ], title: 'The Last Angry Man' } 12 ]
Los documentos en los resultados coinciden porque el campo genres contiene el término drama y el campo de película title contiene términos entre Man y Men en orden alfabético (Man, Maque, March, Maria, Matter, Member y Men en los resultados).
Consultas con comodines
Los siguientes ejemplos utilizan el operador queryString para query títulos de películas usando expresiones regulares, patrones de búsqueda y comodines difusos. Las consultas incluyen una etapa $project para excluir todos los campos, excepto title.
La siguiente query utiliza la función de búsqueda difusa (~) para buscar títulos de películas en el campo title que contengan términos similares a catch, con una variación de hasta dos caracteres.
1 db.movies.aggregate([ 2 { 3 "$search": { 4 "queryString": { 5 "defaultPath": "title", 6 "query": "catch~2" 7 } 8 } 9 }, 10 { 11 "$limit": 10 12 }, 13 { 14 "$project": { 15 "_id": 0, 16 "title": 1 17 } 18 } 19 ])
1 [ 2 { title: 'Catch-22' }, 3 { title: 'Catch That Girl' }, 4 { title: 'Catch That Kid' }, 5 { title: 'Catch a Fire' }, 6 { title: 'Catch Me Daddy' }, 7 { title: 'Death Watch' }, 8 { title: 'Patch Adams' }, 9 { title: "Batch '81" }, 10 { title: 'Briar Patch' }, 11 { title: 'Night Watch' } 12 ]
La siguiente query utiliza una expresión de caracteres comodín para buscar en el campo title títulos de películas que contengan los caracteres cou*t?*, donde * indica cualquier número adicional de caracteres y ? indica cualquier carácter individual.
1 db.movies.aggregate([ 2 { 3 "$search": { 4 "queryString": { 5 "defaultPath": "title", 6 "query": "cou*t?*" 7 } 8 } 9 }, 10 { 11 "$limit": 5 12 }, 13 { 14 "$project": { 15 "_id": 0, 16 "title": 1 17 } 18 } 19 ])
1 [ 2 { title: 'A Day in the Country' }, 3 { title: 'Diary of a Country Priest' }, 4 { title: 'Cry, the Beloved Country' }, 5 { title: 'The Country Girl' }, 6 { title: 'Raintree County' } 7 ]
Los documentos en los resultados coinciden porque el campo title contiene el término Country o County, que coincide con los criterios de consulta para caracteres que comienzan con cou seguido de cualquier número de caracteres (n en los resultados) y luego t seguido de al menos uno o muchos caracteres (r como en country o y como en county en los resultados).
La siguiente query utiliza una expresión regular para buscar en el campo title títulos de películas que contengan caracteres que comiencen con cualquier carácter, seguido de los caracteres tal y ya sea y o ian después de tal.
1 db.movies.aggregate([ 2 { 3 "$search": { 4 "queryString": { 5 "defaultPath": "title", 6 "query": "/.tal(y|ian)/" 7 } 8 } 9 }, 10 { 11 "$limit": 5 12 }, 13 { 14 "$project": { 15 "_id": 0, 16 "title": 1 17 } 18 } 19 ])
1 [ 2 { title: 'The Italian' }, 3 { title: 'Journey to Italy' }, 4 { title: 'Divorce Italian Style' }, 5 { title: 'Marriage Italian Style' }, 6 { title: 'Jealousy, Italian Style' } 7 ]
Los documentos de los resultados coinciden porque el campo title contiene el término Italy o Italian, lo que cumple con los criterios de query para cualquier carácter (I en los resultados) seguido de tal con y (como en Italy en los resultados) o ian (como en Italian en los resultados).
Metadatos query
La siguiente query busca el campo title en la colección movies para Marvel, Avengers, Iron Man o Captain
America.