Site search that sells: making your shop's search find what people mean
TL;DR
Difficulty: Intermediate
People who search convert better mostly because they arrive knowing what they want. The job of search is to stop failing them.
- Read your search log first: sort the top queries by type and fix the common failures.
- Synonyms and spelling entries fix most zero result searches. They are a shop decision, so give them an owner.
- Typo tolerance is weak on short words, stemming handles plurals, and German compounds need a tool built for them.
- A zero result page should suggest categories, alternatives and contact, not just spelling tips.
- Rank by relevance first. Stock, popularity and margin only break ties, and paid placements must be labelled.
- Track five numbers monthly: usage, zero results, exits, refinements and search conversion.
- For a shop of about 1,400 products, PostgreSQL with pg_search is a sound start. Plan the move to a search server for a second language or scale.
What to read first
The words people type into your search box are the most honest research you will ever get: what they want, in their own language. This chapter shows why searchers convert better, why that is only partly the box's doing, and how to build a search that finds what people mean, with the maths, the measurements and the code for a shop on Solidus.
The visitor who types is telling you what they want
Most visitors to an online shop browse. They open a category, scroll, tap a filter, open a product. A smaller group skips all of that and types into the search box. Those few words are the most honest thing a visitor ever tells you: what they want, in their own language, before you have shaped their thinking with your menus.
That makes the search box two things at once. It is a sales tool, because people who type usually know what they are after. And it is a research tool, because the words they type show you every gap between how you describe your range and how your customers think about it.
This chapter first explains why searchers look like better customers, and why that is only partly the search box's doing. Then it goes through every part of a search that helps people buy, how to measure it, and the engines to run it on, with code for a shop built on Solidus.
If you have not read the previous chapter, category pages, navigation and filters that help people find, it covers the browsing half of finding a product. This chapter is the typing half.
A few terms first. A query is what someone types into the search box. The index is the prepared copy of your product data that a search engine looks things up in, a bit like the index at the back of a book. Relevance is how well a product matches what the person meant. Ranking is the order the results appear in.
Example: the shop in this series
Every chapter in this series uses the same invented shop. Wrenfield Home (wrenfieldhome.example) is an online homeware shop in Leeds, owned by Priya, with Callum as her developer. It sells ceramics, kitchen textiles, lamps and small furniture, about 1,400 products, and runs on Solidus. Its baseline figures for a month:
| Figure | Value |
|---|---|
| Sessions | 110,000 |
| Conversion rate | 1.8% |
| Orders | 1,980 |
| Average order value | £72 |
| Revenue | £142,560 |
| Gross margin on product | 52% |
For this chapter I add some invented search figures, used throughout: 15% of sessions use the search box at least once, that is 16,500 sessions, and those sessions run 24,800 searches between them.
Why searchers convert better, and why that is not the whole story
Look at almost any shop's analytics and the sessions with a search in them convert far better than the sessions without. It is tempting to read that as "search makes people buy", so make search bigger and sales will follow. Half of that is true.
People who search usually arrive with something specific in mind. Jakob Nielsen observed as far back as 1997 that more than half of website users were "search dominant", heading straight for the search box, while about a fifth preferred to follow links1. That is an old observation about websites in general, not a shop benchmark, but the logic still holds: someone who types "oval linen tablecloth" is further along in their decision than someone who opened the homepage to look around. Part of the higher conversion rate belongs to the person, not to the box. Statisticians call that self selection: the group chose itself, so comparing it with everyone else mixes up who they are with what the tool did.
This matters, because it changes what you should do. Pushing more browsers into the search box does not turn them into determined buyers. What search can do is stop losing the determined buyers who already use it. Every search that returns nothing, the wrong thing, or the right thing on page three is a person who was ready to buy and could not.
The shop's overall conversion rate is a weighted average of the two groups. See Foundations: mean if weighted averages are new to you.
where is the shop's overall conversion rate, is the share of sessions that use search, is the conversion rate of sessions with a search, and is the conversion rate of sessions without one.
Example: Wrenfield's searchers against its browsers
Of Wrenfield's 110,000 sessions, 16,500 used search, so . Those 16,500 sessions produced 726 orders, so , or 4.4%. The other 93,500 sessions produced the remaining orders, so , or 1.34%. The weighted average checks out: .
Searchers convert at about 3.3 times the rate of browsers. Now Priya asks the obvious question: if she makes the search box twice as prominent and 20% of sessions search instead of 15%, does the shop's conversion rate jump?
Suppose the extra 5% of sessions are browsers who would otherwise have used the menus. They bring their own intent with them, so they convert at roughly the browser rate of 1.34%, whichever box they use. The overall rate stays at 1.80%. The search box got busier and the shop sold nothing extra. The real lever is the other one: raising itself by making each search succeed more often. If better search lifted from 4.4% to 5.0% for the same 16,500 sessions, Wrenfield would gain orders a month, worth in revenue.
That is the rest of this chapter: how to raise the success rate of the searches you already get.
Know what people type: the eight kinds of query
Before you tune anything, look at what people actually type. Baymard Institute, which runs large usability studies of online shops, sorts shop search queries into eight types and has benchmarked how many sites struggle with each2. In its 2026 update it found that 56% of the sites it benchmarked do not adequately support what shoppers search for2.
| Query type | What it looks like at Wrenfield | Sites with issues (Baymard) |
|---|---|---|
| Exact | "Hebden stoneware mug" | 12% |
| Product type | "table lamp", "throws" | 20% |
| Feature | "blue", "linen", "dishwasher safe" | 39% |
| Use case | "lamp for reading", "gift for a new home" | 43% |
| Compatibility | "shade for E27 bulb" | 44% |
| Symptom | "stop rug slipping" | 37% |
| Abbreviation and symbol | "40cm cushion", "6 pc set" | 54% |
| Non product | "returns", "delivery times", "gift card" | 66% |
The percentages are Baymard's, for the sites in its benchmark, and they show where search engines commonly fail. Baymard also found that 34% of its test participants used the search field to look for content that was not a product at all, such as help or policy pages2. A shop that only indexes products sends those people to a dead end.
Example: Priya classifies her top 50 queries
Callum exports the 50 most common queries from the last 30 days (the measurement section below shows how) and Priya sorts them by type. Of the 50:
- 9 are exact product names, almost all of which already work.
- 17 are product types, and 4 of those fail because customers use different words from the shop ("settee" where the shop says "sofa", "throw" where it says "blanket").
- 8 are features, mostly colours and materials, which only work when the word appears in the product name.
- 5 are use cases, and none of them work, because no product description says "reading" or "new home".
- 4 contain sizes with units, and "40cm" fails while "40 cm" works.
- 7 are non product queries such as "returns" and "track order", all of which return nothing.
That afternoon of sorting gives Priya a fix list ordered by how often each problem occurs. No tool can do it for her, because only she knows that a "throw" and a "blanket" are the same thing in her shop.
Put the box where people look for it
Search only helps if people can find the box. Nielsen's long standing advice is that search should be a field you can type into straight away, not a link to a separate search page, placed near the top of every page, and wide enough to hold a typical query3. On a phone, a magnifying glass icon that opens the field is the norm, but the field should open with the keyboard ready.
Two smaller details matter more than they look: keep the query in the box on the results page, so people can correct it, and give mobile users a visible search button.
Example: Wrenfield's mobile header
Callum checks Wrenfield's mobile header on a real phone: tapping the search icon opens the field with the keyboard up, and there is a visible search button. But after searching "linen napkins", the results page shows an empty field. A one line fix in the template means a customer who wants "linen napkins green" now adds one word instead of retyping three.
Autocomplete: help people finish the query
Autocomplete shows suggestions under the box while someone types. Done well, it does three jobs: it saves typing on a phone, it corrects spelling before the search even runs, and it teaches people the words your shop uses. Baymard found autocomplete on 80% of shops it studied, but only 19% got all of its implementation details right4.
The main rules from that research4:
- Suggest queries and categories, not only products. "table lamps" and "table lamps in Lighting" are more useful than ten individual lamps when someone has typed four letters.
- Keep the list short: no more than about 10 suggestions on desktop, and around 4 to 8 on mobile, where the keyboard takes half the screen.
- Tolerate misspellings in the suggestions too, not just in the final search.
- Make the suggestions keyboard friendly, so arrow keys move through them and the chosen one is copied into the field.
For accessibility, an autocomplete list is a combobox pattern: the field and its suggestion list need the right roles and states so a screen reader announces how many suggestions there are and which one is selected. The accessible checkout article covers the same principles for forms.
Example: what "lin" should suggest
A customer on a phone types "lin". Wrenfield has 64 linen products across three categories. A good autocomplete shows six lines:
- linen napkins
- linen tablecloths
- linen cushion covers
- linen tea towels
- All linen in Kitchen textiles
- All linen in Cushions and throws
Four of the six are popular complete queries, taken from the search log, and two are category scopes. The customer taps "linen tablecloths" and lands on a results page that already matches how the shop is organised, after three letters and one tap instead of 17 characters on a small keyboard.
Typo tolerance: find the product even when the spelling is wrong
People misspell, especially on phones. Typo tolerance means the engine still finds "cushion" when someone types "cushon". There are two common ways to do it, and they behave differently on short and long words.
The first is edit distance: how many single letter changes (insert, delete, swap) turn one word into the other. Dedicated engines usually work this way. Meilisearch, for example, allows no typos in query words of 1 to 4 characters, one typo in words of 5 to 8 characters, and at most two typos in longer words by default5. Short words get no tolerance because too many short words are one letter apart.
The second, available inside PostgreSQL through the pg_trgm extension, is trigram similarity. A trigram is a group of three consecutive characters. PostgreSQL pads each word with two spaces in front and one behind, splits it into trigrams, and measures how many trigrams two words share6. See Foundations: ratios and rates for the idea of a share.
where is the similarity of words and , between 0 and 1, and are the sets of trigrams of each word, is the number of trigrams they share, and is the number of distinct trigrams across both. By default PostgreSQL treats two strings as similar when this value is above 0.36.
Example: why "cushon" works and "vace" does not
Take "cushion" and the typo "cushon". The trigrams of "cushion" (with the padding shown as spaces) are: " c", " cu", "cus", "ush", "shi", "hio", "ion", "on ". That is 8. The trigrams of "cushon" are: " c", " cu", "cus", "ush", "sho", "hon", "on ". That is 7.
They share five: " c", " cu", "cus", "ush", "on ". The union holds distinct trigrams, so . That is above 0.3, so "cushon" finds the cushions.
Now "vase" and the typo "vace". "vase" has " v", " va", "vas", "ase", "se ", five trigrams. "vace" has " v", " va", "vac", "ace", "ce ", also five. They share only two, " v" and " va", and the union holds , so . That is below 0.3, so the customer sees nothing. One wrong letter in a four letter word destroys most of its trigrams. Lowering the threshold to 0.25 would rescue "vace", but it would also start matching unrelated short words everywhere. The honest fix for short, common misspellings is a small correction list: Callum adds "vace" to the synonym table described next, pointing at "vase". The search log tells him which misspellings are common enough to deserve an entry.
Synonyms: speak your customers' language
Baymard's product type finding is the one I would fix first in most shops: a search engine that only knows the shop's own words fails everyone who uses a different word for the same thing2. Your catalogue says "sofa", your customers in Leeds say "settee", and some say "couch". Your catalogue says "blanket", Instagram says "throw".
A synonym list fixes this. There are two kinds of entry:
- Two way synonyms, where the words mean the same thing: sofa, settee, couch. A search for any of them finds products described with any of them.
- One way synonyms, where one word is broader: a search for "lighting" should find lamps, but a search for "lamp" should not return every light bulb and candle. So "lighting" expands to "lamp", "pendant" and "shade", and not the other way round.
Synonyms are a shop decision, not a technical one. They come from your search log and your customer service inbox, and they need an owner.
Example: Wrenfield's first synonym list
From the zero result queries of one month, Priya and Callum write this list:
| Customers type | Shop says | Kind |
|---|---|---|
| settee, couch | sofa | two way |
| throw, throws | blanket | two way |
| dish towel, tea cloth | tea towel | two way |
| dinner set | dinnerware set | two way |
| lighting | lamp, pendant, shade | one way |
| eggcup | egg cup | two way |
| lamp shade | lampshade | one way (format) |
| vace | vase | one way (spelling) |
| 40cm | 40 cm | one way (format) |
Nine lines. In the measurement section you will see what these nine lines do to the zero result rate.
Plurals and word forms: stemming
"Cushion" and "cushions" are the same product. So are "ceramic" and "ceramics". A search engine handles this with stemming: reducing each word to a common base, its stem, both when it builds the index and when it reads the query. PostgreSQL's full text search ships Snowball stemmers for many languages, including English and German, which "reduce common variant forms of words to a base"7.
Stemming can be too eager, folding together words that mean different things, and it does nothing for compound words, which brings us to German.
Example: "linen cushions" and "linen cushion"
A product is called "Linen cushion, sage green". A customer types "linen cushions". With English stemming, both "cushion" in the product name and "cushions" in the query become the same stem, so the product matches. Without stemming, a strict word match would miss it, and the customer would see a result list that oddly lacks the one product that matches perfectly. In PostgreSQL this is the difference between searching with the english configuration and searching with simple, which does no stemming at all.
Why search in German is harder
If you sell into Germany or Austria, or run a German version of your shop, search needs extra work, for three reasons.
Compound words. German glues nouns together. A "Leinenkissen" is a linen cushion, a "Kaffeetasse" a coffee cup, a "Tischleuchte" a table lamp. Someone who types "Kissen" (cushion) expects to see the "Leinenkissen", but a normal word match sees one long word that is not "Kissen". A stemmer does not help, because it only trims endings. Trigrams do not help much either: "Kaffeetasse" and "Tasse" share only 4 of 14 distinct trigrams, a similarity of about 0.29, just under PostgreSQL's default threshold.
Umlauts and ß. Customers type "Kuechenhandtuch" or "Kuchenhandtuch" when the product says "Küchenhandtuch", because their keyboard or their habit says so. The engine has to treat ü, ue and u as close enough. PostgreSQL's unaccent extension strips accents for matching, but it does not turn "ue" back into "ü", so you need both rules.
Two ways to say one thing. "Leinenkissen" and "Kissen aus Leinen" are the same product, written as one word or as three.
The tools exist. PostgreSQL's Ispell dictionaries can split compound words when you supply a dictionary that supports it, though PostgreSQL implements only the basic compound operations7. Elasticsearch and OpenSearch have decompounder token filters built for Germanic languages; Elastic's own documentation example splits "Kaffeetasse" into "Kaffee" and "tasse"89. Meilisearch lists compound word decomposition for German in its language support10. Whatever you choose, test it with your own catalogue's compounds, because no general dictionary knows every product word you invented.
Example: the German pages at Wrenfield
Wrenfield ships to Germany and is considering German product pages. Callum takes the 20 most common German compounds in the translated catalogue ("Leinenkissen", "Kaffeetasse", "Tischdecke", "Stehleuchte" and so on) and runs one test per word: search for the second half alone ("Kissen", "Tasse", "Decke", "Leuchte") and check that the compound product appears in the results. With plain PostgreSQL full text search and the German stemmer, 0 of the 20 pass. That single test, run before launch, tells him the German shop needs either a decompounding dictionary or a search engine that splits compounds, before a single German customer gets an empty results page.
Results that guide: filters and category redirects
The results page is a category page that the customer built with their query. It deserves the same tools: product cards that show what matters, sorting, and filters. The filters should come from the results, not from the whole shop: after searching "lamp", the useful filters are type of lamp, bulb fitting, colour and price, not fabric. The previous chapter covers filters and facets in depth.
Some queries are really category names. When someone types "table lamps" and you have a category called exactly that, sending them to the category page (or offering it prominently at the top of the results) gives them the curated page with its filters and descriptions instead of a raw list. Baymard reports that 46% of sites get this autodirect or category guidance wrong11.
Example: "table lamps" at Wrenfield
Today, "table lamps" at Wrenfield returns 41 results in the default order, including two lampshades and a bulb, because their descriptions mention table lamps. The category page "Table lamps" holds 33 lamps, with filters for height, fitting and finish. Callum adds a rule: when the normalised query exactly matches a category name or one of its listed synonyms, redirect to the category page and show a short line "Showing all table lamps". The customer gets 33 relevant products with the right filters instead of 41 mixed ones.
The zero result page is a page, not an apology
Some searches will always find nothing. What happens next decides whether the visitor leaves. Baymard found that around half of shops implement "no results" pages in ways that frustrate users, and that generic search tips alone rarely help12. Its research points to five better responses11:
- Suggest related categories.
- Suggest a simpler alternative query that does return results.
- Show recommendations based on what the visitor has already looked at.
- Offer contact options: phone, chat or a help link.
- Show popular products and categories.
Behind the scenes, the best zero result page is the one that never appears, because the search log fed the synonym list. And when you genuinely do not sell something, say so plainly and help with the next step.
Example: "bedding" at Wrenfield
Wrenfield does not sell bedding, and 150 people searched for it last month. The old page said "No results for bedding. Check your spelling." The new one says "I don't sell bedding, but these might be what you're after", with links to Cushions and throws and to Blankets, four popular throws, and the customer service email. Priya also notes the 150 searches for her range planning: free market research.
Ranking: relevance first, then what helps the shop
Once the engine has found matching products, it has to order them. The first rule never changes: the most relevant products come first. Text relevance comes from how many query words match, how close together they are, how many typos were needed, and which field matched (a match in the product name beats one in the description). Meilisearch, for example, applies its built in rules in this order by default: words, typo, proximity, attribute rank, sort, word position, exactness13.
Among products that are equally relevant, you can then let business signals decide. Common ones:
- Stock: products that can ship today before products that are out of stock.
- Popularity: recent sales or recent clicks from search.
- Margin: among close equals, the product that earns the shop more.
- Newness: new arrivals, for shops where that matters.
Keep business signals as tie breakers, never as the main order. A customer who searched "oak side table" and sees a high margin pine shelf first has learned that your search does not listen.
A simple, explainable way to combine popularity and margin is a weighted score, with each signal divided by the largest value among the results so both sit between 0 and 1. See Foundations: ratios and rates.
where is the business score of product , is its popularity (for example orders in the last 90 days), is its gross margin, and are the largest popularity and margin among the equally relevant results, and and are the weights you choose, adding up to 1.
Example: three linen cushions
A customer searches "linen cushion". Three products match equally well on text:
| Product | Orders, last 90 days | Gross margin | In stock |
|---|---|---|---|
| Sage linen cushion | 120 | 58% | 40 |
| Oat linen cushion | 45 | 61% | 0 |
| Navy linen cushion | 80 | 49% | 12 |
Priya chooses and , because she wants proven sellers first and margin second. The largest popularity is 120 and the largest margin is 61%.
Sage:
Oat:
Navy:
Stock comes before the score: the oat cushion cannot ship, so it goes last whatever its score. The final order is sage (0.980), navy (0.721), then oat (0.625, out of stock). If the oat cushion comes back into stock, its score of 0.625 still puts it after navy. Every step of that order can be explained to Priya in one sentence, which is the point: a ranking nobody can explain is a ranking nobody can fix.
The law on paid placement in search results
If a supplier ever pays you to put its products higher in your search results, that is advertising, and the law treats it that way. In the EU, the Omnibus Directive added to the list of practices that are always unfair "providing search results in response to a consumer's online search query without clearly disclosing any paid advertisement or payment specifically for achieving higher ranking"14. The UK's Digital Markets, Competition and Consumers Act 2024 has no item in its list of banned practices that names search ranking, but its general bans on misleading actions and misleading omissions apply to a paid placement dressed up as a neutral result, and Schedule 20 already bans paid editorial content that is not made clear15. Ranking your own products by your own margin is not a paid placement. A brand paying you for the top slot is, and it needs a clear label. This is general information, not legal advice. If paid placements are part of your plans, check them with a solicitor.
Measuring search: the five numbers that matter
You cannot improve search without measuring it, and the measurements are simple. Five numbers cover almost everything:
- Search usage rate: the share of sessions with at least one search.
- Zero result rate: the share of searches that returned nothing.
- Search exit rate: the share of searches after which the visitor left the shop without clicking anything.
- Search refinement rate: the share of searches followed straight away by another search, a sign the first one did not deliver.
- Search conversion rate: orders from sessions with a search, divided by sessions with a search.
The one to watch first is the zero result rate, because it is the easiest to fix and every fix is permanent. See Foundations: ratios and rates.
where is the zero result rate, is the number of searches that returned no results, and is the total number of searches in the same period.
The other rates follow the same pattern: the count of searches (or sessions) with the outcome, divided by the count of all searches (or sessions).
Example: Wrenfield's search month, before and after
In the month before the synonym list, Wrenfield's search log shows:
| Measure | Count |
|---|---|
| Sessions | 110,000 |
| Sessions with a search | 16,500 |
| Searches | 24,800 |
| Searches with zero results | 2,480 |
| Searches followed by an exit | 3,720 |
| Searches followed straight away by another search | 4,960 |
| Orders from sessions with a search | 726 |
The five numbers:
- Search usage rate:
- Zero result rate:
- Search exit rate:
- Search refinement rate:
- Search conversion rate:
Here are the ten most common queries that returned nothing that month:
Those ten queries account for of the 2,480 zero result searches, or 67%. That is typical of a search log: a short head of common problems and a long tail of one offs. Fixing the head is a day's work.
Seven of the ten are vocabulary or spelling problems that the synonym list fixes: settee, throw, tea towel, lamp shade, dinner set, eggcup and vace, together 1,270 searches. Two are non product queries ("gift card" and "returns", 250 searches) that need help pages added to the index. One ("bedding", 150) is a product the shop does not sell, which gets the better zero result page from the previous section.
Example: what fixing the head is worth
How much is that worth? A search session that hits a zero result converts far worse than one that finds something. Callum's log shows that sessions whose only search returned nothing converted at 0.9% last month, against 4.4% for all search sessions. Assume, cautiously, that fixing a zero result closes only half of that gap. See Foundations: expected value.
where is the expected number of extra orders a month, is the number of sessions that the fix affects, and is the expected rise in their conversion rate.
The fixes cover 1,270 vocabulary searches and 250 non product searches, 1,520 searches in all. Treat each as one session, which is slightly generous since some sessions search twice. Closing half the gap gives , or 0.0175, and so .
About 27 extra orders a month, which at an average order value of £72 is about £1,915 in revenue, and at the 52% gross margin about £996 in gross profit, before delivery and payment costs, every month, from nine synonym lines and two help pages. The non product searches will mostly not turn into orders, so the true figure is probably a little lower. It is still one of the best value changes a shop can make.
Four weeks later, the zero result rate has fallen from about 10% to under 6%:
Collecting search data: in your own database and in analytics
There are two places to record searches, and a shop should use both for different jobs.
Your own database is the complete record. Every search the shop answers can be logged on the server with the normalised query and the number of results, whether or not the visitor accepted analytics cookies, because you store no personal data with it: no customer ID, no IP address, just the words and the count. That table answers "what do people search for and what fails", and it is the source of the synonym list.
Analytics connects searches to the rest of the visit: which searches led to a product view, a basket, an order. GA4 can pick up site searches automatically through enhanced measurement, which records a view_search_results event when the page address contains a query parameter called q, s, search, query or keyword16. Solidus' default searcher reads its query from a parameter called keywords17, which is not on that list, so you either add keywords in the enhanced measurement settings or send the recommended search event yourself, with its required search_term parameter18.
Two cautions. Visitors sometimes type personal data, such as an email address or an order number with a name, into search boxes, and Google's policy is that no personally identifiable information may be sent to Analytics, so strip it before sending19. And front end analytics should only run once the visitor has agreed, which is how I run analytics on my own site. The UK rules on storing and reading cookies sit in regulation 6 of the Privacy and Electronic Communications Regulations (PECR)20. The tracking plan chapter covers event names and consent in full, and the server events chapter covers recording from the shop itself.
Example: Callum's search log
Callum adds a table and a few lines to the search controller. The migration:
class CreateSearchLogs < ActiveRecord::Migration[8.0]
def change
create_table :search_logs do |t|
t.string :query, null: false # normalised: lower case, trimmed
t.integer :results_count, null: false
t.string :locale, null: false
t.timestamps
end
add_index :search_logs, [:created_at, :results_count]
end
end
The model normalises the query and removes anything that looks like an email address before saving:
class SearchLog < ApplicationRecord
EMAIL = /\S+@\S+\.\S+/
def self.record(raw_query, results_count:, locale:)
query = raw_query.to_s.downcase.squish.gsub(EMAIL, "[email]").first(100)
return if query.blank?
create!(query:, results_count:, locale:)
end
end
And the monthly report of the most common zero result queries is one SQL statement:
SELECT query, COUNT(*) AS searches
FROM search_logs
WHERE results_count = 0
AND created_at >= now() - interval '30 days'
GROUP BY query
ORDER BY searches DESC
LIMIT 20;
In the browser, after consent, the results page sends the search to GA4 with the number of results as an extra parameter:
gtag('event', 'search', {
search_term: 'linen cushion',
results_count: 14
});
results_count is a custom parameter, so it only appears in reports once Callum registers it as a custom metric in GA421.
Choosing the engine: from your database to a search server
There is no single right engine. It depends on catalogue size, languages, how much tuning you want, and who runs it. Here are the realistic options, from simplest to heaviest.
| Option | What it is | Good at | Watch out for |
|---|---|---|---|
| Solidus default searcher | A LIKE match on product name and description17 | Nothing to install | No typo tolerance, no stemming, no ranking by relevance |
PostgreSQL full text search with pg_search | Stemming, weights and prefix matching inside your existing database, plus pg_trgm for typos622 | No extra server, data always in sync, fine for a few thousand products | Typo tolerance weak on short words, German compounds need an Ispell dictionary, ranking rules are yours to write |
| Meilisearch | A search server with typo tolerance, synonyms, filters and ranking rules built in, the community edition MIT licensed523 | Fast results as you type, good defaults, German compound support listed | A second system to run and keep in sync with the shop |
| Typesense | A similar typo tolerant search server, GPL 3.0 licensed24 | Similar strengths to Meilisearch | Same: another system to run and sync |
| OpenSearch or Elasticsearch | Full search platforms with detailed text analysis, including decompounders8925 | Large catalogues, many languages, fine control | Far more to configure and operate than a 1,400 product shop needs |
| Hosted search services | Any of the above, or a commercial service, run by a vendor | No servers to run | Monthly fees, and your queries and catalogue leave your systems, so check where the data is processed |
For a catalogue of about 1,400 products in one language, PostgreSQL full text search is usually enough, and it keeps everything in the database you already back up. Move to a search server when you need results as you type at scale, a second language with compounds, or ranking rules that are painful to express in SQL.
Example: choosing the engine for Wrenfield
Callum lists Wrenfield's needs: 1,400 products, English only today, German pages maybe next year, autocomplete on every keystroke, typo tolerance, synonyms that Priya can edit herself. He starts with PostgreSQL and pg_search, because it needs no new server and the synonym table and search log live in the same database. He writes down the trigger for moving to Meilisearch: the day the German shop goes live, since the compound test from earlier fails on plain PostgreSQL. Writing the trigger down now means the switch is a planned piece of work, not a panic.
Building it with PostgreSQL and pg_search
Here is how Callum builds the PostgreSQL version on Solidus. It has four parts: the database extensions, a search scope on the product model, the synonym rewrite, and a small service that puts them together with the ranking rules from earlier.
First, a migration enables the two PostgreSQL extensions and adds a trigram index on the product name, so that typo matching does not have to scan every row:
class EnableProductSearch < ActiveRecord::Migration[8.0]
def change
enable_extension "pg_trgm"
enable_extension "unaccent"
add_index :spree_products, :name,
using: :gin, opclass: :gin_trgm_ops,
name: "index_spree_products_on_name_trgm"
end
end
Second, the search scope. Solidus recommends changing core models through small override modules that are prepended to the model, kept in app/overrides and loaded at boot26. This one adds a pg_search scope to Spree::Product22:
# app/overrides/wrenfield/spree/product/searchable.rb
module Wrenfield
module Spree
module Product
module Searchable
def self.prepended(base)
base.include PgSearch::Model
base.pg_search_scope :shop_search,
against: { name: "A", meta_keywords: "B", description: "C" },
ignoring: :accents,
using: {
tsearch: { prefix: true, dictionary: "english" },
trigram: { only: [:name] }
}
end
::Spree::Product.prepend self
end
end
end
end
The letters A, B and C are weights: a match in the name counts most, then the keywords, then the description. prefix: true lets "lam" match "lamp" while someone is still typing. dictionary: "english" turns on stemming. The trigram part only looks at the short name field, because long descriptions dilute trigram similarity, a limitation the pg_search documentation itself points out22.
Third, the synonym rewrite. Priya edits synonyms in a simple admin table, and the search service replaces whole words before searching:
class SearchSynonym < ApplicationRecord
# term: what customers type, replacement: what the shop calls it
def self.rewrite(query)
map = pluck(:term, :replacement).to_h
query.split.map { |word| map.fetch(word, word) }.join(" ")
end
end
This simple version handles one word terms. Two word terms such as "dish towel" need a phrase match first, which is a few more lines and a good first test to write.
Fourth, the service that ties it together:
class ProductSearch
def initialize(raw_query, locale: "en-GB")
@typed = raw_query.to_s.downcase.squish
@query = SearchSynonym.rewrite(@typed)
@locale = locale
end
def call
return [] if @query.blank?
results = ::Spree::Product.available.shop_search(@query)
.with_pg_search_rank.limit(200).to_a
# Log what the customer typed, not the rewrite, so gaps stay visible
SearchLog.record(@typed, results_count: results.size, locale: @locale)
order(results)
end
private
# Relevance band first, then stock, then the business score
def order(products)
top = products.map(&:pg_search_rank).max.to_f
products.sort_by do |p|
band = top.zero? ? 0 : (p.pg_search_rank / top * 4).round
[-band, p.total_on_hand.positive? ? 0 : 1, -business_score(p)]
end
end
def business_score(product)
0 # popularity and margin, as in the worked example above
end
end
Spree::Product.available is Solidus' own scope for products that are on sale today and not discontinued, and total_on_hand adds up stock across a product's variants17. Dividing each rank by the best rank and rounding it into five bands keeps the business score as a tie breaker inside each band of equally relevant products, exactly as the ranking section recommends. The business score is left as a stub here, because it depends on where you keep popularity and margin, usually a nightly job that writes them onto each product. Sorting in Ruby is fine for 200 results; a larger shop would push the ordering into SQL.
Callum writes the tests before the code: "settee" finds the sofas, "cushons" finds the cushions, an out of stock product never beats an in stock one of the same band, and a typed email address is never stored. Each test guards a lesson from this chapter.
Building it with Meilisearch
When the German shop goes live, Callum moves search to Meilisearch. The shop stays the source of truth: products are written to Meilisearch from Solidus, and search results come back as product IDs that the shop then loads from its own database, so prices and stock shown to the customer are always the shop's own.
An indexing job builds one document per product and sends the settings:
class SearchIndexJob < ApplicationJob
queue_as :default
def perform
index = Meilisearch::Client.new(ENV.fetch("MEILISEARCH_URL"), ENV.fetch("MEILISEARCH_KEY")).index("products")
index.update_settings(
searchable_attributes: %w[name taxons meta_keywords description],
filterable_attributes: %w[taxons in_stock price],
sortable_attributes: %w[price],
ranking_rules: %w[words typo proximity attributeRank sort wordPosition exactness in_stock:desc popularity:desc],
synonyms: SearchSynonym.as_meilisearch_hash
)
::Spree::Product.available.includes(:taxons).find_in_batches(batch_size: 500) do |batch|
index.add_documents(batch.map { |p| document_for(p) }, "id")
end
end
private
def document_for(product)
{
id: product.id,
name: product.name,
description: product.description.to_s,
meta_keywords: product.meta_keywords.to_s,
taxons: product.taxons.map(&:name),
price: product.price.to_f,
in_stock: product.total_on_hand.positive? ? 1 : 0,
popularity: product.respond_to?(:orders_last_90_days) ? product.orders_last_90_days : 0
}
end
end
The meilisearch-ruby client creates the index on first use and converts Ruby's snake case settings to the names Meilisearch expects27. The ranking rules keep Meilisearch's default text relevance rules in their documented order and add two custom rules at the end, as Meilisearch recommends: in stock first, then popularity, only among results that text relevance cannot separate13. as_meilisearch_hash is a small method on the synonym table that returns each term with its list of equivalents. For 1,400 products a full reindex takes seconds, so Callum runs it hourly and after every stock import, which is simpler than catching every single change.
The results controller asks Meilisearch for IDs, then loads the products from Solidus in that order:
hits = index.search(params[:keywords].to_s, limit: 48, filter: ["in_stock = 1"])["hits"]
ids = hits.map { |hit| hit["id"] }
@products = ::Spree::Product.available.where(id: ids).in_order_of(:id, ids)
in_order_of is a Rails method that keeps the order from the search engine. Showing only in stock products here is Priya's choice for this page. Many shops show out of stock items at the end instead, with a "notify me" button. Because the shop loads the products itself, an indexing delay can never show a wrong price: at worst a product is briefly missing from search.
The generative AI and product discovery article covers the newer step beyond this: semantic search, where the engine matches meaning ("something warm for the sofa" finding throws) rather than words. Both Meilisearch and the larger engines now offer it as an addition to keyword search, and a shop that has done the groundwork in this chapter is ready to add it.
Running search as a monthly routine
Search is never finished, because your range, your customers' words and the seasons keep changing. A short routine with an owner works. Here is one that fits in an hour a month:
| Step | Time | What you do |
|---|---|---|
| 1 | 10 minutes | Pull the top 20 zero result queries from the search log |
| 2 | 20 minutes | Sort each one: synonym, spelling, non product, or not stocked |
| 3 | 15 minutes | Add synonyms and spelling entries, add help pages to the index |
| 4 | 10 minutes | Search the top 10 overall queries yourself on a phone and check the first row of results |
| 5 | 5 minutes | Note the five numbers and compare them with last month |
The not stocked list goes to whoever plans the range. Over a year, it becomes one of the clearest pictures you have of what customers wanted and could not buy from you.
Example: Priya's first three months
Priya runs the routine on the first Monday of each month. In month one she adds the nine synonym lines and two help pages, and the zero result rate falls from 10.0% to 5.8%. In month two the top failure is "christmas", because her seasonal range is not live yet, so she points it at the winter collection for now. In month three "bedding" is still in the top five, so she adds a few bedroom throws and points "bedding" at them. After the first set up, none of it needs a developer.
Conclusion
People who search convert better mostly because they arrive knowing what they want, so the job of site search is not to recruit more searchers but to stop failing the ones you have. Start with the search log: classify the queries, and fix the short head of failures with synonyms, spelling entries and help pages. Make the box visible, keep the query in it, and use autocomplete to suggest queries and categories. Accept that typo tolerance is weak on short words, that stemming handles plurals, and that German compounds need a tool built for them. Treat the zero result page as a page that helps. Rank by relevance first and use stock, popularity and margin only to break ties, and label anything a supplier paid for. Measure the five numbers every month. For a shop of Wrenfield's size, PostgreSQL with pg_search is a sound start, and a search server like Meilisearch is the planned next step when languages or scale demand it.