La MongoDB Search highlight La opción añade campos al conjunto de resultados que muestran los términos de búsqueda en su contexto original. Puede usarla junto con todos los... $search operadores para mostrar los términos de búsqueda tal como aparecen en los documentos devueltos, junto con el contenido de texto adyacente (si lo hay). highlight resultados se devuelven como parte del campo $meta.
highlight Limitaciones de opciones
No puede utilizar la opción de búsqueda MongoDB highlight junto con el operador embeddedDocument.
Sintaxis
highlight tiene la siguiente sintaxis:
{ $search: { "index": "<index name>", // optional, defaults to "default" "<operator>": { // such as "text", "compound", or "phrase" <operator-specification> }, "highlight": { "path": "<field-to-search>", "maxCharsToExamine": "<number-of-chars-to-examine>", // optional, defaults to 500,000 "maxNumPassages": "<number-of-passages>" // optional, defaults to 5 } } }, { $project: { "highlights": { "$meta": "searchHighlights" } } }
opciones
Campo | Tipo | Descripción | ¿Requerido? |
|---|---|---|---|
| string | Campo de documento a buscar. El campo
| Sí |
| Int | Número máximo de caracteres a examinar en un documento al realizar el resaltado en un campo. Si se omite, el valor por defecto es | no |
| Int | Número de pasajes con alta puntuación que se devuelven por documento en los resultados | no |
El campo "$meta": "searchHighlights" contiene los resultados resaltados. Ese campo no forma parte del documento original, por lo que es necesario usar un Etapa de pipeline $project para añadirlo a la salida de la query.
Salida
El campo highlights es un arreglo que contiene los siguientes campos de salida:
Campo | Tipo | Descripción |
|---|---|---|
| string | Campo de documento que devolvió una coincidencia. |
| arreglo de documentos | Cada coincidencia de búsqueda retorna uno o más objetos que contienen el texto coincidente y el texto circundante (si lo hay). |
| string | Texto del campo que devolvió una coincidencia. |
| string | Tipo de resultado. El valor puede ser uno de los siguientes:
|
| float | Puntuación asignada al resultado coincidente. La |
Requisitos previos
Debes indexar el campo que deseas resaltar como un tipo de string de MongoDB Search, con indexOptions configurado en offsets (por defecto).
Ejemplos
Puedes probar los siguientes ejemplos en MongoDB Search Playground o en tu clúster.
Colección de muestra
Los ejemplos de esta página utilizan una colección llamada fruit que contiene los siguientes documentos:
{ "_id" : 1, "type" : "fruit", "summary" : "Apple varieties", "description" : "Apples come in several varieties, including Fuji, Granny Smith, and Honeycrisp. The most popular varieties are McIntosh, Gala, and Granny Smith.", "category": "organic" }, { "_id" : 2, "type" : "fruit", "summary" : "Banana", "description" : "Bananas are usually sold in bunches of five or six.", "category": "nonorganic" }, { "_id" : 3, "type" : "fruit", "summary" : "Pear varieties", "description" : "Bosc and Bartlett are the most common varieties of pears.", "category": "nonorganic" }
Índice de muestra
La colección fruit también tiene una definición de índice que utiliza el analizador ingles y asignaciones dinámicas de campos.
{ "analyzer": "lucene.english", "searchAnalyzer": "lucene.english", "mappings": { "dynamic": true } }
Nota
Un aspecto útil del resaltado es que revela el texto original devuelto por la consulta de búsqueda, que puede no ser exactamente el mismo que el término de búsqueda. Por ejemplo, si utilizas un analizador específico por idioma, tus búsquedas de texto devolverán todos los lexemas variaciones de tus términos de búsqueda.
Otro aspecto útil del resaltado es que puede usarse para resaltar cualquier campo, dentro o fuera de la query path. Por ejemplo, cuando se busca un término, puedes resaltar el término de búsqueda en el campo de query y en cualquier otro campo que especifiques utilizando la opción highlight. Para aprender más, consulte Ejemplo multifild.
Queries de muestra
Las siguientes consultas demuestran la $search highlight opción en las consultas de búsqueda de MongoDB.
Ejemplo básico
La siguiente query busca variety y bunch en el campo description de la colección fruit, con la opción highlight habilitada.
La etapa del pipeline $project restringe la salida al campo description y añade un nuevo campo llamado highlights, que contiene información de resaltado.
1 db.fruit.aggregate([ 2 { 3 $search: { 4 "text": { 5 "path": "description", 6 "query": ["variety", "bunch"] 7 }, 8 "highlight": { 9 "path": "description" 10 } 11 } 12 }, 13 { 14 $project: { 15 "description": 1, 16 "_id": 0, 17 "highlights": { "$meta": "searchHighlights" } 18 } 19 } 20 ])
1 { 2 "description" : "Bananas are usually sold in bunches of five or six. ", 3 "highlights" : [ 4 { 5 "path" : "description", 6 "texts" : [ 7 { 8 "value" : "Bananas are usually sold in ", 9 "type" : "text" 10 }, 11 { 12 "value" : "bunches", 13 "type" : "hit" 14 }, 15 { 16 "value" : " of five or six. ", 17 "type" : "text" 18 } 19 ], 20 "score" : 1.2841906547546387 21 } 22 ] 23 } 24 { 25 "description" : "Bosc and Bartlett are the most common varieties of pears.", 26 "highlights" : [ 27 { 28 "path" : "description", 29 "texts" : [ 30 { 31 "value" : "Bosc and Bartlett are the most common ", 32 "type" : "text" 33 }, 34 { 35 "value" : "varieties", 36 "type" : "hit" 37 }, 38 { 39 "value" : " of pears.", 40 "type" : "text" 41 } 42 ], 43 "score" : 1.2691514492034912 44 } 45 ] 46 } 47 { 48 "description" : "Apples come in several varieties, including Fuji, Granny Smith, and Honeycrisp. The most popular varieties are McIntosh, Gala, and Granny Smith. ", 49 "highlights" : [ 50 { 51 "path" : "description", 52 "texts" : [ 53 { 54 "value" : "Apples come in several ", 55 "type" : "text" 56 }, 57 { 58 "value" : "varieties", 59 "type" : "hit" 60 }, 61 { 62 "value" : ", including Fuji, Granny Smith, and Honeycrisp. ", 63 "type" : "text" 64 } 65 ], 66 "score" : 1.0330637693405151 67 }, 68 { 69 "path" : "description", 70 "texts" : [ 71 { 72 "value" : "The most popular ", 73 "type" : "text" 74 }, 75 { 76 "value" : "varieties", 77 "type" : "hit" 78 }, 79 { 80 "value" : " are McIntosh, Gala, and Granny Smith. ", 81 "type" : "text" 82 } 83 ], 84 "score" : 1.0940992832183838 85 } 86 ] 87 }
El término de búsqueda bunch devuelve una coincidencia en el documento con _id: 2, porque el campo description contiene la palabra bunches. El término de búsqueda variety devuelve una coincidencia en los documentos con _id: 3 y _id: 1 porque el campo description contiene la palabra varieties.
➤ Pruebe esto en el patio de búsqueda de MongoDB.
Ejemplo avanzado
La siguiente consulta busca variety y bunch en el campo description de la colección fruit, con la opción highlight habilitada, el número máximo de caracteres a examinar establecido en 40, y solo 1 fragmento altamente relevante para devolver por documento.
La etapa del pipeline $project restringe la salida al campo description y añade un nuevo campo llamado highlights, que contiene información de resaltado.
1 db.fruit.aggregate([ 2 { 3 $search: { 4 "text": { 5 "path": "description", 6 "query": ["variety", "bunch"] 7 }, 8 "highlight": { 9 "path": "description", 10 "maxNumPassages": 1, 11 "maxCharsToExamine": 40 12 } 13 } 14 }, 15 { 16 $project: { 17 "description": 1, 18 "_id": 0, 19 "highlights": { "$meta": "searchHighlights" } 20 } 21 } 22 ])
1 { 2 "description" : "Bananas are usually sold in bunches of five or six. ", 3 "highlights" : [ 4 { 5 "path" : "description", 6 "texts" : [ 7 { 8 "value" : "Bananas are usually sold in ", 9 "type" : "text" 10 }, 11 { 12 "value" : "bunches", 13 "type" : "hit" 14 }, 15 { 16 "value" : " of f", 17 "type" : "text" 18 } 19 ], 20 "score" : 1.313065767288208 21 } 22 ] 23 } 24 { 25 "description" : "Bosc and Bartlett are the most common varieties of pears.", 26 "highlights" : [ ] 27 } 28 { 29 "description" : "Apples come in several varieties, including Fuji, Granny Smith, and Honeycrisp. The most popular varieties are McIntosh, Gala, and Granny Smith.", 30 "highlights" : [ 31 { 32 "path" : "description", 33 "texts" : [ 34 { 35 "value" : "Apples come in several ", 36 "type" : "text" 37 }, 38 { 39 "value" : "varieties", 40 "type" : "hit" 41 }, 42 { 43 "value" : ", includ", 44 "type" : "text" 45 } 46 ], 47 "score" : 0.9093900918960571 48 } 49 ] 50 }
El segundo documento de los resultados anteriores contiene una matriz highlights vacía, aunque el campo de búsqueda contiene el término varieties, ya que MongoDB Search solo examinó 40 caracteres para resaltar. De igual forma, la palabra includ se trunca porque MongoDB Search solo examinó 40 caracteres en el campo de búsqueda para resaltar. En el tercer documento, aunque varios pasajes contienen el término de búsqueda, MongoDB Search solo devuelve un pasaje en los resultados highlights, ya que la consulta solo requería 1 pasajes por documento en los resultados highlights.
➤ Pruebe esto en el patio de búsqueda de MongoDB.
Ejemplo de campo múltiple
La siguiente consulta busca varieties en el campo description de la colección fruit, con la opción highlight habilitada para los campos description y summary.
La etapa de canalización $project agrega un nuevo campo highlights llamado, que contiene información resaltada para el término de consulta en todos los campos en la highlight opción.
1 db.fruit.aggregate([ 2 { 3 $search: { 4 "text": { 5 "path": "description", 6 "query": "varieties" 7 }, 8 "highlight": { 9 "path": ["description", "summary" ] 10 } 11 } 12 }, 13 { 14 $project: { 15 "description": 1, 16 "summary": 1, 17 "_id": 0, 18 "highlights": { "$meta": "searchHighlights" } 19 } 20 } 21 ])
1 { 2 "summary" : "Pear varieties", 3 "description" : "Bosc and Bartlett are the most common varieties of pears.", 4 "highlights" : [ 5 { 6 "path" : "summary", 7 "texts" : [ 8 { 9 "value" : "Pear ", 10 "type" : "text" 11 }, 12 { 13 "value" : "varieties", 14 "type" : "hit" 15 } 16 ], 17 "score" : 1.3891443014144897 }, 18 { 19 "path" : "description", 20 "texts" : [ 21 { 22 "value" : "Bosc and Bartlett are the most common ", 23 "type" : "text" 24 }, 25 { 26 "value" : "varieties", 27 "type" : "hit" 28 }, 29 { 30 "value" : " of pears.", 31 "type" : "text" 32 } 33 ], 34 "score" : 1.2691514492034912 35 } 36 ] 37 } 38 { 39 "summary" : "Apple varieties", 40 "description" : "Apples come in several varieties, including Fuji, Granny Smith, and Honeycrisp. The most popular varieties are McIntosh, Gala, and Granny Smith.", 41 "highlights" : [ 42 { 43 "path" : "summary", 44 "texts" : [ 45 { 46 "value" : "Apple ", 47 "type" : "text" 48 }, 49 { 50 "value" : "varieties", 51 "type" : "hit" 52 } 53 ], 54 "score" : 1.3859853744506836 55 }, 56 { 57 "path" : "description", 58 "texts" : [ 59 { 60 "value" : "Apples come in several ", 61 "type" : "text" 62 }, 63 { 64 "value" : "varieties", 65 "type" : "hit" 66 }, 67 { 68 "value" : ", including Fuji, Granny Smith, and Honeycrisp. ", 69 "type" : "text" 70 } 71 ], 72 "score" : 1.0330637693405151 73 }, 74 { 75 "path" : "description", 76 "texts" : [ 77 { 78 "value" : "The most popular ", 79 "type" : "text" 80 }, 81 { 82 "value" : "varieties", 83 "type" : "hit" 84 }, 85 { 86 "value" : " are McIntosh, Gala, and Granny Smith.", 87 "type" : "text" 88 } 89 ], 90 "score" : 1.0940992832183838 91 } 92 ] 93 }
El término de búsqueda varieties devuelve una coincidencia en documentos con _id: 1 y _id: 3 porque el campo de query description en ambos documentos contiene el término de query varieties. Además, el arreglo highlights incluye el campo summary porque el campo contiene el término de consulta varieties.
➤ Pruebe esto en el patio de búsqueda de MongoDB.
Ejemplo de comodín
La siguiente query busca el término varieties en los campos que comienzan con des en la colección fruit, con la opción highlight habilitada para los campos que comienzan con des.
La etapa de canalización $project agrega un nuevo campo highlights llamado, que contiene información destacada.
1 db.fruit.aggregate([ 2 { 3 "$search": { 4 "text": { 5 "path": {"wildcard": "des*"}, 6 "query": ["variety"] 7 }, 8 "highlight": { 9 "path": {"wildcard": "des*"} 10 } 11 } 12 }, 13 { 14 "$project": { 15 "description": 1, 16 "_id": 0, 17 "highlights": { "$meta": "searchHighlights" } 18 } 19 } 20 ])
1 { 2 "description" : "Bosc and Bartlett are the most common varieties of pears.", 3 "highlights" : [ 4 { 5 "path" : "description", 6 "texts" : [ 7 { 8 "value" : "Bosc and Bartlett are the most common ", 9 "type" : "text" 10 }, 11 { 12 "value" : "varieties", 13 "type" : "hit" 14 }, 15 { 16 "value" : " of pears.", 17 "type" : "text" 18 } 19 ], 20 "score" : 1.2691514492034912 21 } 22 ] 23 }, 24 { 25 "description" : "Apples come in several varieties, including Fuji, Granny Smith, and Honeycrisp. The most popular varieties are McIntosh, Gala, and Granny Smith.", 26 "highlights" : [ 27 { 28 "path" : "description", 29 "texts" : [ 30 { 31 "value" : "Apples come in several ", 32 "type" : "text" 33 }, 34 { 35 "value" : "varieties", 36 "type" : "hit" 37 }, 38 { 39 "value" : ", including Fuji, Granny Smith, and Honeycrisp. ", 40 "type" : "text" 41 } 42 ], 43 "score" : 1.0330637693405151 44 }, 45 { 46 "path" : "description", 47 "texts" : [ 48 { 49 "value" : "The most popular ", 50 "type" : "text" 51 }, 52 { 53 "value" : "varieties", 54 "type" : "hit" 55 }, 56 { 57 "value" : " are McIntosh, Gala, and Granny Smith.", 58 "type" : "text" 59 } 60 ], 61 "score" : 1.0940992832183838 62 } 63 ] 64 }
En los resultados de búsqueda de MongoDB, los campos que comienzan con des están resaltados.
➤ Pruebe esto en el patio de búsqueda de MongoDB.
Ejemplo compuesto
La siguiente consulta busca el término organic en el campo category y variety en el campo description. La opción highlight en la $search compound query solicita información de destacado solo para la text query contra el campo description. Es importante tener en cuenta que la opción highlight dentro de la fase $search debe ser un elemento hijo de la fase $search, y no de ningún operador dentro de la fase $search.
La etapa de canalización $project agrega un nuevo campo highlights llamado, que contiene información destacada.
1 db.fruit.aggregate([ 2 { 3 "$search": { 4 "compound": { 5 "should": [{ 6 "text": { 7 "path": "category", 8 "query": "organic" 9 } 10 }, 11 { 12 "text": { 13 "path": "description", 14 "query": "variety" 15 } 16 }] 17 }, 18 "highlight": { 19 "path": "description" 20 } 21 } 22 }, 23 { 24 "$project": { 25 "description": 1, 26 "category": 1, 27 "_id": 0, 28 "highlights": { "$meta": "searchHighlights" } 29 } 30 } 31 ])
1 [ 2 { 3 description: 'Apples come in several varieties, including Fuji, Granny Smith, and Honeycrisp. The most popular varieties are McIntosh, Gala, and Granny Smith.', 4 category: 'organic', 5 highlights: [ 6 { 7 score: 1.0330637693405151, 8 path: 'description', 9 texts: [ 10 { value: 'Apples come in several ', type: 'text' }, 11 { value: 'varieties', type: 'hit' }, 12 { 13 value: ', including Fuji, Granny Smith, and Honeycrisp. ', 14 type: 'text' 15 } 16 ] 17 }, 18 { 19 score: 1.0940992832183838, 20 path: 'description', 21 texts: [ 22 { value: 'The most popular ', type: 'text' }, 23 { value: 'varieties', type: 'hit' }, 24 { 25 value: ' are McIntosh, Gala, and Granny Smith.', 26 type: 'text' 27 } 28 ] 29 } 30 ] 31 }, 32 { 33 description: 'Bosc and Bartlett are the most common varieties of pears.', 34 category: 'nonorganic', 35 highlights: [ 36 { 37 score: 1.2691514492034912, 38 path: 'description', 39 texts: [ 40 { 41 value: 'Bosc and Bartlett are the most common ', 42 type: 'text' 43 }, 44 { value: 'varieties', type: 'hit' }, 45 { value: ' of pears.', type: 'text' } 46 ] 47 } 48 ] 49 } 50 ]
➤ Pruebe esto en el patio de búsqueda de MongoDB.
Ejemplo de autocompletar
Para este ejemplo, la fruit colección también tiene la siguiente definición de índice.
{ "mappings": { "dynamic": false, "fields": { "description": [ { "type": "autocomplete", "tokenization": "edgeGram", "minGrams": 2, "maxGrams": 15, "foldDiacritics": true } ] } } }
La siguiente consulta busca los caracteres var en el campo description de la colección fruit, con la opción highlight habilitada para el campo description.
La etapa de canalización $project agrega un nuevo campo highlights llamado, que contiene información destacada.
Importante
Para resaltar la versión indexada de autocompletar de una ruta, el operador de autocompletar debe ser el único operador que utilice esa ruta en la consulta.
1 db.fruit.aggregate([ 2 { 3 "$search": { 4 "autocomplete": { 5 "path": "description", 6 "query": ["var"] 7 }, 8 "highlight": { 9 "path": "description" 10 } 11 } 12 }, 13 { 14 "$project": { 15 "description": 1, 16 "_id": 0, 17 "highlights": { "$meta": "searchHighlights" } 18 } 19 } 20 ])
1 { 2 "description": "Apples come in several varieties, including Fuji, Granny Smith, and Honeycrisp. The most popular varieties are McIntosh, Gala, and Granny Smith.", 3 "highlights": [ 4 { 5 "score": 0.774385392665863, 6 "path": "description", 7 "texts": [ 8 { "value": "Apples come in several ", "type": "text" }, 9 { "value": "varieties, including Fuji", "type": "hit" }, 10 { "value": ", Granny Smith, and Honeycrisp. ", "type": "text" } 11 ] 12 }, 13 { 14 "score": 0.7879307270050049, 15 "path": "description", 16 "texts": [ 17 { "value": "The most popular ", "type": "text" }, 18 { "value": "varieties are McIntosh", "type": "hit" }, 19 { "value": ", Gala, and Granny Smith.", "type": "text" } 20 ] 21 } 22 ] 23 }, 24 { 25 "description": "Bosc and Bartlett are the most common varieties of pears.", 26 "highlights": [ 27 { 28 "score": 0.9964432120323181, 29 "path": "description", 30 "texts": [ 31 { 32 "value": "Bosc and Bartlett are the most common ", 33 "type": "text" 34 }, 35 { "value": "varieties of pears", "type": "hit" }, 36 { "value": ".", "type": "text" } 37 ] 38 } 39 ] 40 }
MongoDB Search devuelve una coincidencia en los documentos con _id: 1 y id_: 2 para la string del query var porque el campo description en la colección fruit contiene los caracteres var al principio de una palabra. MongoDB Search hace coincidir un hit destacado de manera más general con tus términos de query cuando una ruta destacada solo se referencia en los operadores de autocompletar de la query destacada.
➤ Pruebe esto en el patio de búsqueda de MongoDB.