Term enumerations are always ordered by Term.compareTo(). Each term in the enumeration is greater than all that precede it. */ public final class SubstringTermEnum extends FilteredTermEnum { int del_len; boolean endEnum = false; Term searchTerm = null; String field = ""; String text = ""; int textlen; public SubstringTermEnum(IndexReader reader, Term term) throws IOException { super(reader, term); searchTerm = term; field = searchTerm.field(); text = searchTerm.text(); textlen = text.length(); setEnum(reader.terms(new Term(searchTerm.field(), ""))); } /** The termCompare method in SubstringTermEnum uses the difference in lengths to calculate the distance between the given term and the comparing term assuming that the term passed to the ctr is a substring of the current term. */ protected final boolean termCompare(Term term) { if (field == term.field()) { String target = term.text(); boolean res = target.indexOf( text) >= 0; del_len = Math.abs( text.length() - target.length()); return res; } endEnum = true; return false; } protected final float difference() { // if lengths differ by more than 10 then clamp the difference at 0.05 // if it's an exact match then we return 1.0 here return (float) Math.max( ((10 - del_len)/10.0f), 0.05); } public final boolean endEnum() { return endEnum; } public void close() throws IOException { super.close(); searchTerm = null; field = null; text = null; } }