Tuning Search Relevance in Magento with Precision
AI generated
_doc
_index
Magento · Search Relevance · Elasticsearch · Boosting
Tuning Search Relevance in Magento
deliberately, instead of leaving it to chance

Magento's default relevance treats every attribute by the same rules, regardless of whether a search request looks for SKU, brand, or description. Deliberately controlling search relevance via search weight, custom query builders, and function score boosting brings the products that actually matter for a given shop to the top.

19 min read Search Weight · Boosting · Function Score · Query Builder Magento 2.4.x · Elasticsearch 8.x · OpenSearch 2.x

1. What search relevance concretely means in Magento

Search relevance describes the order in which Magento displays search results when multiple products match a search request. Technically, relevance is not a fixed value but a numeric score Elasticsearch computes for every document in the context of a specific query. This score is based on the BM25 algorithm, which combines term frequency, inverse document frequency, and field length, but in Magento search this base score is additionally influenced by configurable weightings.

The most common frustration with search relevance in e-commerce search: a user searches for "wireless headphones" and gets as the first result a product whose description mentions "wireless" only in passing, while the actually relevant main product sits further down. This problem almost always arises because Magento's default weighting is not tuned to the specific catalog but uses generic values that are optimal for no shop in particular.

This article shows the three central levers for deliberately tuning search relevance in Magento: the per-attribute search weight configuration, custom adjustments to the query builder, and function score queries for business-logic boosting factors such as availability and freshness.

2. The search weight configuration in the backend

The simplest entry point for controlling search relevance is the search weight setting, configurable per attribute under Stores > Attributes > Product in the "Search Weight" field. This value ranges from 1 to 10 and determines how strongly a hit in that attribute contributes to the overall score. A high value for the sku field ensures that an exact article number search almost always returns the correct product first, while a lower value for description prevents random mentions in body text from dominating the ranking.

This configuration directly affects the generated Elasticsearch query: the search weight value is appended as a boost factor to the respective field name, in the format fieldname^weight. Important to understand: these boosts are relative to each other, not absolute. An attribute with weight 10 does not automatically dominate every search, it merely receives ten times the influence compared to an attribute with weight 1, within the same query.

3. How attribute weighting flows into the ES query

Technically, Magento reads the configured search weight values from the attribute configuration when building every search request and passes them to the query builder, which assembles the field list for the multi_match query from them. Every searchable field appears in this list with its individual boost suffix, so search relevance ultimately emerges from the interplay of all configured weights, not from a single value.

The type parameter within the multi_match query additionally influences how these weights are combined. The type best_fields takes the highest individual score across all fields, while cross_fields treats terms across multiple fields as a single large field, which often delivers more precise results for product searches with terms spanning name and description. Magento uses cross_fields by default for catalog search, which is important to know when interpreting search relevance results.


GET /magento2_product_1_v1/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "multi_match": {
            "query": "wireless headphones",
            "fields": ["sku^10", "name^5", "brand^3", "description^1", "short_description^2"],
            "type": "cross_fields"
          }
        }
      ]
    }
  }
}

4. The query builder: match, multi-match and boosting

The central building block for search relevance at the code level is Magento\Elasticsearch\SearchAdapter\Query\Builder\Match, which assembles the actual query clause from the user query string and the configured attribute weights. This class iterates over all searchable attributes, reads their search weight, and builds the boost suffix for each field. Anyone wanting to refine the default weighting beyond the backend, for example with non-linear weights or context-dependent adjustments, needs to hook in at this point.

A common use case for query builder adjustments is dynamic weighting depending on search term length or type: a search consisting entirely of digits usually indicates a SKU or EAN search and benefits from stronger weighting of exact fields, while a multi-word search benefits more from the default cross-fields logic. This kind of context-sensitive search relevance cannot be represented via the static backend configuration and requires intervention in the query builder itself.

5. Customizing query builder logic via a plugin

A plugin on the Match class allows the generated query to be modified deliberately before it is sent. The following approach detects numeric search terms and, in that case, additionally strengthens the weighting of the sku field, without changing the base configuration in the backend. This kind of search relevance adjustment stays update-safe because it works exclusively through the official extension point.


<?php
declare(strict_types=1);

namespace Mironsoft\SearchExtension\Plugin;

use Magento\Elasticsearch\SearchAdapter\Query\Builder\Match;
use Magento\Framework\Search\Request\Query\Match as MatchQuery;

/**
 * Boosts the sku field additionally when the search term looks like
 * a product code or EAN, improving relevance for exact-match queries.
 */
class NumericQueryBoostPlugin
{
    /**
     * Increases the sku boost for purely numeric or code-like search terms.
     *
     * @param Match $subject
     * @param array $result
     * @param MatchQuery $query
     * @return array
     */
    public function afterBuildQuery(Match $subject, array $result, MatchQuery $query): array
    {
        $queryText = $query->getValue();

        if (preg_match('/^[A-Z0-9\-]{5,}$/i', (string) $queryText)) {
            $result['bool']['must'][0]['multi_match']['fields'][] = 'sku^20';
        }

        return $result;
    }
}

6. Function score queries for e-commerce boosting

Search weight and query builder adjustments control textual search relevance but do not account for business-logic factors such as stock level, margin, or how recent a product is. A function_score query is made exactly for this, multiplying or adding to the text-based relevance score with additional factors. A product with high textual relevance but sold-out status can thus be deliberately downranked without disappearing from the search result.

The function_score query combines any number of field_value_factor and decay functions. field_value_factor multiplies the score by the value of a numeric field, for example the number of units sold. Decay functions such as gauss or exp reduce the score with increasing distance from a reference value, for example the creation date, so newer products tend to be weighted more strongly without completely hiding older ones.


