0Pricing
Elasticsearch & Full Text Search Systems · Leçon

Mise en évidence des résultats de recherche

Ajoutez une mise en évidence à vos résultats de recherche pour accentuer visuellement les termes correspondants dans les documents renvoyés et améliorer l’expérience utilisateur.

Mise en évidence des résultats de recherche est une leçon Elasticsearch & Full Text Search Systems gratuite sur CoddyKit. Ceci est la leçon 3 sur 4. Tu peux lire la leçon complète ci-dessous gratuitement — puis la pratiquer en direct dans le navigateur avec un éditeur de code intégré et un tuteur IA 24/7. Elle fait partie du parcours d'apprentissage Elasticsearch & Full Text Search Systems, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours Elasticsearch & Full Text Search Systems comprend 4 leçons au total.

Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.

Why Highlight Results?

Imagine searching for a recipe and seeing 'chicken' highlighted exactly where it appears in the ingredients and steps. That's highlighting!

It visually emphasizes the matching terms in your search results, making it much easier for users to quickly scan and find relevant information.

  • Improved User Experience: Users quickly spot why a document is relevant.
  • Contextual Clues: Provides snippets of text around the match, giving context.
  • Faster Information Retrieval: Reduces time spent reading irrelevant parts.

Your First Highlight

Adding basic highlighting to your Elasticsearch search is straightforward. You just need to include a highlight block in your search request.

This block specifies which fields you want to highlight. By default, Elasticsearch wraps the matching terms with <em> and </em> tags.

curl -X GET "localhost:9200/products/_search?pretty" \
  -H 'Content-Type: application/json' \
  -d'
{
  "query": {
    "match": {
      "description": "lightweight laptop"
    }
  },
  "highlight": {
    "fields": {
      "description": {}
    }
  }
}'

Highlighting Specific Fields

In the previous example, we told Elasticsearch to highlight matches found in the description field.

The highlight.fields object is where you list all the fields you want to apply highlighting to. For each field, you can provide an empty object {} for default behavior, or specify custom options.

Only fields that are indexed for full-text search (like text fields) can be highlighted effectively.

Highlighting Multiple Fields

Often, you'll want to highlight matching terms across several fields within the same document, such as a product's title and its content.

Simply add more fields to the fields object in your highlight section. Elasticsearch will process each field independently.

curl -X GET "localhost:9200/articles/_search?pretty" \
  -H 'Content-Type: application/json' \
  -d'
{
  "query": {
    "match": {
      "text": "Elasticsearch indexing"
    }
  },
  "highlight": {
    "fields": {
      "title": {},
      "content": {}
    }
  }
}'

Customizing Highlight Tags

The default <em> tags are fine, but you might want to use different HTML tags or CSS classes for styling your highlighted terms.

You can change these using the pre_tags and post_tags parameters within your highlight block. These parameters accept arrays of strings.

curl -X GET "localhost:9200/products/_search?pretty" \
  -H 'Content-Type: application/json' \
  -d'
{
  "query": {
    "match": {
      "name": "wireless headphones"
    }
  },
  "highlight": {
    "pre_tags": ["<span class=\"highlight\">"],
    "post_tags": ["</span>"],
    "fields": {
      "name": {}
    }
  }
}'

Controlling Snippet Length (fragment_size)

When a document is very long, you usually don't want to return the entire field with highlights. Instead, you want short, relevant snippets.

The fragment_size parameter controls the maximum length (in characters) of the highlighted fragments. Elasticsearch tries to break fragments at sentence boundaries or natural breaks.

curl -X GET "localhost:9200/blogs/_search?pretty" \
  -H 'Content-Type: application/json' \
  -d'
{
  "query": {
    "match": {
      "body": "data analytics"
    }
  },
  "highlight": {
    "fragment_size": 100,
    "fields": {
      "body": {}
    }
  }
}'

Multiple Fragments & No Matches

You can also control the number of snippets returned per field using number_of_fragments. Set it to 0 to return the entire field content as a single fragment (if fragment_size is also 0).

