Definición
El operador text realiza una búsqueda de texto completo utilizando el Analizador que especifique en la configuración del índice. Si omite un analizador, el text operador utiliza el analizador estándar predeterminado.
Sintaxis
text tiene la siguiente sintaxis:
{ $search: { "index": <index name>, // optional, defaults to "default" "text": { "query": "<search-string>", "path": "<field-to-search>", "fuzzy": <options>, "matchCriteria": "any" | "all" "score": <options>, "synonyms": "<synonyms-mapping-name>" } } }
opciones
text utiliza los siguientes términos para construir una consulta:
Campo | Tipo | Descripción | Necesidad |
|---|---|---|---|
| cadena o matriz de cadenas | La cadena o cadenas que se buscarán. Si una cadena contiene varios términos, MongoDB Search también busca una coincidencia para cada término por separado. | Requerido |
| cadena o matriz de cadenas | El campo o los campos indexados a buscar. También se puede especificar una ruta comodín para realizar una búsqueda. | Requerido |
| Documento | Habilitar la búsqueda difusa. Encuentra cadenas similares al término o términos de búsqueda. No se puede usar | Opcional |
| entero | Número máximo de ediciones de un solo carácter necesarias para encontrar el término de búsqueda especificado. El valor puede ser | Opcional |
| entero | Número de caracteres al principio de cada término del resultado que deben coincidir exactamente. El valor predeterminado es | Opcional |
| entero | Número máximo de variaciones para generar y buscar. Este límite se aplica por token. El valor predeterminado es | Opcional |
| string | Criterios para encontrar coincidencias con los términos de la consulta. Si se omite, el valor predeterminado es
| Opcional, Recomendado |
| Documento | Puntuación asignada a los resultados de búsqueda coincidentes. Utilice una de las siguientes opciones para modificar la puntuación:
Al consultar valores de una matriz, MongoDB Search asigna puntuaciones más altas si más valores en la matriz coinciden con la consulta. | Opcional |
| string | Es necesario para ejecutar queries utilizando synonyms. Nombre de la definición de asignación de sinónimos en la definición del índice. El valor no puede ser una cadena vacía. No se puede usar IMPORTANTE: Para usar la opción Utilice siempre El tiempo que MongoDB Search tarda en ejecutar consultas que utilizan asignaciones de sinónimos depende del número y el tamaño de los documentos de la colección de origen de sinónimos. Una consulta que utiliza una asignación de sinónimos basada en muy pocos documentos de sinónimos podría ser más rápida que una que utiliza una asignación de sinónimos basada en muchos documentos de sinónimos. | Opcional |
Comportamiento de puntuación
De forma predeterminada, el operador de texto utiliza el bm25 algoritmo de similitud para puntuar los documentos según su relevancia para la consulta.
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.
Comportamiento
Para las text queries que utilizan synonyms sin matchCriteria, MongoDB Search sólo coincide con los documentos que contienen una coincidencia exacta de los términos de la query (con o sin los sinónimos expandidos).
Este comportamiento puede cambiar en el futuro y tus resultados de consulta también pueden cambiar. Para evitar interrupciones en el servicio, siempre usa matchCriteria cuando utilices synonyms. O utiliza sinónimos con el operador frase.
Por ejemplo, supongamos que existen asignaciones de sinónimos equivalentes para nyc y new
york city. Una búsqueda de i like nyc devuelve lo siguiente:
Especificación del operador | Comportamiento predeterminado | "matchCriteria": "any" | "matchCriteria": "all" |
|---|---|---|---|
| Coincidencias | Coincidencias | Coincidencias |
| Coincidencias | Coincide con | Coincide con |
El tiempo que MongoDB Search tarda en ejecutar consultas que utilizan asignaciones de sinónimos depende del número y el tamaño de los documentos de la colección de origen de sinónimos. Una consulta que utiliza una asignación de sinónimos basada en muy pocos documentos de sinónimos podría ser más rápida que una que utiliza una asignación de sinónimos basada en muchos documentos de sinónimos.
Ejemplos
Los ejemplos de esta página utilizan la colección movies en la base de datos sample_mflix. Después de cargar el conjunto de datos de muestra en tu clúster, crea el índice de MongoDB Search con asignaciones dinámicas y ejecuta las queries de ejemplo en tu clúster. También debes definir una colección de mapeo synonyms en el índice, como se muestra en los Ejemplos de definición de índice, para probar los ejemplos de sinónimos a continuación.
Ejemplo básico
La siguiente consulta de búsqueda de MongoDB utiliza el text operador para buscar el title término en el campo movies de la surfer colección. Incluye una etapa $project para:
Excluir todos los campos excepto
titleAgregue un campo llamado
score
db.movies.aggregate([ { $search: { "text": { "path": "title", "query": "surfer" } } }, { $project: { "_id": 0, "title": 1, score: { $meta: "searchScore" } } } ])
{ "title" : "Soul Surfer", "score" : 4.518949508666992 } { "title" : "Little Surfer Girl", "score" : 3.8856077194213867 } { "title" : "Fantastic 4: Rise of the Silver Surfer", "score" : 2.489800453186035 }
Ejemplo de metadatos
La siguiente consulta busca title el término en summer el campo. Utiliza la $searchMeta etapa para recuperar el número de películas en los siguientes grupos (años) que coinciden con los criterios de búsqueda:
1970, límite inferior inclusivo para este depósito
1980, límite superior exclusivo para el cubo 1970 y límite inferior inclusivo para este cubo
1990, límite superior exclusivo para el cubo 1980 y límite inferior inclusivo para este cubo
2000, límite superior exclusivo para el cubo 1990 y límite inferior inclusivo para este cubo
2010, límite superior exclusivo para el cubo 2000 y límite inferior inclusivo para este cubo
2015, límite superior exclusivo para el depósito 2010
db.movies.aggregate([ { "$searchMeta": { "facet": { "operator": { "text": { "path": "title", "query": "summer" } }, "facets": { "yearFacet": { "type": "number", "path": "year", "boundaries": [1970, 1980, 1990, 2000, 2010, 2020 ] } } } } } ])
[ { count: { lowerBound: Long('65') }, facet: { yearFacet: { buckets: [ { _id: 1970, count: Long('6') }, { _id: 1980, count: Long('7') }, { _id: 1990, count: Long('11') }, { _id: 2000, count: Long('19') }, { _id: 2010, count: Long('14') } ] } } } ]
Ejemplos difusos
Las siguientes consultas utilizan el operador text para buscar en el campo title de la colección movies términos que se encuentren dentro de una variación de cada término de la frase query naw
yark. MongoDB Search devuelve resultados diferentes según se utilicen las opciones predeterminadas fuzzy o se definan los campos maxExpansions, prefixLength u maxEdits.
Haga clic en las siguientes pestañas para ver consultas de ejemplo que utilizan opciones predeterminadas y especificadas:
La siguiente consulta busca la frase naw yark en el campo title. Utiliza las opciones predeterminadas fuzzy, donde:
maxEditspermite hasta dos variaciones de caracteres para cada término en la frase dada, lo que permite que la query coincida con un documento.maxExpansionsconsidera hasta cincuenta términos similares para cada término ennaw yarkpara encontrar coincidencias.prefixLengthestá deshabilitado.
La consulta también incluye una etapa $limit para limitar la salida a 10 resultados y una etapa $project para:
Excluir todos los campos excepto
titleAgregue un campo llamado
score
db.movies.aggregate([ { $search: { "text": { "path": "title", "query": "naw yark", "fuzzy": {} } } }, { $limit: 10 }, { $project: { "_id": 0, "title": 1, score: { $meta: "searchScore" } } } ])
{ "title" : "New York, New York", "score" : 3.6040148735046387 } { "title" : "New York", "score" : 3.323730945587158 } { "title" : "New York Stories", "score" : 2.8579015731811523 } { "title" : "New York Minute", "score" : 2.8579015731811523 } { "title" : "Synecdoche, New York", "score" : 2.8579015731811523 } { "title" : "New York Doll", "score" : 2.8579015731811523 } { "title" : "Little New York", "score" : 2.8579015731811523 } { "title" : "Escape from New York", "score" : 2.506596088409424 } { "title" : "Naked in New York", "score" : 2.506596088409424 } { "title" : "Autumn in New York", "score" : 2.506596088409424 }
La siguiente consulta busca en el campo title términos que se encuentren a menos de un carácter de cada término de la cadena naw yark. Utiliza:
El campo
maxEditsindica que solo se permite una variación de carácter por cada término para que coincida la consulta con un documento.El campo
maxExpansionsindica que se deben considerar hasta cien términos similares paranawy cien términos similares ayarkal hacer coincidir la consulta con un documento.
La consulta también incluye una etapa $limit para limitar la salida a 10 resultados y una etapa $project para:
Excluir todos los campos excepto
titleAgregue un campo llamado
score
db.movies.aggregate([ { $search: { "text": { "path": "title", "query": "naw yark", "fuzzy": { "maxEdits": 1, "maxExpansions": 100, } } } }, { $limit: 10 }, { $project: { "_id": 0, "title": 1, score: { $meta: "searchScore" } } } ])
{ "title" : "New York, New York", "score" : 4.38106107711792 } { "title" : "New York", "score" : 4.040346145629883 } { "title" : "New York Stories", "score" : 3.4740817546844482 } { "title" : "New York Minute", "score" : 3.4740817546844482 } { "title" : "Synecdoche, New York", "score" : 3.4740817546844482 } { "title" : "New York Doll", "score" : 3.4740817546844482 } { "title" : "Little New York", "score" : 3.4740817546844482 } { "title" : "Escape from New York", "score" : 3.047032356262207 } { "title" : "Naked in New York", "score" : 3.047032356262207 } { "title" : "Autumn in New York", "score" : 3.047032356262207 }
La siguiente consulta busca en el campo title términos que se encuentren a menos de un carácter de cada término de la cadena naw yark. Utiliza:
El campo
maxEditspara indicar que solo se permite una variación de carácter para que coincida con la query de un documento.El campo
prefixLengthindica que los dos primeros caracteres de cada término de la cadenanaw yarkno se pueden cambiar para que coincida la consulta con un documento.
La consulta también incluye una etapa $limit para limitar la salida a 8 resultados y una etapa $project para:
Excluir todos los campos excepto
_idytitleAgregue un campo llamado
score
db.movies.aggregate([ { $search: { "text": { "path": "title", "query": "naw yark", "fuzzy": { "maxEdits": 1, "prefixLength": 2, } } } }, { $limit: 8 }, { $project: { "_id": 1, "title": 1, score: { $meta: "searchScore" } } } ])
{ "_id" : ObjectId("573a1396f29313caabce5646", "title" : "The Longest Yard", "score" : 2.914206027984619 } { "_id" : ObjectId("573a13aff29313caabd31ed8", "title" : "The Longest Yard", "score" : 2.914206027984619 } { "_id" : ObjectId("573a13b7f29313caabd4ad8b", "title" : "Stomp the Yard", "score" : 2.914206027984619 } { "_id" : ObjectId("573a13eaf29313caabdcf410", "title" : "Naz & Maalik", "score" : 2.5460386276245117 } { "_id" : ObjectId("573a1393f29313caabcddbed", "title" : "La nao capitana", "score" : 2.1892051696777344 } { "_id" : ObjectId("573a1399f29313caabcee781", "title" : "Kabhi Haan Kabhi Naa", "score" : 1.9200985431671143 } { "_id" : ObjectId("573a13a2f29313caabd0b815", "title" : "Kaho Naa... Pyaar Hai", "score" : 1.9200985431671143 } { "_id" : ObjectId("573a13a7f29313caabd1b5c0", "title" : "Oysters at Nam Kee's", "score" : 1.9200985431671143 }
Match all
La siguiente consulta utiliza el operador text para buscar en el campo plot de la colección movies todos los términos de la cadena de consulta automobile race.
db.movies.aggregate([ { "$search": { "text": { "path": "plot", "query": "automobile race", "matchCriteria": "all" } } }, { "$limit": 20 }, { "$project": { "_id": 0, "plot": 1, "title": 1, "score": { "$meta": "searchScore" } } } ])
[ { plot: 'A young driver, Speed Racer, aspires to be champion of the racing world with the help of his family and his high-tech Mach 5 automobile.', title: 'Speed Racer', score: 6.122188568115234 }, { plot: 'A gorgeous young automobile fanatic--and front to the hottest unsigned band on the West coast--finds herself caught up in illegal drag-racing competitions organized by exotic car fanatics.', title: 'Redline', score: 5.497724533081055 }, { plot: 'When a popular daredevil proposes an automobile race across three continents, his arch rival vows to beat him, while an ambitious female reporter has her own plans for victory.', title: 'The Great Race', score: 5.282209396362305 } ]
MongoDB Search devuelve documentos que contienen los términos automobile y race en cualquier lugar del campo plot.
Sinónimos Ejemplos
Los siguientes ejemplos utilizan el text operador para buscar plot en el campo del espacio sample_mflix.movies de nombres. MongoDB Search devuelve resultados según el tipo de synonymous_termsasignación en la sample_mflix.movies colección de origen de sinónimos,, especificado en la definición de asignación de sinónimos del índice de la colección.
any Coincidir con mediante equivalent el mapeo
La siguiente consulta busca la frase attire en el campo plot. Utiliza la asignación de sinónimos mySynonyms en el índice de la colección para buscar también palabras configuradas como sinónimos de la palabra dress.
db.movies.aggregate([ { "$search": { "text": { "path": "plot", "query": "attire", "synonyms": "my_synonyms", "matchCriteria": "any" } } }, { "$limit": 5 }, { "$project": { "_id": 0, "plot": 1, "title": 1, "score": { "$meta": "searchScore" } } } ])
[ { plot: 'The Sanguiwon are responsible for the attire worn by royalty. Dol-Seok (Han Suk-Kyu) is the best master artisan in charge of royal attire. He views set rules as paramount to his job. ...', title: 'The Royal Tailor', score: 15.825017929077148 }, { plot: "During Christmas' holidays, the children of a village split in two gang to play a snowball war. But that half-tone war scattered some bitterness and make more difficult the mutual attirance...", title: 'La guerre des tuques', score: 11.863945007324219 }, { plot: 'The Dress is a tale filled with sex, violence, comedy and drama as it follows the life of a dress. Conceived under a cloud of frustration and despair, the dress serves as the hub in a great...', title: 'The Dress', score: 5.061710834503174 }, { plot: "Boardroom and dressing-room intrigues spill on to the field at the Australian Rules football club.", title: 'The Club', score: 3.991994857788086 }, { plot: 'Deserting soldier dresses as a woman to escape detection; liking the female role he goes to a dance with another soldier and is exposed.', title: 'The Triple Echo', score: 3.5169785022735596 } ]
MongoDB Search devuelve los documentos que contienen los términos attire, apparel y dress porque configuramos todos estos términos como sinónimos de equivalent en la colección de origen de sinónimos synonymous_terms, lo que significa que todos estos términos son sinónimos entre sí. Por lo tanto, MongoDB Search devuelve documentos similares para las búsquedas de dress y attire.
any Coincidir con mediante explicit el mapeo
La siguiente query busca en el campo plot la frase boat
race. Utiliza el mapeo de sinónimos llamado my_synonyms en el índice de la colección para también buscar palabras que estén configuradas como sinónimos de la palabra boat y race.
db.movies.aggregate([ { "$search": { "text": { "path": "plot", "query": "boat race", "synonyms": "my_synonyms", "matchCriteria": "any" } } }, { "$limit": 10 }, { "$project": { "_id": 0, "plot": 1, "title": 1, "score": { "$meta": "searchScore" } } } ])
[ { plot: 'A man is picked up by a fishing boat, bullet-riddled and suffering from amnesia, before racing to elude assassins and regain his memory.', title: 'The Bourne Identity', score: 15.405073165893555 }, { plot: 'A few friends builds a sailing boat together. They plan trips and during the completion of the boat marriages crumble, new relations blossom and the boat burns. They rebuild it and the ...', title: 's/y Glèdjen', score: 13.40434741973877 }, { plot: 'Famous motor-racing champion Joe Greer returns to his hometown to compete in a local race. He discovers his younger brother has aspirations to become a racing champion and during the race ...', title: 'The Crowd Roars', score: 10.466073036193848 }, { plot: 'The claustrophobic world of a WWII German U-boat; boredom, filth, and sheer terror.', title: 'Das Boot', score: 10.304922103881836 }, { plot: 'Several survivors of a torpedoed ship find themselves in the same boat with one of the men who sunk it.', title: 'Lifeboat', score: 9.776729583740234 }, { plot: 'A fishing-boat crew takes on a dangerous commission to smuggle a group of illegal immigrants from China to Korea.', title: 'Haemoo', score: 9.532430648803711 }, { plot: 'A land baron tries to reconnect with his two daughters after his wife is seriously injured in a boating accident.', title: 'The Descendants', score: 9.300044059753418 }, { plot: 'A weekend boating party turns into a nightmare for a group of young Londoners when they stumble upon a terrifying secret hidden in the reeds.', title: 'The Reeds', score: 9.078716278076172 }, { plot: 'Documentary telling the true story of the sinking of the liner Laconia by a German U-boat in 1942 through the eyes of six survivors.', title: 'The Sinking of the Laconia', score: 9.078716278076172 }, { plot: 'Sabotage efforts damage an international air race.', title: 'Those Magnificent Men in Their Flying Machines or How I Flew from London to Paris in 25 hours 11 minutes', score: 8.983794212341309 } ]
MongoDB Search devuelve documentos que contienen el término boat, vessel,, sail, race, rally o contest porque configuramos boat como sinónimo de explicit, vessel y sail, y configuramos race como sinónimo de explicit, rally y contest. MongoDB Search no devuelve ningún resultado para una consulta sobre vessel y sail, o rally y contest, porque no configuramos estas palabras para que las considere sinónimos.
Emparejar all usando sinónimos
La siguiente consulta utiliza el operador text para buscar en el campo plot de la colección movies todos los términos de la cadena de consulta automobile race.
La synonymous_termsbúsqueda sample_mflix.movies de MongoDB devuelve resultados basados en el tipo de asignación en la colección de origen de sinónimos,, especificada en la definición de asignación de sinónimos del índice para la colección.
db.movies.aggregate([ { "$search": { "text": { "path": "plot", "query": "automobile race", "matchCriteria": "all", "synonyms": "my_synonyms" } } }, { "$limit": 20 }, { "$project": { "_id": 0, "plot": 1, "title": 1, "score": { "$meta": "searchScore" } } } ])
[ { plot: 'A young driver, Speed Racer, aspires to be champion of the racing world with the help of his family and his high-tech Mach 5 automobile.', title: 'Speed Racer', score: 17.354578018188477 }, { plot: 'A gorgeous young automobile fanatic--and front to the hottest unsigned band on the West coast--finds herself caught up in illegal drag-racing competitions organized by exotic car fanatics.', title: 'Redline', score: 16.085742950439453 }, { plot: 'When a popular daredevil proposes an automobile race across three continents, his arch rival vows to beat him, while an ambitious female reporter has her own plans for victory.', title: 'The Great Race', score: 15.087226867675781 }, { plot: 'A race car driver becomes a champion with a Volkswagen Beetle with a mind of its own.', title: 'The Love Bug', score: 5.1777167320251465 }, { plot: 'A wide variety of eccentric competitors participate in a wild and illegal cross-country car race.', title: 'The Cannonball Run', score: 5.041530609130859 }, { plot: 'The original characters from the first Cannonball movie race across the country once more in various cars and trucks.', title: 'Cannonball Run II', score: 4.67281436920166 }, { plot: 'After a tied 1st place in a local stunt race, two drivers start a contest to decide who of them will own the prize, a dune buggy. But when a mobster destroys the car, they are determined to get it back.', title: "Watch Out, We're Mad", score: 4.500225067138672 }, { plot: 'Four teenagers are killed in a car accident. Two of the teenagers refuse to go with "The Grim Reaper" and a race between life and death ensues!', title: 'Soultaker', score: 4.455573081970215 }, { plot: "The driver races to locate a kidnapped victim locked in the trunk of an abandoned car somewhere on the water's edge. Linked to her only by cell phone, the driver narrows in on her location in a desperate race against time and tide.", title: 'Hostage', score: 4.429774284362793 }, { plot: 'Race car driver Lucky Jackson goes to Las Vegas to earn money to pay for a new engine for his motor car. Working as a waiter, he still finds the time to court young Rusty Martin.', title: 'Viva Las Vegas', score: 4.379656791687012 }, { plot: 'Barry Pepper portrays legendary race car drive Dale Earnhardt, who died in 2001 during the last lap of the Daytona 500.', title: '3: The Dale Earnhardt Story', score: 4.3543548583984375 }, { plot: 'Bounty hunters from the future transport a doomed race-car driver to 2009 New York, where his mind will be replaced with that of a dead billionaire.', title: 'Freejack', score: 4.257633209228516 }, { plot: 'A mechanic takes his family to a car race and a series of events occur which brings problems, betrayals, violence and the unexpected death of an elderly person.', title: 'National Mechanics', score: 4.257633209228516 }, { plot: 'A hot-shot race-car named Lightning McQueen gets waylaid in Radiator Springs, where he finds the true meaning of friendship and family.', title: 'Cars', score: 4.257633209228516 }, { plot: 'Star race car Lightning McQueen and his pal Mater head overseas to compete in the World Grand Prix race. But the road to the championship becomes rocky as Mater gets caught up in an intriguing adventure of his own: international espionage.', title: 'Cars 2', score: 4.231379985809326 }, { plot: "An illegal race that takes place over the United States and nothing will stop this bunch of racers except for the occasional cop or a damsel in distress. Jackie Chan's car is not in this ...", title: 'Cannonball Fever', score: 4.1651153564453125 }, { plot: 'Roy is mad about cars, and runs Stallion Parts while attending to his yellow Mustang, far away from his daughter, which comes on holiday, while he is to attend a race. Soon he is challenged in a illegal race through the length of Norway.', title: 'Bèrning', score: 4.050384521484375 }, { plot: "It's time for the annual London to Brighton antique car rally, and Alan McKim and Ambrose Claverhouse are not going to let their friendship stop them from trying to humiliate each other. ...", title: 'Genevieve', score: 3.9916391372680664 }, { plot: "After a young man's premonition of a deadly race-car crash helps saves the lives of his peers, Death sets out to collect those who evaded their end.", title: 'The Final Destination', score: 3.9916391372680664 }, { plot: "A fast-paced comedy about a young Belgian car nut and hairdresser's apprentice, his girlfriend, and their legal and illegal attempts to get a Porsche under him for his nearing debut race.", title: 'The Departure', score: 3.832036256790161 } ]
MongoDB Search devuelve documentos que contienen los términos de consulta automobile, car o vehicle y race, context o rally porque configuramos automobile, vehicle y car para que sean equivalent sinónimos y configuramos rally y contest para que sean explicit sinónimos de race en la colección synonymous_terms.