Ecommerce Reranker API: Boost Product Search Relevance
Product search is the front door of every ecommerce platform. A customer types "red dress" and expects to see dresses — not red pants, red paint, or red phone cases. Traditional keyword matching (BM25, TF-IDF) gets you partway there, but it breaks down on synonyms, paraphrases, and intent mismatches. A reranker sits on top of your initial retrieval and reorders results by semantic relevance, dramatically improving the quality of your top-K results without replacing your existing search infrastructure.
Why Reranking Matters for Ecommerce
Ecommerce search has unique challenges that general-purpose rerankers don't handle well:
- Attribute matching — "wireless bluetooth headphones with ANC" should rank products with Active Noise Cancellation higher, even if the listing says "noise cancelling" instead of "ANC".
- Category disambiguation — "apple" should rank electronics when the user's context suggests tech, not fruit.
- Cross-lingual product titles — Many marketplaces have product titles mixing English brand names with local-language descriptions.
- Long-tail queries — Specific queries like "size 10 waterproof hiking boots for wide feet" need deep semantic understanding to match against product attributes scattered across title, bullets, and description.
Our reranker is fine-tuned on ecommerce product data, so it understands product attributes, brand names, and shopping intent out of the box.
API Design
The API accepts a batch of search queries, each with its own list of product documents, then returns documents ranked by relevance for each query.
Endpoint: POST https://api.apiclaw.io/openapi/v2/model/ecommerce-rerank
Credits: 1 credit per query in the batch. A request with 3 queries and 50 documents costs 3 credits.
Limits:
- Max 10 queries per request
- Max 100 documents per query
- Max 1,000 characters per query
- Max 10,000 characters per document
Request
{
"queries": ["red dress", "summer shoes"],
"documents": [
[
"Red cotton summer dress with floral print",
"Blue denim jeans slim fit",
"Women elegant red evening gown"
],
[
"Nike Air Zoom Pegasus 40 running shoes",
"Leather sandals summer collection",
"Blue denim jeans slim fit"
]
],
"topK": 2
}
Response
{
"success": true,
"data": {
"results": [
[
{ "index": 2, "relevanceScore": 0.9341, "document": "Women elegant red evening gown" },
{
"index": 0,
"relevanceScore": 0.8756,
"document": "Red cotton summer dress with floral print"
}
],
[
{ "index": 1, "relevanceScore": 0.8912, "document": "Leather sandals summer collection" },
{
"index": 0,
"relevanceScore": 0.7234,
"document": "Nike Air Zoom Pegasus 40 running shoes"
}
]
],
"modelName": "qwen3_reranker:Qwen/Qwen3-Reranker-0.6B (reranker_v02)"
},
"meta": {
"requestId": "req_8a3f2b1c4d567890",
"timestamp": "2026-04-17T10:30:00.000000Z",
"creditsRemaining": 997,
"creditsConsumed": 2
}
}
Response Fields:
results— Nested array:results[i]contains ranked documents forqueries[i], sorted byrelevanceScoredescendingresults[i][j].index— Original index of the document indocuments[i]results[i][j].relevanceScore— Normalized relevance score between 0 and 1results[i][j].document— The document textmodelName— Name and version of the reranker model
Code Recipes
Recipe 1: Basic Reranking (curl)
# Rerank products for a single query
curl -s -X POST https://api.apiclaw.io/openapi/v2/model/ecommerce-rerank \
-H "Authorization: Bearer hms_live_YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"queries": ["wireless bluetooth headphones"],
"documents": [
[
"Sony WH-1000XM5 wireless noise cancelling headphones",
"USB-C charging cable 6ft braided",
"Bose QuietComfort Ultra wireless earbuds",
"Laptop stand adjustable aluminum"
]
],
"topK": 2
}'
# => results[0] = [{index: 0, relevanceScore: 0.95, ...}, {index: 2, relevanceScore: 0.88, ...}]
Recipe 2: Python — Rerank After Keyword Search
import httpx
APICLAW_URL = "https://api.apiclaw.io/openapi/v2/model/ecommerce-rerank"
APICLAW_KEY = "hms_live_YOUR_API_KEY"
def rerank_search_results(query: str, product_titles: list[str], top_k: int = 10) -> list[dict]:
"""Rerank product titles by semantic relevance to the search query."""
resp = httpx.post(
APICLAW_URL,
headers={"Authorization": f"Bearer {APICLAW_KEY}"},
json={
"queries": [query],
"documents": [product_titles],
"topK": top_k,
},
timeout=30.0,
)
result = resp.json()
if not result["success"]:
raise RuntimeError(f"Reranking failed: {result['error']}")
return result["data"]["results"][0]
# Example: keyword search returns 20 products, rerank to get top 5
keyword_results = [
"Red cotton summer dress with floral print",
"Red LED desk lamp adjustable",
"Women elegant red evening gown",
"Red phone case iPhone 15",
"Casual red midi dress v-neck",
]
top_5 = rerank_search_results("red dress", keyword_results, top_k=3)
for item in top_5:
print(f" [{item['relevanceScore']:.3f}] {item['document']}")
# => [0.934] Women elegant red evening gown
# => [0.876] Red cotton summer dress with floral print
# => [0.812] Casual red midi dress v-neck
Recipe 3: Python — Multi-Query Batch for A/B Testing
import httpx
APICLAW_URL = "https://api.apiclaw.io/openapi/v2/model/ecommerce-rerank"
APICLAW_KEY = "hms_live_YOUR_API_KEY"
def compare_query_variants(
query_variants: list[str], product_catalog: list[str]
) -> dict[str, list[dict]]:
"""Compare how different query phrasings rank the same products."""
resp = httpx.post(
APICLAW_URL,
headers={"Authorization": f"Bearer {APICLAW_KEY}"},
json={
"queries": query_variants,
"documents": [product_catalog] * len(query_variants),
},
timeout=30.0,
)
data = resp.json()["data"]
return {
query: results
for query, results in zip(query_variants, data["results"])
}
# Compare how "sneakers" vs "running shoes" rank the same catalog
results = compare_query_variants(
["sneakers", "running shoes"],
[
"Nike Air Max 90 casual sneakers",
"Adidas Ultraboost Light running shoes",
"Converse Chuck Taylor All Star",
"ASICS Gel-Kayano 30 stability running shoe",
],
)
for query, ranked in results.items():
print(f"\n'{query}' top pick: {ranked[0]['document']} ({ranked[0]['relevanceScore']:.3f})")
Recipe 4: TypeScript — Next.js Search Enhancement
const APICLAW_URL = "https://api.apiclaw.io/openapi/v2/model/ecommerce-rerank";
const APICLAW_KEY = process.env.APICLAW_API_KEY!;
interface RankedDocument {
index: number;
relevanceScore: number;
document: string;
}
interface RerankResponse {
success: boolean;
data: {
results: RankedDocument[][];
modelName: string;
};
}
async function rerankProducts(
query: string,
productTitles: string[],
topK?: number,
): Promise<RankedDocument[]> {
const res = await fetch(APICLAW_URL, {
method: "POST",
headers: {
Authorization: `Bearer ${APICLAW_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
queries: [query],
documents: [productTitles],
topK,
}),
});
const data: RerankResponse = await res.json();
if (!data.success) throw new Error("Reranking failed");
return data.data.results[0];
}
// Usage in a search API route
export async function GET(req: NextRequest) {
const query = req.nextUrl.searchParams.get("q") ?? "";
const keywordResults = await searchByKeyword(query); // your existing search
const titles = keywordResults.map((p) => p.title);
const ranked = await rerankProducts(query, titles, 20);
const reorderedProducts = ranked.map((r) => keywordResults[r.index]);
return NextResponse.json({ products: reorderedProducts });
}
Model Details
The reranker is powered by Qwen3-Reranker-0.6B, a 0.6B-parameter cross-encoder model fine-tuned for ecommerce product matching. Key characteristics:
- Cross-encoder architecture — Jointly encodes query and document for deeper semantic matching than bi-encoder retrieval
- Ecommerce-optimized — Fine-tuned on product titles, descriptions, and search queries across multiple categories
- Normalized scores — Output scores are normalized to [0, 1] for easy thresholding and comparison
- Batch-efficient — Process multiple queries, each with its own document set, in a single request
When to Use Reranking
| Scenario | Benefit |
|---|---|
| After keyword search (BM25/Elasticsearch) | Promotes semantically relevant results that keyword matching missed |
| Product recommendation | Rerank candidate products by relevance to user's current search context |
| Catalog deduplication | Score product pairs to find semantic duplicates |
| Search quality evaluation | Compare ranking quality across different query phrasings |
References
- Qwen Team. "Qwen3-Reranker". Hugging Face, 2025.
- Nogueira, R. & Cho, K. "Passage Re-ranking with BERT". arXiv:1901.04085, 2019.
- Gao, L., Ma, X., Lin, J. & Callan, J. "Precise Zero-Shot Dense Retrieval without Relevance Labels". arXiv:2212.10496, 2022.
Ready to build with APIClaw?