2 * Copyright 2004 The Apache Software Foundation
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 using Field
= Lucene
.Net
.Documents
.Field
;
18 using IndexReader
= Lucene
.Net
.Index
.IndexReader
;
19 using IndexWriter
= Lucene
.Net
.Index
.IndexWriter
;
20 using Term
= Lucene
.Net
.Index
.Term
;
21 namespace Lucene
.Net
.Search
25 /// <summary>Expert: Scoring API.
26 /// <p>Subclasses implement search scoring.
28 /// <p>The score of query <code>q</code> for document <code>d</code> is defined
29 /// in terms of these methods as follows:
31 /// <table cellpadding="0" cellspacing="0" border="0">
33 /// <td valign="middle" align="right" rowspan="2">score(q,d) =<br></td>
34 /// <td valign="middle" align="center">
35 /// <big><big><big><big><big>Σ</big></big></big></big></big></td>
36 /// <td valign="middle"><small>
37 /// {@link #Tf(int) tf}(t in d) *
38 /// {@link #Idf(Term,Searcher) idf}(t) *
39 /// {@link Field#getBoost getBoost}(t.Field in d) *
40 /// {@link #LengthNorm(String,int) lengthNorm}(t.Field in d)
42 /// <td valign="middle" rowspan="2"> *
43 /// {@link #Coord(int,int) coord}(q,d) *
44 /// {@link #QueryNorm(float) queryNorm}(q)
48 /// <td valign="top" align="right">
49 /// <small>t in q</small>
55 /// <seealso cref="#SetDefault(Similarity)">
57 /// <seealso cref="IndexWriter#SetSimilarity(Similarity)">
59 /// <seealso cref="Searcher#SetSimilarity(Similarity)">
61 public abstract class Similarity
63 /// <summary>The Similarity implementation used by default. </summary>
64 private static Similarity defaultImpl
= new DefaultSimilarity();
66 /// <summary>Set the default Similarity implementation used by indexing and search
70 /// <seealso cref="Searcher#SetSimilarity(Similarity)">
72 /// <seealso cref="IndexWriter#SetSimilarity(Similarity)">
74 public static void SetDefault(Similarity similarity
)
76 Similarity
.defaultImpl
= similarity
;
79 /// <summary>Return the default Similarity implementation used by indexing and search
82 /// <p>This is initially an instance of {@link DefaultSimilarity}.
85 /// <seealso cref="Searcher#SetSimilarity(Similarity)">
87 /// <seealso cref="IndexWriter#SetSimilarity(Similarity)">
89 public static Similarity
GetDefault()
91 return Similarity
.defaultImpl
;
94 /// <summary>Cache of decoded bytes. </summary>
95 private static readonly float[] NORM_TABLE
= new float[256];
97 /// <summary>Decodes a normalization factor stored in an index.</summary>
98 /// <seealso cref="#EncodeNorm(float)">
100 public static float DecodeNorm(byte b
)
102 return NORM_TABLE
[b
& 0xFF];
105 /// <summary>Computes the normalization value for a Field given the total number of
106 /// terms contained in a Field. These values, together with Field boosts, are
107 /// stored in an index and multipled into scores for hits on each Field by the
110 /// <p>Matches in longer fields are less precise, so implemenations of this
111 /// method usually return smaller values when <code>numTokens</code> is large,
112 /// and larger values when <code>numTokens</code> is small.
114 /// <p>That these values are computed under {@link
115 /// IndexWriter#AddDocument(Document)} and stored then using
116 /// {#encodeNorm(float)}. Thus they have limited precision, and documents
117 /// must be re-indexed if this method is altered.
120 /// <param name="fieldName">the name of the Field
122 /// <param name="numTokens">the total number of tokens contained in fields named
123 /// <i>fieldName</i> of <i>doc</i>.
125 /// <returns> a normalization factor for hits on this Field of this document
128 /// <seealso cref="Field#SetBoost(float)">
130 public abstract float LengthNorm(System
.String fieldName
, int numTokens
);
132 /// <summary>Computes the normalization value for a query given the sum of the squared
133 /// weights of each of the query terms. This value is then multipled into the
134 /// weight of each query term.
136 /// <p>This does not affect ranking, but rather just attempts to make scores
137 /// from different queries comparable.
140 /// <param name="sumOfSquaredWeights">the sum of the squares of query term weights
142 /// <returns> a normalization factor for query weights
144 public abstract float QueryNorm(float sumOfSquaredWeights
);
146 /// <summary>Encodes a normalization factor for storage in an index.
148 /// <p>The encoding uses a five-bit exponent and three-bit mantissa, thus
149 /// representing values from around 7x10^9 to 2x10^-9 with about one
150 /// significant decimal digit of accuracy. Zero is also represented.
151 /// Negative numbers are rounded up to zero. Values too large to represent
152 /// are rounded down to the largest representable value. Positive values too
153 /// small to represent are rounded up to the smallest positive representable
157 /// <seealso cref="Field#SetBoost(float)">
159 public static byte EncodeNorm(float f
)
161 return FloatToByte(f
);
164 private static float ByteToFloat(byte b
)
167 // zero is a special case
169 int mantissa
= b
& 7;
170 int exponent
= (b
>> 3) & 31;
171 int bits
= ((exponent
+ (63 - 15)) << 24) | (mantissa
<< 21);
172 return BitConverter
.ToSingle(BitConverter
.GetBytes(bits
), 0);
175 private static byte FloatToByte(float f
)
178 // round negatives up to zero
182 // zero is a special case
185 int bits
= BitConverter
.ToInt32(BitConverter
.GetBytes(f
), 0); // parse float into parts
186 int mantissa
= (bits
& 0xffffff) >> 21;
187 int exponent
= (((bits
>> 24) & 0x7f) - 63) + 15;
191 // overflow: use max value
198 // underflow: use min value
203 return (byte) ((exponent
<< 3) | mantissa
); // pack into a byte
207 /// <summary>Computes a score factor based on a term or phrase's frequency in a
208 /// document. This value is multiplied by the {@link #Idf(Term, Searcher)}
209 /// factor for each term in the query and these products are then summed to
210 /// form the initial score for a document.
212 /// <p>Terms and phrases repeated in a document indicate the topic of the
213 /// document, so implementations of this method usually return larger values
214 /// when <code>freq</code> is large, and smaller values when <code>freq</code>
217 /// <p>The default implementation calls {@link #Tf(float)}.
220 /// <param name="freq">the frequency of a term within a document
222 /// <returns> a score factor based on a term's within-document frequency
224 public virtual float Tf(int freq
)
226 return Tf((float) freq
);
229 /// <summary>Computes the amount of a sloppy phrase match, based on an edit distance.
230 /// This value is summed for each sloppy phrase match in a document to form
231 /// the frequency that is passed to {@link #Tf(float)}.
233 /// <p>A phrase match with a small edit distance to a document passage more
234 /// closely matches the document, so implementations of this method usually
235 /// return larger values when the edit distance is small and smaller values
236 /// when it is large.
239 /// <seealso cref="PhraseQuery#SetSlop(int)">
241 /// <param name="distance">the edit distance of this sloppy phrase match
243 /// <returns> the frequency increment for this match
245 public abstract float SloppyFreq(int distance
);
247 /// <summary>Computes a score factor based on a term or phrase's frequency in a
248 /// document. This value is multiplied by the {@link #Idf(Term, Searcher)}
249 /// factor for each term in the query and these products are then summed to
250 /// form the initial score for a document.
252 /// <p>Terms and phrases repeated in a document indicate the topic of the
253 /// document, so implemenations of this method usually return larger values
254 /// when <code>freq</code> is large, and smaller values when <code>freq</code>
258 /// <param name="freq">the frequency of a term within a document
260 /// <returns> a score factor based on a term's within-document frequency
262 public abstract float Tf(float freq
);
264 /// <summary>Computes a score factor for a simple term.
266 /// <p>The default implementation is:<pre>
267 /// return idf(searcher.docFreq(term), searcher.maxDoc());
270 /// Note that {@link Searcher#MaxDoc()} is used instead of
271 /// {@link IndexReader#NumDocs()} because it is proportional to
272 /// {@link Searcher#DocFreq(Term)} , i.e., when one is inaccurate,
273 /// so is the other, and in the same direction.
276 /// <param name="term">the term in question
278 /// <param name="searcher">the document collection being searched
280 /// <returns> a score factor for the term
282 public virtual float Idf(Term term
, Searcher searcher
)
284 return Idf(searcher
.DocFreq(term
), searcher
.MaxDoc());
287 /// <summary>Computes a score factor for a phrase.
289 /// <p>The default implementation sums the {@link #Idf(Term,Searcher)} factor
290 /// for each term in the phrase.
293 /// <param name="terms">the terms in the phrase
295 /// <param name="searcher">the document collection being searched
297 /// <returns> a score factor for the phrase
299 public virtual float Idf(System
.Collections
.ICollection terms
, Searcher searcher
)
302 System
.Collections
.IEnumerator i
= terms
.GetEnumerator();
305 idf
+= Idf((Term
) i
.Current
, searcher
);
310 /// <summary>Computes a score factor based on a term's document frequency (the number
311 /// of documents which contain the term). This value is multiplied by the
312 /// {@link #Tf(int)} factor for each term in the query and these products are
313 /// then summed to form the initial score for a document.
315 /// <p>Terms that occur in fewer documents are better indicators of topic, so
316 /// implemenations of this method usually return larger values for rare terms,
317 /// and smaller values for common terms.
320 /// <param name="docFreq">the number of documents which contain the term
322 /// <param name="numDocs">the total number of documents in the collection
324 /// <returns> a score factor based on the term's document frequency
326 public abstract float Idf(int docFreq
, int numDocs
);
328 /// <summary>Computes a score factor based on the fraction of all query terms that a
329 /// document contains. This value is multiplied into scores.
331 /// <p>The presence of a large portion of the query terms indicates a better
332 /// match with the query, so implemenations of this method usually return
333 /// larger values when the ratio between these parameters is large and smaller
334 /// values when the ratio between them is small.
337 /// <param name="overlap">the number of query terms matched in the document
339 /// <param name="maxOverlap">the total number of terms in the query
341 /// <returns> a score factor based on term overlap with the query
343 public abstract float Coord(int overlap
, int maxOverlap
);
347 for (int i
= 0; i
< 256; i
++)
348 NORM_TABLE
[i
] = ByteToFloat((byte) i
);