GET /magento2_product_1_v1/_search
{
  "query": {
    "function_score": {
      "query": {
        "multi_match": {
          "query": "wireless headphones",
          "fields": ["sku^10", "name^5", "description^1"]
        }
      },
      "functions": [
        {
          "filter": { "term": { "in_stock": true } },
          "weight": 1.5
        },
        {
          "field_value_factor": {
            "field": "sales_count",
            "modifier": "log1p",
            "factor": 0.3
          }
        },
        {
          "gauss": {
            "created_at": { "origin": "now", "scale": "90d", "decay": 0.5 }
          }
        }
      ],
      "score_mode": "multiply",
      "boost_mode": "multiply"
    }
  }
}

7. Synonyms and stopwords as relevance levers

Besides boosting, the analyzer configuration also influences perceived search relevance. A synonym filter linking "headphones" with "headset" and "earbuds" ensures users with different word choices get the same hits, without the scoring mechanism itself changing. Stopwords such as "and," "the," "for" should be removed from the analyzer so they do not falsely contribute to term frequency and dilute relevance.

An often overlooked effect: an overly aggressive synonym filter can also worsen search relevance when it links terms that, in a given catalog, actually denote different product categories. A carefully curated, catalog-specific synonym list is therefore more important than generically importing prefabricated synonym databases.

Relevance Lever Effect Level Change Effort Typical Use
Search Weight Field boost in multi_match Backend configuration Base weighting per attribute
Query builder plugin Dynamic query structure Custom code Context-dependent adjustment
Function score Business logic factors Custom query extension Availability, freshness, margin
Synonyms / stopwords Analyzer configuration Index settings Vocabulary coverage

8. Measuring relevance: testing and A/B approaches

Without measurement, every search relevance adjustment remains gut feeling. The Elasticsearch _explain API shows, for a single document, how its score is composed of the individual query components, and is therefore the most important diagnostic tool when debugging individual cases. For systematic evaluation, a fixed set of test queries with defined "ideal" top hits is suitable, against which every change to weighting or function score can be checked automatically.

For production decisions, real user behavior is additionally recommended: click-through rate on search results, bounce rate after a search, and the position of the product actually purchased in the search result deliver more reliable signals than isolated score values. An A/B test comparing two boosting configurations against real traffic is the most reliable way to check whether a search relevance adjustment actually leads to more conversions.

9. Practical example: availability and freshness as boost factors

A realistic scenario: a fashion retailer notices that sold-out products, despite high textual relevance, keep appearing in the top search result positions, while new, available collection items sit further down. The solution combines the function_score query shown in section 6 with two specific functions: a filter boost for in_stock that does not hide sold-out products but noticeably downranks them, and a gauss decay function on the creation date that favors new items without completely displacing older bestsellers.

Important with this approach: the weights between textual search relevance and business-logic factors must be carefully calibrated. Too strong an availability boost can cause an exact SKU match to no longer rank first just because a thematically related but less relevant product happens to be better in stock. Iterative testing with the _explain API and real search requests from the logs is therefore part of any serious implementation.

Mironsoft

Search relevance tuning and Elasticsearch boosting for Magento

Want search results that fit your catalog?

We calibrate search weight, build function score queries for availability and margin, and measure the effect with real search requests instead of gut feeling.

Relevance audit

Systematically reviewing existing search weights and query structure

Function score boosting

Deliberately building availability, freshness and margin into the ranking

Measurable results

Test query sets and A/B tests for traceable relevance decisions

10. Summary

Search relevance in Magento emerges from the interplay of three levels: the per-attribute search weight configuration, which influences the base textual score, custom query builder adjustments for context-dependent cases such as SKU searches, and function score queries for business-logic factors such as availability, freshness, or margin. No single one of these levels alone delivers optimal results, their interplay decides the quality of the search.

Anyone wanting to sustainably improve search relevance should always make changes measurable: with the _explain API for individual cases, with fixed test query sets for systematic regression, and with real user behavior for final validation. This combination of technical control and measurement prevents relevance tuning from becoming a gut-feeling exercise.

Search relevance in Magento: the essentials at a glance

Search Weight

Attribute weighting 1 to 10 in the backend, works as a boost factor in the multi_match query.

Query builder plugin

Context-dependent weighting, for example a stronger SKU boost for numeric search terms.

Function score

Combines text relevance with availability, sales numbers and freshness.

Measurement

_explain API, fixed test query sets and A/B tests instead of gut feeling.

11. FAQ: Search Relevance in Magento

1What does Search Weight control?
A boost factor 1 to 10 per attribute, works as fieldname^weight in the multi_match query.
2Why isn't a high weight absolute?
Boosts are relative to each other and combined with the BM25 base score, not a fixed value.
3best_fields vs. cross_fields?
best_fields takes the highest field score, cross_fields combines fields as one. Magento uses the latter.
4When a custom query plugin?
For context-dependent logic that cannot be statically represented in the backend.
5What is function_score for?
For business factors like stock and sales numbers, combined with the text score.
6What does gauss decay do?
Reduces the score with distance from the reference value, favors newer without hiding older.
7Can synonyms hurt relevance?
Yes, when linking terms too aggressively across different product categories.
8How to diagnose a low ranking?
With the _explain API for document and query, shows the full score composition.
9How to test relevance changes?
Fixed test query sets for regression, A/B tests against real traffic for validation.
10How to calibrate the ratio?
Iteratively with _explain and real search requests, to avoid overshadowing exact hits.