Building a Hybrid Semantic Product Search Engine
Keyword search works well when you know a product's name or model number. It's less helpful when all you know is that you need comfortable headphones for long flights.
I wanted to see if combining keyword search with semantic search would give better results, without ignoring things like budget or required features. So I built a small product search engine.
Search and ranking
You can search in three different ways:
- Keyword search: Uses PostgreSQL full-text search to match words, product names and model numbers.
- Semantic search: Uses OpenAI embeddings and pgvector to find products that match the meaning of your query, even when the descriptions use different words.
- Hybrid search: Combines the two sets of results using Reciprocal Rank Fusion (RRF), which looks at the position of each result rather than its raw score.
I apply filters for price, brand, category and features in SQL before ranking the results. Products that don't meet those requirements are excluded.
Architecture
I built the frontend in Svelte and hosted it on Cloudflare Pages. A Cloudflare Worker handles search requests, queries Neon PostgreSQL with pgvector, and uses OpenAI's text-embedding-3-small model to generate embeddings.
How well does it work?
I compared the three search methods using a catalog of 200 products and 25 test queries that I hadn't used to tune the search. Each query had at least one relevant product.
I measured Hit@5: the percentage of searches that showed at least one relevant product in the first five results.
| Search method | Hit@5 |
|---|---|
| Keyword | 40% |
| Semantic | 92% |
| Hybrid | 96% |
I also checked that the filters worked correctly. Across the wider set of tests, all 1,234 returned products matched the filters applied to their searches.
The test set was small, and I used AI to judge which products were relevant rather than asking independent reviewers. Keep that in mind when looking at the results.
What I learned
- Embeddings work well alongside keyword search. Exact product names and model numbers still matter.
- Apply requirements like a maximum price in SQL. A high similarity score doesn't make a product affordable.
- Vector search can return the closest matches even when nothing in the catalog fits. There needs to be a way to return no results.