DEV Community

Erik Hatcher for MongoDB

Posted on • Edited on

Playing With Search: Query Term Highlighting

This article is part of a series. Please see the complete series above.

Visit the query term highlighting Playground.

The collection contains this document:

[
  {
    "_id": 1,
    "name": "Introduction to Atlas Search"
  }
]
Enter fullscreen mode Exit fullscreen mode

Enable highlighting and project the searchHighlights:

[
  {
    $search: {
      index: "default",
      text: {
        query: "atlas",
        path: "name"
      },
      highlight: {
        path: "name"
      }
    }
  },
  {
    $project: {
      highlights: {
        $meta: "searchHighlights"
      }
    }
  }
]
Enter fullscreen mode Exit fullscreen mode

The query searched for the word "atlas", and is shown in context of the full field value in the response:

[
  {
    "_id": 1,
    "highlights": [
      {
        "score": 1.3466932773590088,
        "path": "name",
        "texts": [
          {
            "value": "Introduction to ",
            "type": "text"
          },
          {
            "value": "Atlas",
            "type": "hit"
          },
          {
            "value": " Search",
            "type": "text"
          }
        ]
      }
    ]
  }
]
Enter fullscreen mode Exit fullscreen mode

The application code, when presenting the search results, can concatenate all the values, accentuating the hits.

Introduction to Atlas Search

Learn more search fundamentals!

Top comments (0)