Advanced Search Capabilities

9 min read

Course: Elasticsearch

Topic: Advanced Search Capabilities

When you first start using Elasticsearch, you quickly learn the basics: matching a single word or finding an exact term. But real-world data is messy, users are demanding, and simple queries fall apart the moment a user misspells a word or asks for complex, multi-layered conditions.

In this guide, we are moving beyond basic searches to explore how industry-level applications handle search. We will combine queries, manipulate scoring mathematically, handle massive result sets gracefully, forgive human typos, and guide the user's eye exactly to what they searched for.

Before we dive in, let's establish a basic dataset. Imagine an e-commerce platform selling electronics. Here is a quick boilerplate to visualize the data structure we will query against.

json
PUT /tech_store
{
  "mappings": {
    "properties": {
      "product_name": { "type": "text" },
      "description": { "type": "text" },
      "brand": { "type": "keyword" },
      "price": { "type": "double" },
      "in_stock": { "type": "boolean" },
      "release_date": { "type": "date" }
    }
  }
}

1. The Bool Query: Combining Multiple Search Clauses 🧩

Definition: The bool query is a compound query that matches documents based on boolean combinations of other queries. It acts as the primary container for nesting multiple search conditions.

The Problem: You are building an e-commerce search bar. A user searches for a "laptop". But they used your sidebar filters to specify it must be an "Apple" brand, it must be "in stock", and they absolutely do not want "refurbished" items. A standard match query only takes one condition. You need a way to chain "AND", "OR", and "NOT" logic together in a single request.

The Solution: The bool query solves this by offering four specific occurrence types: must, must_not, filter, and should.

