SimSwitcherQuery extends Query { @Override public Weight createWeight(IndexSearcher searcher, boolean needsScores, float boost) throws IOException { if (!needsScores) { return searcher.createWeight(subQuery, false, boost); } final Similarity oldSim = searcher.getSimilarity(true); try { searcher.setSimilarity(similarity); return searcher.createWeight(subQuery, true, boost); } finally { searcher.setSimilarity(oldSim); } } SimSwitcherQuery(Similarity similarity, Query subQuery); @Override String toString(String field); @Override @SuppressFBWarnings(value = "BC_EQUALS_METHOD_SHOULD_WORK_FOR_ALL_OBJECTS", justification = "handled by sameClassAs") boolean equals(Object obj); @Override int hashCode(); @Override Weight createWeight(IndexSearcher searcher, boolean needsScores, float boost); Similarity getSimilarity(); Query getSubQuery();  }
@Test public void testExplain() throws IOException { String q = "brown cow"; for (Map.Entry<String, Similarity> entry : similarityMap.entrySet()) { String msg = "switch from " + similarity.getClass().getSimpleName() + " to " + entry.getKey(); Query query = new QueryBuilder(analyzer).createBooleanQuery(entry.getKey(), q); Query hacked = new SimSwitcherQuery(entry.getValue(), new QueryBuilder(analyzer).createBooleanQuery("main_field", q)); TopDocs docs = searcherUnderTest.search(query, 10); Weight weight = searcherUnderTest.createWeight(searcherUnderTest.rewrite(query), true, 1F); Weight hackedWeight = searcherUnderTest.createWeight(searcherUnderTest.rewrite(hacked), true, 1F); Explanation exp = searcherUnderTest.explain(query, docs.scoreDocs[0].doc); Explanation hackExp = searcherUnderTest.explain(hacked, docs.scoreDocs[0].doc); assertEquals(msg, exp.getValue(), hackExp.getValue(), Math.ulp(exp.getValue())); } }