What if there are no matches in a field, but you still want to see its content? Use no_match_size to specify the length of the fragment to return if no matches are found. By default, if there's no match, no fragment is returned for that field.

Advanced Fragment Boundaries

For even more precise control over how fragments are generated, you can use boundary_scanner, boundary_chars, and boundary_max_scan.

  • boundary_scanner: Defines how fragments are split (e.g., sentence, word, chars).
  • boundary_chars: Custom characters to use as fragment boundaries when boundary_scanner is chars.
  • boundary_max_scan: How far to scan for boundary characters.

These are useful for languages without clear sentence structures or for specific content types.

Highlighting from Matched Fields

Sometimes, your search query matches in one field (e.g., content), but you want to highlight the corresponding terms in another field (e.g., a shorter summary or title) for display.

The matched_fields parameter allows you to specify a list of fields that will be used to generate highlights for the current field. This is powerful for showing concise, highlighted snippets from a related, more prominent field.

curl -X GET "localhost:9200/documents/_search?pretty" \
  -H 'Content-Type: application/json' \
  -d'
{
  "query": {
    "match": {
      "full_text": "distributed systems"
    }
  },
  "highlight": {
    "fields": {
      "abstract": {
        "matched_fields": ["full_text"],
        "fragment_size": 100
      }
    }
  }
}'

Highlighting Options Quiz

Which of the following parameters can be used to customize how Elasticsearch generates search result highlights?

Recap: Emphasize Key Finds

You've learned how to bring your search results to life with highlighting! This powerful feature is crucial for improving user experience by visually emphasizing matching terms.

  • We started with basic highlighting using the highlight block.
  • You can specify fields to highlight and customize pre_tags/post_tags.
  • fragment_size and number_of_fragments give you control over snippet length and count.
  • Advanced options like boundary_scanner and matched_fields provide fine-grained control for complex scenarios.

Go forth and make your search results sparkle!

Questions Fréquemment Posées

La leçon « Mise en évidence des résultats de recherche » est-elle gratuite ?

Oui — le texte complet de « Mise en évidence des résultats de recherche » est gratuit à lire ici sur le web. Pour la pratiquer de manière interactive (un éditeur de code intégré et un tuteur IA 24/7) et déverrouiller le reste du cours Elasticsearch & Full Text Search Systems, passe à CoddyKit PRO. Le cours Elasticsearch & Full Text Search Systems comprend 4 leçons au total.

Qu'est-ce que j'apprendrai dans « Mise en évidence des résultats de recherche » ?

Ajoutez une mise en évidence à vos résultats de recherche pour accentuer visuellement les termes correspondants dans les documents renvoyés et améliorer l’expérience utilisateur. Tu pratiques Elasticsearch & Full Text Search Systems avec du code pratique que tu exécutes directement dans le navigateur, et un tuteur IA 24/7 répond à tes questions au fur et à mesure que tu avances dans la leçon.

Dois-je avoir de l'expérience pour commencer Elasticsearch & Full Text Search Systems ?

Aucune expérience préalable n'est requise. Elasticsearch & Full Text Search Systems sur CoddyKit est structuré pour les débutants jusqu'aux apprenants avancés, donc tu peux commencer ici ou depuis le début et avancer à ton rythme. Ceci est la leçon 3 sur 4.

Combien de temps prend la leçon « Mise en évidence des résultats de recherche » ?

La plupart des leçons CoddyKit prennent environ 5–10 minutes. Chacune est courte et interactive, tu progresses régulièrement et tu repiques exactement où tu t'es arrêté sur le web et l'app.

Peux-tu écrire et exécuter du code dans cette leçon Elasticsearch & Full Text Search Systems ?

Oui. Chaque leçon Elasticsearch & Full Text Search Systems inclut un éditeur de code intégré, tu écris et exécutes du vrai code directement dans ton navigateur et tu reçois des retours IA instantanés — aucune configuration locale requise.

Toutes les leçons de ce cours

  1. Recherches par expression et proximité
  2. Requêtes approximatives et avec caractères génériques
  3. Mise en évidence des résultats de recherche
  4. Agrégations pour la recherche à facettes
← Retour à Elasticsearch & Full Text Search Systems