Build a full-text search API with filtering, sorting, and relevance scoring
Create a powerful search API that enables full-text search across your data with HARD features like filtering, faceting, fuzzy matching, and relevance scoring.
To get started, you can use the following code snippet for basic search:
function search(query, documents) {
const terms = query.toLowerCase().split(/\s+/);
return documents
.map(doc => ({
...doc,
score: calculateRelevance(doc, terms)
}))
.filter(doc => doc.score > 0)
.sort((a, b) => b.score - a.score);
}
function calculateRelevance(doc, terms) {
let score = 0;
const text = `${doc.title} ${doc.content}`.toLowerCase();
terms.forEach(term => {
const matches = (text.match(new RegExp(term, 'g')) || []).length;
score += matches;
});
return score;
}