Prompt
How do I search similar products using embeddings?
Latest observation
To search for similar products using embeddings, you generally do this:
1) Turn each product into a vector
Create an embedding for each product using a model that converts text or multimodal content into a numeric vector.
Typical product text to embed:
- title
- description
- category
- brand
- key attributes
- maybe reviews or tags
Example input:
Nike Air Zoom Pegasus 40 running shoes, men's, breathable mesh, size 10
The embedding model outputs a vector like:
[0.12, -0.04, 0.88, ...]
Products with similar meaning get vectors that are close together.
2) Store embeddings in a vector index
Save each product’s embedding in a vector database or search index, such as:
- FAISS
- Pinecone
- Weaviate
- Milvus
- Elasticsearch / OpenSearch with vector search
- PostgreSQL with pgvector
You also store metadata:
- product_id
- title
- price
- category
- availability
3) Embed the query product or search text
When a user searches:
- embed the query text, or
- embed a “source product” if doing “similar items” recommendations
Example:
"lightweight running shoes for men"
Convert that into a vector using the same embedding model.
4) Find nearest vectors
Search the index for the top-k closest product vectors using a similarity metric like:
- cosine similarity
- dot product
- Euclidean distance
The nearest vectors are your most similar products.
5) Filter and rerank if needed
Usually you’ll want business filters first:
- same category
- in stock
- price range
- region
Then rerank results with:
- additional text similarity
- boosted attributes
- popularity
- personalization
- a cross-encoder / LLM reranker for better precision
Simple workflow
- Embed all products offline.
- Store embeddings in a vector DB.
- Embed the search query at runtime.
- Retrieve nearest neighbors.
- Apply filters and rerank.
- Return results.
Example with cosine similarity
If you already have embeddings:
import numpy as np
def cosine_similarity(a, b):
return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))
query_emb = ...
product_embs = ...
scores = [cosine_similarity(query_emb, p) for p in product_embs]
top_indices = np.argsort(scores)[::-1][:10]
Tips for better product search
- Use rich product text, not just titles.
- Normalize product data before embedding.
- Combine embeddings with structured filters.
- Consider separate embeddings for:
- title
- description
- image
- If products are visual, use multimodal embeddings.
- Re-embed when product details change.
- Cache embeddings for performance.
If you want “similar products to this item”
A common pattern is:
- User views product A
- Embed product A
- Retrieve nearest neighbors excluding itself
- Filter by category/availability
- Show top similar items
If you want, I can also show:
- a full Python example with FAISS or pgvector, or
- how to do this in OpenSearch/Pinecone.