Web / Apache Lucene Interview questions
How do you implement custom scoring using Lucene's Similarity API?
When BM25's general-purpose relevance model doesn't capture business-specific ranking needs - like factoring in a product's popularity alongside text relevance - Lucene lets you plug in a custom Similarity implementation, typically by extending SimilarityBase or wrapping the default with a PerFieldSimilarityWrapper.
public class BoostedSimilarity extends SimilarityBase { @Override protected double score(BasicStats stats, double freq, double docLen) { double base = super.score(stats, freq, docLen); return base * 1.0; // combine with an external boost signal here } }
A more common production pattern avoids overriding the low-level formula entirely and instead applies business signals at the query level - wrapping a text query in a FunctionScoreQuery or multiplying in a boost derived from a DocValues field (like a popularity score), which keeps standard BM25 relevance intact while layering in a secondary ranking signal.
Custom Similarity is powerful but easy to misuse: changes to the core scoring formula affect every query using that field, so most teams reach for query-level boosting first and only touch Similarity itself when a genuinely different mathematical model of relevance is required.
More Related questions...