La búsqueda de MongoDB 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 Los resultados se devuelven como parte del $meta campo.
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 | ¿Obligatorio? |
|---|---|---|---|
| string | Campo de documento para 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 canalización del proyecto $project para agregarlo a la salida de la consulta.
Salida
El campo highlights es una matriz que contiene los siguientes campos de salida:
Campo | Tipo | Descripción |
|---|---|---|
| string | Campo de documento que devolvió una coincidencia. |
| conjunto de documentos | Cada coincidencia de búsqueda devuelve 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
Debe indexar el campo que desea resaltar como un tipo de cadena de búsqueda de MongoDB con indexOptions establecido en offsets (predeterminado).
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 fruit colección también tiene una definición de índice que utiliza el analizador inglés y asignaciones de campos dinámicos.
{ "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 utiliza un analizador específico para cada idioma, sus búsquedas de texto devuelven todas las palabras derivadas. variaciones de sus términos de búsqueda.
Otra característica útil del resaltado es que permite resaltar cualquier campo, dentro o fuera de la path consulta. Por ejemplo, al buscar un término, se puede resaltar el término de consulta en el campo de consulta y en cualquier otro campo que se especifique con la highlight opción. Para obtener más información, consulte el ejemplo de campos múltiples.
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 consulta busca variety y bunch en el campo description de la colección fruit, con la opción highlight habilitada.
La etapa de canalización $project restringe la salida al description campo y agrega un nuevo campo highlights llamado, que contiene información destacada.
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 coincide con el documento _id: 2, porque el campo description contiene la palabra bunches. El término de búsqueda variety coincide con los documentos _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 pasajes con puntaje alto para devolver por documento.
La etapa de canalización $project restringe la salida al description campo y agrega un nuevo campo highlights llamado, que contiene información destacada.
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 campos múltiples
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 consulta 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 de la consulta compuesta$searchsolicita que se resalte la información solo para la consulta de texto en el campo description. Tenga en cuenta que la opción highlight dentro de la etapa$searchdebe ser un elemento secundario de la etapa$searchy no de ningún operador dentro de la etapa$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.