Imagine you are a strict HR recruiter sorting through resumes.

  • You must find a candidate who knows "JavaScript" (This affects their score; better JS developers rank higher).
  • They must_not have "malware creator" on their resume (Immediate rejection).
  • You filter out anyone who does not have a "Computer Science" degree (Strict yes/no check, but doesn't make one candidate "better" than another).
  • They should know "Elasticsearch" (It is not a dealbreaker, but candidates who know it get bonus points and are pushed to the top of the pile).

Here is how that logic translates to our e-commerce store in industry practice:

json
GET /tech_store/_search
{
  "query": {
    "bool": {
      "must": [
        { "match": { "product_name": "laptop" } }
      ],
      "filter": [
        { "term": { "brand": "Apple" } },
        { "term": { "in_stock": true } }
      ],
      "must_not": [
        { "match": { "description": "refurbished" } }
      ],
      "should": [
        { "match": { "description": "M3 chip" } }
      ]
    }
  }
}

Under the Hood & Industry Practice

Notice how we separated must and filter. Under the hood, Elasticsearch calculates a relevance score (_score) for every document matching a must or should clause. Math is computationally expensive.

The filter clause, however, runs in a non-scoring context. It simply asks: "Is the brand Apple? Yes or No." Because it skips the complex scoring math, Elasticsearch can heavily cache the results of a filter. Industry Standard: Always put exact-match criteria (dates, booleans, statuses, categories) inside a filter clause, and keep text-search criteria in must or should.


2. Controlling Relevance: Boosting and Scoring 🎯

Definition: Boosting is the process of modifying the calculated relevance score (_score) of documents to artificially rank certain fields or specific documents higher than they would naturally rank.

The Problem: A user searches for "headphones". Document A has the word "headphones" in the product_name. Document B is a 5-page long description of a smartphone that happens to mention "does not include headphones" three times. By pure keyword math, Document B might rank higher because the word appeared more times. You need to tell Elasticsearch that a match in the title is inherently more valuable than a match in the description.

The Solution: You apply a multiplier (a boost) to specific fields at query time.

json
GET /tech_store/_search
{
  "query": {
    "multi_match": {
      "query": "headphones",
      "fields": ["product_name^3", "description"]
    }
  }
}

In this example, the caret symbol (^3) tells Elasticsearch: "If you find a match in the product_name, multiply its base score by 3."

Under the Hood: The BM25 Algorithm

Elasticsearch doesn't just count words. It uses an algorithm called Okapi BM25. It looks at three main factors:

  1. Term Frequency (TF): How many times does the word appear in the document? (More is better).
  2. Inverse Document Frequency (IDF): How many times does the word appear across the entire database? (If the word "the" appears everywhere, it is useless. A rare word like "Sennheiser" is heavily rewarded).
  3. Field Length Norm: How long is the text field? (A match in a 5-word title is much more relevant than a match in a 5,000-word article).

By using the boost parameter ^, you are artificially injecting a multiplier into this BM25 equation to bend the ranking to your business needs. E-commerce sites frequently boost product titles, brand names, and occasionally inject custom scripts to boost products with higher profit margins.


3. Pagination: Navigating Large Result Sets 📖

Definition: Pagination is the technique of dividing a large set of search results into smaller, sequential, manageable chunks (pages) for retrieval and display.

The Problem: Your database has 500,000 laptops. A user searches for "laptop". Returning a JSON payload of half a million objects in a single API response will instantly crash your server, exhaust your memory, and fry the user's browser.

The Solution: You ask Elasticsearch to return a specific "slice" of the results using from and size.

json
GET /tech_store/_search
{
  "query": {
    "match": { "product_name": "laptop" }
  },
  "from": 20,
  "size": 10
}
  • size: The number of hits to return (defaults to 10).
  • from: The number of hits to skip. If size is 10, and you want Page 3, you skip the first 20 (from: 20).

The 10,000 Limit (Deep Pagination)

Using from and size works perfectly for basic web UI pagination (Pages 1 through 10). But try setting "from": 100000. Elasticsearch will throw an error.

Why? Imagine a massive library. Asking for page 5,000 of a sorted list is like asking a librarian to read, sort, and carry 4,999 books to their desk, throw them in the trash, and hand you the 5,000th one. It is incredibly wasteful. Elasticsearch explicitly blocks deep pagination past 10,000 hits to protect cluster memory.

Industry Practice: search_after
For infinite scrolling (like social media feeds) or exporting huge datasets, modern systems use the search_after API combined with a sort array.

  1. First, sort your query (usually by score, and a tie-breaker like release_date).
  2. Take the sort values from the last document in the returned array.
  3. Pass those values into the next query.
json
GET /tech_store/_search
{
  "query": { "match": { "product_name": "laptop" } },
  "size": 10,
  "sort": [
    { "_score": "desc" },
    { "release_date": "desc" } 
  ],
  "search_after": [ 1.4532, 1672531200000 ] 
}

This acts as a bookmark. The librarian no longer carries 5,000 books. They just go straight to the shelf marked "Score 1.4532, Date 2023-01-01" and hand you the next 10.


4. Fuzzy Searching and Typo Tolerance 🥴

Definition: A fuzzy query searches for documents containing terms that are similar to the search term, rather than an exact match, based on a mathematical measurement of string differences.

The Problem: Humans are flawed. We type on tiny mobile screens with fat thumbs while walking down the street. A user intends to buy an "iPhone" but types "iphne". A standard match query looks for exactly "iphne", finds 0 results, and the user leaves your app thinking you have no inventory.

The Solution: The fuzziness parameter. It forgives typos by automatically checking permutations of the inputted word.

json
GET /tech_store/_search
{
  "query": {
    "match": {
      "product_name": {
        "query": "iphne",
        "fuzziness": "AUTO"
      }
    }
  }
}

Under the Hood: Levenshtein Edit Distance

Fuzziness is calculated using the Levenshtein distance. This is the minimum number of single-character edits required to change one word into the other.
An "edit" is:

  • Insertion: iphne -> iphone (1 edit)
  • Deletion: lapttopp -> laptop (2 edits)
  • Substitution: samsang -> samsung (1 edit)

Industry Standard: Always use "fuzziness": "AUTO".
If you set a hard number like fuzziness: 2, a search for the two-letter word "TV" could match "PC" (2 substitutions). That ruins the user experience. "AUTO" handles this intelligently:

  • 0-2 character words must match exactly.
  • 3-5 character words allow 1 typo.
  • 6+ character words allow 2 typos.

5. Highlighting Match Results for User Interfaces 🖍️

Definition: Highlighting is the process of extracting the specific snippets of text where the user's search query matched, and wrapping the matched words in specific HTML tags.

The Problem: You have a digital library app. A user searches for "quantum entanglement". The search engine finds a match in a 400-page PDF document. If you just return the title of the PDF, the user has no idea why it matched or what the context is. They shouldn't have to read 400 pages to find the phrase.

The Solution: You request Elasticsearch to highlight the results. It will analyze the text, find the matching keywords, extract a small sentence around it, and wrap the keyword in HTML (by default, <em> tags).

json
GET /tech_store/_search
{
  "query": {
    "match": { "description": "noise cancelling" }
  },
  "highlight": {
    "fields": {
      "description": {}
    }
  }
}

The Response JSON:
Elasticsearch will append a new highlight object to every hit in the response.

json
"hits": [
  {
    "_id": "1",
    "_source": {
      "product_name": "Sony WH-1000XM4",
      "description": "These industry-leading noise cancelling headphones provide premium sound."
    },
    "highlight": {
      "description": [
        "These industry-leading <em>noise</em> <em>cancelling</em> headphones provide premium sound."
      ]
    }
  }
]

Industry Practice

Frontend frameworks (React, Vue) can take this highlight array and safely render it as HTML (using mechanisms like dangerouslySetInnerHTML in React, carefully sanitized).

If your frontend design system uses custom CSS classes instead of generic <em> tags, you can customize the wrapper at query time:

json
"highlight": {
  "pre_tags": ["<span class='search-highlight'>"],
  "post_tags": ["</span>"],
  "fields": {
    "description": {
      "fragment_size": 150,
      "number_of_fragments": 3
    }
  }
}

Here, fragment_size limits the length of the extracted sentence to 150 characters, ensuring your UI doesn't break if a massive wall of text is returned.


By mastering these five advanced capabilities, you transition from simply querying a database to engineering an intelligent, forgiving, and high-performance search experience.

References

Challenge

You are an Elasticsearch engineer for a large e-commerce platform. Your task is to construct a single, complex search query object that satisfies all of the following requirements for a user searching for products.

Requirements:

  1. The user's search term is "smrtphone", which may contain a typo. The query should be forgiving and match similar terms in the product_name and description fields.
  2. Matches found in the product_name field must be considered three times more relevant than matches in the description field.
  3. The query must only return products where the in_stock field is true. This filtering should be performance-optimized and not affect the relevance score.
  4. Results must explicitly exclude any products where the brand field is "GenericCorp".
  5. In addition to the primary search term, include products with a rating of 4.5 or higher. These should appear in the results but be ranked lower than direct matches if they don't match the search term.
  6. For the documents that are returned, configure highlighting for the description field. The matched terms should be wrapped in <strong> and </strong> tags.
  7. Implement efficient, deep pagination. You are fetching the second page of results. Assume each page has 20 items. The last document from the first page had a relevance score of 15.7 and a document _id of "456".

Expected result

Your Elasticsearch query should be a single JSON object with size, sort, query, search_after, and highlight as top-level keys.

The structure should be as follows:

  • size: Set to 20.
  • sort: An array sorting first by _score descending, then by _id ascending to ensure a consistent tie-breaking order for pagination.
  • search_after: An array containing the sort values from the last document of the previous page: [15.7, "456"].
  • highlight: An object that specifies pre_tags as ["<strong>"], post_tags as ["</strong>"], and targets the description field within a fields object.
  • query: A bool query object containing the following clauses:
    • must: A multi_match query searching for "smrtphone" in the ["product_name^3", "description"] fields. The ^3 applies the required boost. This query must also include the fuzziness: "AUTO" parameter to handle typos.
    • filter: A term query to match documents where in_stock is true.
    • must_not: A match query to exclude documents where brand is "GenericCorp".
    • should: A range query to find documents where the rating field has a value gte (greater than or equal to) 4.5.
json

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.