from multi_match to function_score
A technically correct search that still shows the wrong products first costs revenue without ever showing up in an error log. Tuning search relevance in Magento 2 means understanding the underlying multi_match query, weighting attributes deliberately, and letting business signals such as sales figures and stock levels actively shape ranking.
Table of Contents
- 1. Why relevance is more than keyword matching
- 2. How Magento assembles the search query
- 3. search_weight and a boosting strategy per attribute
- 4. Adding custom query building blocks via a plugin
- 5. Function Score: bringing in popularity, margin and stock
- 6. Fuzzy matching and typo tolerance
- 7. A/B testing and measuring search relevance
- 8. Common pitfalls in relevance tuning
- 9. Relevance approaches compared
- 10. Summary
- 11. FAQ
1. Why relevance is more than keyword matching
Search relevance describes how well the order of search results matches what a customer is actually looking for and wants to buy. Plain keyword matching, which only checks whether a search term appears anywhere in the product data, is not enough for that. Two products can contain the exact same search term the exact same number of times and still be wildly different in relevance for the concrete search context.
In Magento this becomes obvious with ambiguous search terms. A search for a brand name should ideally surface that brand's flagship products first, not an accessory that only mentions the brand in a footnote of its description. Tuning search relevance means capturing exactly this distinction technically, through field weighting, business signals, and a deliberate structure of the underlying query.
The economic leverage is significant: customers who find nothing suitable on the first results page usually abandon the search rather than paging further. Every improvement to search relevance in the top result positions directly affects conversion rate and bounce rate of the internal search, often more than many other optimizations on checkout or product pages.
2. How Magento assembles the search query
By default, Magento builds a multi_match query against every field marked as searchable for full text search. The best_fields type is usually used when a single field should ideally match the search term well, while most_fields sums relevance across multiple fields. The choice between these two types directly affects search relevance, especially for products with very differently sized description texts.
{
"query": {
"bool": {
"must": [
{
"multi_match": {
"query": "waterproof hiking boots",
"type": "best_fields",
"fields": [
"name^5",
"sku^3",
"description^1",
"short_description^2"
],
"tie_breaker": 0.3
}
}
],
"filter": [
{ "term": { "visibility": 4 } },
{ "term": { "status": 1 } }
]
}
}
}
The tie_breaker parameter is a frequently overlooked lever for search relevance: it lets additional matches in other fields contribute proportionally to the score, instead of being ignored entirely once the best matching field is found. Without this parameter, a search that matches in two fields at once can end up with the same score as one that only matches in a single field, which unnecessarily limits fine grained relevance grading.
3. search_weight and a boosting strategy per attribute
The Search Weight attribute field in the Magento backend translates directly into the ^weight boost of the multi_match query, as visible on name^5 in the previous code example. A sound search relevance strategy starts with prioritization: product name and model number receive the highest weight, the short description a medium weight, and the long body description the lowest weight, since it is most likely to contain incidental word matches.
A common mistake is leaving every searched field at the same weight. That causes a product whose description happens to mention the search term several times to rank above a product whose name matches the search term exactly. For search relevance, the rule of thumb is: the shorter and more specific a field, the higher its weight should be, because a match there is more likely to be genuinely relevant.
The relative boost ordering between attributes should also be reviewed periodically, especially after catalog expansions. A new attribute with a high weight that accidentally matches too many products at once can dilute search relevance across the whole catalog without the effect being immediately obvious.
4. Adding custom query building blocks via a plugin
For adjustments beyond plain weighting, Magento offers the interface Magento\Framework\Search\Request\QueryInterface as well as the ability to inject additional query fragments into the generated request structure via a plugin. A typical use case: a boost for products currently on sale, or a bool.should clause that artificially raises exact SKU matches regardless of text score.
<?php
declare(strict_types=1);
namespace Mironsoft\SearchRelevance\Plugin;
use Magento\Elasticsearch\SearchAdapter\QueryContainer;
use Magento\Framework\Search\RequestInterface;
/**
* Adds a should clause that boosts exact SKU matches independent of text score.
*/
final class BoostExactSkuMatchPlugin
{
/**
* Injects an exact-match should clause for the sku field.
*
* @param QueryContainer $subject Original query container
* @param array $result Assembled OpenSearch query array
* @param RequestInterface $request Original search request
* @return array
*/
public function afterGetSearchQuery(
QueryContainer $subject,
array $result,
RequestInterface $request
): array {
$searchTerm = (string) $request->getQuery()->getValue();
if ($searchTerm === '') {
return $result;
}
$result['query']['bool']['should'][] = [
'term' => [
'sku' => [
'value' => strtoupper($searchTerm),
'boost' => 50,
],
],
];
return $result;
}
}
Important for search relevance: an additional should clause only increases the score additively, it does not automatically displace every other result. For a hard priority, where an exact SKU match should always rank first, a combination of a high boost value and a sufficient minimum_should_match is needed, otherwise other matches with many small boosts can theoretically catch up.
5. Function Score: bringing in popularity, margin and stock
Plain text score does not take business signals like sales figures, stock level or margin into account. The function_score query solves exactly this problem by multiplying or adding extra factors to the text score. For search relevance with real business impact, this is often the decisive building block: a product with high sales figures should, given otherwise similar text relevance, appear before a slow mover.
{
"query": {
"function_score": {
"query": {
"multi_match": {
"query": "running shoe",
"fields": ["name^5", "description^1"]
}
},
"functions": [
{
"field_value_factor": {
"field": "sales_count_30d",
"factor": 0.1,
"modifier": "log1p",
"missing": 0
}
},
{
"filter": { "term": { "in_stock": true } },
"weight": 1.5
},
{
"filter": { "range": { "special_price": { "gt": 0 } } },
"weight": 1.2
}
],
"score_mode": "sum",
"boost_mode": "multiply"
}
}
}
The log1p modifier is almost always the right choice for search relevance signals like sales figures on field_value_factor, because it dampens large differences. Without this dampening, a single extremely popular product would outshine every other text relevance signal. The sales_count_30d field needs to exist as its own, regularly updated attribute in the product index, usually populated through a dedicated indexer or cron job.
6. Fuzzy matching and typo tolerance
A significant share of real search queries contains typos, especially on mobile devices. Without fuzzy matching, these queries lead to zero result pages even though the searched product exists. The fuzziness parameter in the multi_match query allows a limited number of character deviations (Levenshtein distance), typically controlled via AUTO, which automatically adjusts tolerance to word length.
Caution is needed here for search relevance: overly aggressive fuzzy matching produces false positive hits on short words, where even a small deviation completely changes meaning. That is why fuzziness should only be enabled on fields with sufficiently long values, usually name and description, but not on short codes like sku, where fuzzy matching causes more harm than benefit.
{
"multi_match": {
"query": "hikeing boots",
"fields": ["name^5", "description^1"],
"fuzziness": "AUTO",
"prefix_length": 2,
"max_expansions": 30
}
}
The prefix_length parameter requires the leading characters to match exactly before fuzzy matching kicks in, which reduces computational load and simultaneously prevents nonsensical matches where only the end of a word happens to be similar.
7. A/B testing and measuring search relevance
Tuning search relevance without measurement is pure gut feeling. The most reliable indicator is the click through rate on the first three to five search results relative to the total number of searches with the same term. If this click through rate drops after a change, relevance has probably gotten worse, even if the change looked sensible on paper.
For solid conclusions, real A/B testing is worthwhile: part of the search traffic runs on the old query configuration, part on the new one, and both groups are compared over at least two weeks using click through rate, search conversion rate and bounce rate. On top of that, analyzing zero result searches provides valuable clues about which search terms fail despite matching products existing in the catalog, which is often more about synonyms than search relevance weighting, but closely related to it.
8. Common pitfalls in relevance tuning
The most common mistake is making every adjustment at once, weights, function score and fuzzy matching in a single deployment. If search relevance degrades afterwards, the root cause is nearly impossible to isolate. Changes should be rolled out and measured one at a time, even if that means more iterations.
A second pitfall: function score factors based on stale or infrequently updated fields. If sales_count_30d is only refreshed once a week via cron, search relevance reflects an outdated sales situation for days, which is particularly damaging during short lived campaigns or sale events and leads to wrong rankings. A third mistake: boost values are chosen by gut feeling without checking the actual score distribution in the concrete catalog, which easily leads to over or under compensation.
9. Relevance approaches compared
The following table compares common levers for search relevance and shows when each approach applies.
| Approach | Solves | Risk when overdone | Typical use |
|---|---|---|---|
| Field weighting (^Boost) | Prioritizes name over body text | Displaces genuinely relevant matches | Base configuration of every query |
| function_score | Brings in business signals | Popularity outshines text relevance | Prioritize bestsellers, stock |
| Fuzzy matching | Catches typos | False positives on short words | Name, description, not SKU |
| tie_breaker | Fine grading of multi field matches | Minimal, effect is moderate | Always enable |
This overview shows that the most effective levers for search relevance are rarely spectacular, they are precisely dosed adjustments measured one at a time.
Mironsoft
Magento search, relevance tuning and merchandising consulting
Does your search actually find the right products first?
We analyze your current search query, measure click through rate on the top result positions, and optimize field weighting, function score and fuzzy matching based on real search data.
Relevance audit
Analysis of top search terms and their current result quality
Function score setup
Bringing in business signals like stock level and sales figures
A/B testing
Measurable comparisons between old and new query configuration
10. Summary
Good search relevance in Magento emerges from the interplay of several layers: a sensibly weighted multi_match query as the foundation, function_score for business signals like sales figures and stock level, controlled fuzzy matching against typos, and a tie_breaker that fairly grades multi field matches. None of these levers work correctly in isolation, they need to be tuned together.
The most important success factor is measurability: click through rate on the top result positions, conversion rate of internal search, and analyzing zero result queries show whether a change to search relevance actually helps or just sounds plausible on paper. Rolling out changes one at a time and measuring them one at a time is more effort, but it is the only way to cleanly separate cause and effect.
Search Relevance in Magento 2 — Key Takeaways
Field weighting as the foundation
Weight name notably higher than body text, otherwise incidental word matches win.
function_score for business signals
Bring in sales figures, stock level and margin with log1p dampening.
Use fuzzy matching deliberately
Only enable on long text fields, never on short codes like SKU.
Measure instead of guessing
Compare click through rate, conversion and zero result searches before and after each change.