Apache Solr open-source search software
New GradientFormatter, TermVector helper class and IDF-based fragment scoring
Mark Harwoodc5b61e167170
diff --git a/sandbox/contributions/highlighter/src/java/org/apache/lucene/search/highlight/GradientFormatter.java b/sandbox/contributions/highlighter/src/java/org/apache/lucene/search/highlight/GradientFormatter.javanew file mode 100644index 00000000000..775e5c62747--- /dev/null+++ b/sandbox/contributions/highlighter/src/java/org/apache/lucene/search/highlight/GradientFormatter.java@@ -0,0 +1,226 @@+package org.apache.lucene.search.highlight;+/**+ * Copyright 2002-2004 The Apache Software Foundation+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++/**+ * Formats text with different color intensity depending on the score of the+ * term.+ *+ * @author maharwood+ */+public class GradientFormatter implements Formatter+{+ private int maxScore;++ int fgRMin, fgGMin, fgBMin;++ int fgRMax, fgGMax, fgBMax;++ boolean highlightForeground;++ int bgRMin, bgGMin, bgBMin;++ int bgRMax, bgGMax, bgBMax;++ boolean highlightBackground;++ /**+ * Sets the color range for the IDF scores+ *+ * @param maxScore+ * The score (and above) displayed as maxColor+ * @param minForegroundColor+ * The hex color used for representing IDF scores of zero eg+ * #FFFFFF (white) or null if no foreground color required+ * @param maxForegroundColor+ * The largest hex color used for representing IDF scores eg+ * #000000 (black) or null if no foreground color required+ * @param minBackgroundColor+ * The hex color used for representing IDF scores of zero eg+ * #FFFFFF (white) or null if no background color required+ * @param maxBackgroundColor+ * The largest hex color used for representing IDF scores eg+ * #000000 (black) or null if no background color required+ */+ public GradientFormatter(int maxScore, String minForegroundColor,+ String maxForegroundColor, String minBackgroundColor,+ String maxBackgroundColor)+ {+ highlightForeground = (minForegroundColor != null)+ && (maxForegroundColor != null);+ if (highlightForeground)+ {+ if (minForegroundColor.length() != 7)+ {+ throw new IllegalArgumentException(+ "minForegroundColor is not 7 bytes long eg a hex "+ + "RGB value such as #FFFFFF");+ }+ if (maxForegroundColor.length() != 7)+ {+ throw new IllegalArgumentException(+ "minForegroundColor is not 7 bytes long eg a hex "+ + "RGB value such as #FFFFFF");+ }+ fgRMin = hexToInt(minForegroundColor.substring(1, 3));+ fgGMin = hexToInt(minForegroundColor.substring(3, 5));+ fgBMin = hexToInt(minForegroundColor.substring(5, 7));++ fgRMax = hexToInt(maxForegroundColor.substring(1, 3));+ fgGMax = hexToInt(maxForegroundColor.substring(3, 5));+ fgBMax = hexToInt(maxForegroundColor.substring(5, 7));+ }++ highlightBackground = (minBackgroundColor != null)+ && (maxBackgroundColor != null);+ if (highlightBackground)+ {+ if (minBackgroundColor.length() != 7)+ {+ throw new IllegalArgumentException(+ "minBackgroundColor is not 7 bytes long eg a hex "+ + "RGB value such as #FFFFFF");+ }+ if (maxBackgroundColor.length() != 7)+ {+ throw new IllegalArgumentException(+ "minBackgroundColor is not 7 bytes long eg a hex "+ + "RGB value such as #FFFFFF");+ }+ bgRMin = hexToInt(minBackgroundColor.substring(1, 3));+ bgGMin = hexToInt(minBackgroundColor.substring(3, 5));+ bgBMin = hexToInt(minBackgroundColor.substring(5, 7));++ bgRMax = hexToInt(maxBackgroundColor.substring(1, 3));+ bgGMax = hexToInt(maxBackgroundColor.substring(3, 5));+ bgBMax = hexToInt(maxBackgroundColor.substring(5, 7));+ }+ // this.corpusReader = corpusReader;+ this.maxScore = maxScore;+ // totalNumDocs = corpusReader.numDocs();+ }++ public String highlightTerm(String originalText, TokenGroup tokenGroup)+ {+ if (tokenGroup.getTotalScore() == 0)+ return originalText;+ float score = tokenGroup.getTotalScore();+ if (score == 0)+ {+ return originalText;+ }+ StringBuffer sb = new StringBuffer();+ sb.append("<font ");+ if (highlightForeground)+ {+ sb.append("color=\"");+ sb.append(getForegroundColorString(score));+ sb.append("\" ");+ }+ if (highlightBackground)+ {+ sb.append("bgcolor=\"");+ sb.append(getBackgroundColorString(score));+ sb.append("\" ");+ }+ sb.append(">");+ sb.append(originalText);+ sb.append("</font>");+ return sb.toString();+ }++ private String getForegroundColorString(float score)+ {+ int rVal = getColorVal(fgRMin, fgRMax, score);+ int gVal = getColorVal(fgGMin, fgGMax, score);+ int bVal = getColorVal(fgBMin, fgBMax, score);+ StringBuffer sb = new StringBuffer();+ sb.append("#");+ sb.append(intToHex(rVal));+ sb.append(intToHex(gVal));+ sb.append(intToHex(bVal));+ return sb.toString();+ }++ private String getBackgroundColorString(float score)+ {+ int rVal = getColorVal(bgRMin, bgRMax, score);+ int gVal = getColorVal(bgGMin, bgGMax, score);+ int bVal = getColorVal(bgBMin, bgBMax, score);+ StringBuffer sb = new StringBuffer();+ sb.append("#");+ sb.append(intToHex(rVal));+ sb.append(intToHex(gVal));+ sb.append(intToHex(bVal));+ return sb.toString();+ }++ private int getColorVal(int colorMin, int colorMax, float score)+ {+ if (colorMin == colorMax)+ {+ return colorMin;+ }+ float scale = Math.abs(colorMin - colorMax);+ float relScorePercent = Math.min(maxScore, score) / maxScore;+ float colScore = scale * relScorePercent;+ return Math.min(colorMin, colorMax) + (int) colScore;+ }++ private static char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',+ '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };++ private static String intToHex(int i)+ {+ return "" + hexDigits[(i & 0xF0) >> 4] + hexDigits[i & 0x0F];+ }++ /**+ * Converts a hex string into an int. Integer.parseInt(hex, 16) assumes the+ * input is nonnegative unless there is a preceding minus sign. This method+ * reads the input as twos complement instead, so if the input is 8 bytes+ * long, it will correctly restore a negative int produced by+ * Integer.toHexString() but not neccesarily one produced by+ * Integer.toString(x,16) since that method will produce a string like '-FF'+ * for negative integer values.+ *+ * @param hex+ * A string in capital or lower case hex, of no more then 16+ * characters.+ * @throws NumberFormatException+ * if the string is more than 16 characters long, or if any+ * character is not in the set [0-9a-fA-f]+ */+ public static final int hexToInt(String hex)+ {+ int len = hex.length();+ if (len > 16)+ throw new NumberFormatException();++ int l = 0;+ for (int i = 0; i < len; i++)+ {+ l <<= 4;+ int c = Character.digit(hex.charAt(i), 16);+ if (c < 0)+ throw new NumberFormatException();+ l |= c;+ }+ return l;+ }++}+diff --git a/sandbox/contributions/highlighter/src/java/org/apache/lucene/search/highlight/QueryScorer.java b/sandbox/contributions/highlighter/src/java/org/apache/lucene/search/highlight/QueryScorer.javaindex 1e85717b737..b425ad42572 100644--- a/sandbox/contributions/highlighter/src/java/org/apache/lucene/search/highlight/QueryScorer.java+++ b/sandbox/contributions/highlighter/src/java/org/apache/lucene/search/highlight/QueryScorer.java@@ -19,6 +19,7 @@ import java.util.HashMap;import java.util.HashSet;import org.apache.lucene.analysis.Token;+import org.apache.lucene.index.IndexReader;import org.apache.lucene.search.Query;/**@@ -27,7 +28,6 @@ import org.apache.lucene.search.Query;* their boosts to be used.* @author [email protected]*/-//TODO: provide option to roll idf into the scoring equation by passing a IndexReader.//TODO: provide option to boost score of fragments near beginning of document// based on fragment.getFragNum()public class QueryScorer implements Scorer@@ -48,6 +48,18 @@ public class QueryScorer implements Scorerthis(QueryTermExtractor.getTerms(query));}+ /**+ *+ * @param query a Lucene query (ideally rewritten using query.rewrite+ * before being passed to this class and the searcher)+ * @param reader used to compute IDF which can be used to a) score selected fragments better+ * b) use graded highlights eg set font color intensity+ * @param fieldName the field on which Inverse Document Frequency (IDF) calculations are based+ */+ public QueryScorer(Query query, IndexReader reader, String fieldName)+ {+ this(QueryTermExtractor.getIdfWeightedTerms(query, reader, fieldName));+ }public QueryScorer(WeightedTerm []weightedTerms ){@@ -83,7 +95,7 @@ public class QueryScorer implements Scorer//not a query term - returnreturn 0;}- //found a query term - is it unique in this fragment?+ //found a query term - is it unique in this doc?if(!uniqueTermsInFragment.contains(termText)){totalScore+=queryTerm.getWeight();diff --git a/sandbox/contributions/highlighter/src/java/org/apache/lucene/search/highlight/QueryTermExtractor.java b/sandbox/contributions/highlighter/src/java/org/apache/lucene/search/highlight/QueryTermExtractor.javaindex 55bf4b476cd..d0e186e809c 100644--- a/sandbox/contributions/highlighter/src/java/org/apache/lucene/search/highlight/QueryTermExtractor.java+++ b/sandbox/contributions/highlighter/src/java/org/apache/lucene/search/highlight/QueryTermExtractor.java@@ -15,8 +15,10 @@ package org.apache.lucene.search.highlight;* limitations under the License.*/+import java.io.IOException;import java.util.HashSet;+import org.apache.lucene.index.IndexReader;import org.apache.lucene.index.Term;import org.apache.lucene.search.BooleanClause;import org.apache.lucene.search.BooleanQuery;@@ -45,6 +47,35 @@ public final class QueryTermExtractorreturn getTerms(query,false);}+ /**+ * Extracts all terms texts of a given Query into an array of WeightedTerms+ *+ * @param query Query to extract term texts from+ * @param reader used to compute IDF which can be used to a) score selected fragments better+ * b) use graded highlights eg chaning intensity of font color+ * @param fieldName the field on which Inverse Document Frequency (IDF) calculations are based+ * @return an array of the terms used in a query, plus their weights.+ */+ public static final WeightedTerm[] getIdfWeightedTerms(Query query, IndexReader reader, String fieldName)+ {+ WeightedTerm[] terms=getTerms(query,false);+ int totalNumDocs=reader.numDocs();+ for (int i = 0; i < terms.length; i++)+ {+ try+ {+ int docFreq=reader.docFreq(new Term(fieldName,terms[i].term));+ //IDF algorithm taken from DefaultSimilarity class+ float idf=(float)(Math.log((float)totalNumDocs/(double)(docFreq+1)) + 1.0);+ terms[i].weight*=idf;+ }+ catch (IOException e)+ {+ //ignore+ }+ }+ return terms;+ }/*** Extracts all terms texts of a given Query into an array of WeightedTermsdiff --git a/sandbox/contributions/highlighter/src/java/org/apache/lucene/search/highlight/TokenSources.java b/sandbox/contributions/highlighter/src/java/org/apache/lucene/search/highlight/TokenSources.javanew file mode 100644index 00000000000..69b0bfcd15f--- /dev/null+++ b/sandbox/contributions/highlighter/src/java/org/apache/lucene/search/highlight/TokenSources.java@@ -0,0 +1,216 @@+/*+ * Created on 28-Oct-2004+ */+package org.apache.lucene.search.highlight;++import java.io.IOException;+import java.io.StringReader;+import java.util.ArrayList;+import java.util.Arrays;+import java.util.Comparator;++import org.apache.lucene.analysis.Analyzer;+import org.apache.lucene.analysis.Token;+import org.apache.lucene.analysis.TokenStream;+import org.apache.lucene.document.Document;+import org.apache.lucene.index.IndexReader;+import org.apache.lucene.index.TermFreqVector;+import org.apache.lucene.index.TermPositionVector;+import org.apache.lucene.index.TermVectorOffsetInfo;++/**+ * Hides implementation issues associated with obtaining a TokenStream for use with+ * the higlighter - can obtain from TermFreqVectors with offsets and (optionally) positions or+ * from Analyzer class reparsing the stored content.+ * @author maharwood+ */+public class TokenSources+{+ /**+ * A convenience method that tries a number of approaches to getting a token stream.+ * The cost of finding there are no termVectors in the index is minimal (1000 invocations still+ * registers 0 ms). So this "lazy" (flexible?) approach to coding is probably acceptable+ * @param reader+ * @param docId+ * @param field+ * @param analyzer+ * @return null if field not stored correctly+ * @throws IOException+ */+ public static TokenStream getAnyTokenStream(IndexReader reader,int docId, String field,Analyzer analyzer) throws IOException+ {+ TokenStream ts=null;++ TermFreqVector tfv=(TermFreqVector) reader.getTermFreqVector(docId,field);+ if(tfv!=null)+ {+ if(tfv instanceof TermPositionVector)+ {+ ts=getTokenStream((TermPositionVector) tfv);+ }+ }+ //No token info stored so fall back to analyzing raw content+ if(ts==null)+ {+ ts=getTokenStream(reader,docId,field,analyzer);+ }+ return ts;+ }+++ public static TokenStream getTokenStream(TermPositionVector tpv)+ {+ //assumes the worst and makes no assumptions about token position sequences.+ return getTokenStream(tpv,false);+ }+ /**+ * Low level api.+ * Returns a token stream or null if no offset info available in index.+ * This can be used to feed the highlighter with a pre-parsed token stream+ *+ * In my tests the speeds to recreate 1000 token streams using this method are:+ * - with TermVector offset only data stored - 420 milliseconds+ * - with TermVector offset AND position data stored - 271 milliseconds+ * (nb timings for TermVector with position data are based on a tokenizer with contiguous+ * positions - no overlaps or gaps)+ * The cost of not using TermPositionVector to store+ * pre-parsed content and using an analyzer to re-parse the original content:+ * - reanalyzing the original content - 980 milliseconds+ *+ * The re-analyze timings will typically vary depending on -+ * 1) The complexity of the analyzer code (timings above were using a+ * stemmer/lowercaser/stopword combo)+ * 2) The number of other fields (Lucene reads ALL fields off the disk+ * when accessing just one document field - can cost dear!)+ * 3) Use of compression on field storage - could be faster cos of compression (less disk IO)+ * or slower (more CPU burn) depending on the content.+ *+ * @param tpv+ * @param tokenPositionsGuaranteedContiguous true if the token position numbers have no overlaps or gaps. If looking+ * to eek out the last drops of performance, set to true. If in doubt, set to false.+ */+ public static TokenStream getTokenStream(TermPositionVector tpv, boolean tokenPositionsGuaranteedContiguous)+ {+ //an object used to iterate across an array of tokens+ class StoredTokenStream extends TokenStream+ {+ Token tokens[];+ int currentToken=0;+ StoredTokenStream(Token tokens[])+ {+ this.tokens=tokens;+ }+ public Token next() throws IOException+ {+ if(currentToken>=tokens.length)+ {+ return null;+ }+ return tokens[currentToken++];+ }+ }+ //code to reconstruct the original sequence of Tokens+ String[] terms=tpv.getTerms();+ int[] freq=tpv.getTermFrequencies();+ int totalTokens=0;+ for (int t = 0; t < freq.length; t++)+ {+ totalTokens+=freq[t];+ }+ Token tokensInOriginalOrder[]=new Token[totalTokens];+ ArrayList unsortedTokens = null;+ for (int t = 0; t < freq.length; t++)+ {+ TermVectorOffsetInfo[] offsets=tpv.getOffsets(t);+ if(offsets==null)+ {+ return null;+ }++ int[] pos=null;+ if(tokenPositionsGuaranteedContiguous)+ {+ //try get the token position info to speed up assembly of tokens into sorted sequence+ pos=tpv.getTermPositions(t);+ }+ if(pos==null)+ {+ //tokens NOT stored with positions or not guaranteed contiguous - must add to list and sort later+ if(unsortedTokens==null)+ {+ unsortedTokens=new ArrayList();+ }+ for (int tp = 0; tp < offsets.length; tp++)+ {+ unsortedTokens.add(new Token(terms[t],+ offsets[tp].getStartOffset(),+ offsets[tp].getEndOffset()));+ }+ }+ else+ {+ //We have positions stored and a guarantee that the token position information is contiguous++ // This may be fast BUT wont work if Tokenizers used which create >1 token in same position or+ // creates jumps in position numbers - this code would fail under those circumstances++ //tokens stored with positions - can use this to index straight into sorted array+ for (int tp = 0; tp < pos.length; tp++)+ {+ tokensInOriginalOrder[pos[tp]]=new Token(terms[t],+ offsets[tp].getStartOffset(),+ offsets[tp].getEndOffset());+ }+ }+ }+ //If the field has been stored without position data we must perform a sort+ if(unsortedTokens!=null)+ {+ tokensInOriginalOrder=(Token[]) unsortedTokens.toArray(new Token[unsortedTokens.size()]);+ Arrays.sort(tokensInOriginalOrder, new Comparator(){+ public int compare(Object o1, Object o2)+ {+ Token t1=(Token) o1;+ Token t2=(Token) o2;+ if(t1.startOffset()>t2.startOffset())+ return 1;+ if(t1.startOffset()<t2.startOffset())+ return -1;+ return 0;+ }});+ }+ return new StoredTokenStream(tokensInOriginalOrder);+ }++ public static TokenStream getTokenStream(IndexReader reader,int docId, String field) throws IOException+ {+ TermFreqVector tfv=(TermFreqVector) reader.getTermFreqVector(docId,field);+ if(tfv==null)+ {+ throw new IllegalArgumentException(field+" in doc #"+docId+ +"does not have any term position data stored");+ }+ if(tfv instanceof TermPositionVector)+ {+ TermPositionVector tpv=(TermPositionVector) reader.getTermFreqVector(docId,field);+ return getTokenStream(tpv);+ }+ throw new IllegalArgumentException(field+" in doc #"+docId+ +"does not have any term position data stored");+ }++ //convenience method+ public static TokenStream getTokenStream(IndexReader reader,int docId, String field,Analyzer analyzer) throws IOException+ {+ Document doc=reader.document(docId);+ String contents=doc.get(field);+ if(contents==null)+ {+ throw new IllegalArgumentException("Field "+field +" in document #"+docId+ " is not stored and cannot be analyzed");+ }+ return analyzer.tokenStream(field,new StringReader(contents));+ }++++}diff --git a/sandbox/contributions/highlighter/src/java/org/apache/lucene/search/highlight/package.html b/sandbox/contributions/highlighter/src/java/org/apache/lucene/search/highlight/package.htmlindex 1aa5721af91..9b1b0b3db7f 100755--- a/sandbox/contributions/highlighter/src/java/org/apache/lucene/search/highlight/package.html+++ b/sandbox/contributions/highlighter/src/java/org/apache/lucene/search/highlight/package.html@@ -13,7 +13,7 @@ Fragmenter, FragmentScorer and Formatter classes.query=query.rewrite(reader); //required to expand search termsHits hits = searcher.search(query);- Highlighter highlighter =new Highlighter(new QueryScorer(query));+ Highlighter highlighter =new Highlighter(this,new QueryScorer(query));for (int i = 0; i < hits.length(); i++){String text = hits.doc(i).get(FIELD_NAME);@@ -24,5 +24,26 @@ Fragmenter, FragmentScorer and Formatter classes.}</pre>+<h2>New features 22/12/2004</h2>+This release adds some new capabilities:+<ol>+ <li>Faster highlighting using Term vector support</li>+ <li>New formatting options to use color intensity to show informational value</li>+ <li>Options for better summarization by using term IDF scores to influence fragment selection</li>+</ol>+<p>+The highlighter takes a TokenStream as input. Until now these streams have typically been produced+using an Analyzer but the new class TokenSources provides helper methods for obtaining TokenStreams from+the new TermVector position support (see latest CVS version).</p>+<p>The new class GradientFormatter can use a scale of colors to highlight terms according to their score.+A subtle use of color can help emphasise the reasons for matching (useful when doing "MoreLikeThis" queries and+you want to see what the basis of the similarities are)</p>+<p>The QueryScorer class has a new constructor which can use an IndexReader to derive the IDF (inverse document frequency)+for each term in order to influcence the score. This is useful for helping to extracting the most significant sections+of a document and in supplying scores used by the new GradientFormatter to color significant words more strongly</p>++++</body></html>\ No newline at end of filediff --git a/sandbox/contributions/highlighter/src/test/org/apache/lucene/search/highlight/HighlighterTest.java b/sandbox/contributions/highlighter/src/test/org/apache/lucene/search/highlight/HighlighterTest.javaindex dc7c949ccd4..c964e51ac0b 100644--- a/sandbox/contributions/highlighter/src/test/org/apache/lucene/search/highlight/HighlighterTest.java+++ b/sandbox/contributions/highlighter/src/test/org/apache/lucene/search/highlight/HighlighterTest.java@@ -152,7 +152,6 @@ public class HighlighterTest extends TestCase implements Formatterpublic void testGetBestSingleFragment() throws Exception{doSearching("Kennedy");-// QueryHighlightExtractor highlighter = new QueryHighlightExtractor(this, query, new StandardAnalyzer());Highlighter highlighter =new Highlighter(this,new QueryScorer(query));highlighter.setTextFragmenter(new SimpleFragmenter(40));