Skip to the workspace
Pebellslearn by building
Controlling Search Results  ›  Capstone Project

Source Filtering and Highlighting

Highlighting 12 min_source filtering chooses which stored fields come back in each hit, and highlighting returns fragments with the matched terms wrapped in tags.

elasticsearch / Source Filtering and Highlighting

Explore each scene at your own pace.

01 · The rule

The rule

Source Filtering and Highlighting

The bookshop's result list shows only a title, a price and a snippet with the shopper's words in bold. Yet every hit comes back with the whole book — blurb, reviews, attributes and all. Two features shape the response to fit the screen: source filtering trims what comes back, and highlighting marks why each hit matched.

The rule

_source picks the fields you get back; highlight marks the words that matched.

Each hit normally includes _source, the original JSON you indexed. Source filtering trims it:

GET /books/_search
{
  "_source": [ "title", "price" ],
  "query": { "match": { "title": "garden" } }
}

Each hit's _source now holds only title and price. Other forms:

  • "_source": false — no source at all (you still get _id and _score).
  • "_source": { "includes": [ "title", "reviews.*" ], "excludes": [ "reviews.user" ] } — wildcards, plus exclusions applied after the includes.

This changes only what is returned. The query still searches every field, and the stored document is untouched. Smaller responses mean less data over the network and less JSON for the app to parse.

Highlighting returns fragments of text with the matching words wrapped in tags:

GET /books/_search
{
  "query": { "match": { "blurb": "slow travel" } },
  "highlight": {
    "fields": { "blurb": {} },
    "pre_tags": [ "<mark>" ],
    "post_tags": [ "</mark>" ]
  }
}

Each hit gains a highlight section:

"highlight": {
  "blurb": [ "An overnight journey that makes the case for <mark>slow</mark> <mark>travel</mark> across India." ]
}

Without pre_tags and post_tags, the default wrapper is <em>. Highlighting works on the terms the query matched, so a field only gets highlights if the query actually searched it. Long fields are cut into fragments around the matches; fragment_size and number_of_fragments control them.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.