41.1 Hybrid search (keyword + vector)

Overview and links for this section of the guide.

The Problem

Vector search finds semantically similar content but misses exact matches. Keyword search finds exact terms but misses synonyms. Hybrid combines both.

Implementation

// hybrid-search.ts
async function hybridSearch(query: string, limit = 10) {
  // Parallel search with both methods
  const [vectorResults, keywordResults] = await Promise.all([
    vectorSearch(query, limit * 2),
    keywordSearch(query, limit * 2)
  ]);
  
  // Reciprocal Rank Fusion
  const scores = new Map();
  const k = 60; // Tuning parameter
  
  vectorResults.forEach((doc, rank) => {
    const score = 1 / (k + rank);
    scores.set(doc.id, (scores.get(doc.id) || 0) + score);
  });
  
  keywordResults.forEach((doc, rank) => {
    const score = 1 / (k + rank);
    scores.set(doc.id, (scores.get(doc.id) || 0) + score);
  });
  
  // Sort by combined score
  return [...scores.entries()]
    .sort((a, b) => b[1] - a[1])
    .slice(0, limit)
    .map(([id]) => getDocument(id));
}

Where to go next