1
package org.apache.lucene.search.highlight;
4
* Licensed to the Apache Software Foundation (ASF) under one or more
5
* contributor license agreements. See the NOTICE file distributed with
6
* this work for additional information regarding copyright ownership.
7
* The ASF licenses this file to You under the Apache License, Version 2.0
8
* (the "License"); you may not use this file except in compliance with
9
* the License. You may obtain a copy of the License at
11
* http://www.apache.org/licenses/LICENSE-2.0
13
* Unless required by applicable law or agreed to in writing, software
14
* distributed under the License is distributed on an "AS IS" BASIS,
15
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
* See the License for the specific language governing permissions and
17
* limitations under the License.
20
import java.io.IOException;
21
import java.util.HashMap;
22
import java.util.HashSet;
26
import org.apache.lucene.analysis.CachingTokenFilter;
27
import org.apache.lucene.analysis.TokenStream;
28
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
29
import org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute;
30
import org.apache.lucene.index.IndexReader;
31
import org.apache.lucene.index.memory.MemoryIndex;
32
import org.apache.lucene.search.Query;
33
import org.apache.lucene.search.spans.SpanQuery;
34
import org.apache.lucene.util.StringHelper;
37
* {@link Scorer} implementation which scores text fragments by the number of
38
* unique query terms found. This class converts appropriate {@link Query}s to
39
* {@link SpanQuery}s and attempts to score only those terms that participated in
40
* generating the 'hit' on the document.
42
public class QueryScorer implements Scorer {
43
private float totalScore;
44
private Set<String> foundTerms;
45
private Map<String,WeightedSpanTerm> fieldWeightedSpanTerms;
46
private float maxTermWeight;
47
private int position = -1;
48
private String defaultField;
49
private CharTermAttribute termAtt;
50
private PositionIncrementAttribute posIncAtt;
51
private boolean expandMultiTermQuery = true;
54
private IndexReader reader;
55
private boolean skipInitExtractor;
56
private boolean wrapToCaching = true;
57
private int maxCharsToAnalyze;
60
* @param query Query to use for highlighting
62
public QueryScorer(Query query) {
63
init(query, null, null, true);
67
* @param query Query to use for highlighting
68
* @param field Field to highlight - pass null to ignore fields
70
public QueryScorer(Query query, String field) {
71
init(query, field, null, true);
75
* @param query Query to use for highlighting
76
* @param field Field to highlight - pass null to ignore fields
77
* @param reader {@link IndexReader} to use for quasi tf/idf scoring
79
public QueryScorer(Query query, IndexReader reader, String field) {
80
init(query, field, reader, true);
85
* @param query to use for highlighting
86
* @param reader {@link IndexReader} to use for quasi tf/idf scoring
87
* @param field to highlight - pass null to ignore fields
90
public QueryScorer(Query query, IndexReader reader, String field, String defaultField) {
91
this.defaultField = StringHelper.intern(defaultField);
92
init(query, field, reader, true);
96
* @param defaultField - The default field for queries with the field name unspecified
98
public QueryScorer(Query query, String field, String defaultField) {
99
this.defaultField = StringHelper.intern(defaultField);
100
init(query, field, null, true);
104
* @param weightedTerms an array of pre-created {@link WeightedSpanTerm}s
106
public QueryScorer(WeightedSpanTerm[] weightedTerms) {
107
this.fieldWeightedSpanTerms = new HashMap<String,WeightedSpanTerm>(weightedTerms.length);
109
for (int i = 0; i < weightedTerms.length; i++) {
110
WeightedSpanTerm existingTerm = fieldWeightedSpanTerms.get(weightedTerms[i].term);
112
if ((existingTerm == null) ||
113
(existingTerm.weight < weightedTerms[i].weight)) {
114
// if a term is defined more than once, always use the highest
116
fieldWeightedSpanTerms.put(weightedTerms[i].term, weightedTerms[i]);
117
maxTermWeight = Math.max(maxTermWeight, weightedTerms[i].getWeight());
120
skipInitExtractor = true;
126
* @see org.apache.lucene.search.highlight.Scorer#getFragmentScore()
128
public float getFragmentScore() {
134
* @return The highest weighted term (useful for passing to
135
* GradientFormatter to set top end of coloring scale).
137
public float getMaxTermWeight() {
138
return maxTermWeight;
144
* @see org.apache.lucene.search.highlight.Scorer#getTokenScore(org.apache.lucene.analysis.Token,
147
public float getTokenScore() {
148
position += posIncAtt.getPositionIncrement();
149
String termText = termAtt.toString();
151
WeightedSpanTerm weightedSpanTerm;
153
if ((weightedSpanTerm = fieldWeightedSpanTerms.get(
154
termText)) == null) {
158
if (weightedSpanTerm.positionSensitive &&
159
!weightedSpanTerm.checkPosition(position)) {
163
float score = weightedSpanTerm.getWeight();
165
// found a query term - is it unique in this doc?
166
if (!foundTerms.contains(termText)) {
168
foundTerms.add(termText);
175
* @see org.apache.lucene.search.highlight.Scorer#init(org.apache.lucene.analysis.TokenStream)
177
public TokenStream init(TokenStream tokenStream) throws IOException {
179
termAtt = tokenStream.addAttribute(CharTermAttribute.class);
180
posIncAtt = tokenStream.addAttribute(PositionIncrementAttribute.class);
181
if(!skipInitExtractor) {
182
if(fieldWeightedSpanTerms != null) {
183
fieldWeightedSpanTerms.clear();
185
return initExtractor(tokenStream);
191
* Retrieve the {@link WeightedSpanTerm} for the specified token. Useful for passing
192
* Span information to a {@link Fragmenter}.
194
* @param token to get {@link WeightedSpanTerm} for
195
* @return WeightedSpanTerm for token
197
public WeightedSpanTerm getWeightedSpanTerm(String token) {
198
return fieldWeightedSpanTerms.get(token);
203
private void init(Query query, String field, IndexReader reader, boolean expandMultiTermQuery) {
204
this.reader = reader;
205
this.expandMultiTermQuery = expandMultiTermQuery;
210
private TokenStream initExtractor(TokenStream tokenStream) throws IOException {
211
WeightedSpanTermExtractor qse = defaultField == null ? new WeightedSpanTermExtractor()
212
: new WeightedSpanTermExtractor(defaultField);
213
qse.setMaxDocCharsToAnalyze(maxCharsToAnalyze);
214
qse.setExpandMultiTermQuery(expandMultiTermQuery);
215
qse.setWrapIfNotCachingTokenFilter(wrapToCaching);
216
if (reader == null) {
217
this.fieldWeightedSpanTerms = qse.getWeightedSpanTerms(query,
220
this.fieldWeightedSpanTerms = qse.getWeightedSpanTermsWithScores(query,
221
tokenStream, field, reader);
223
if(qse.isCachedTokenStream()) {
224
return qse.getTokenStream();
233
* @see org.apache.lucene.search.highlight.Scorer#startFragment(org.apache.lucene.search.highlight.TextFragment)
235
public void startFragment(TextFragment newFragment) {
236
foundTerms = new HashSet<String>();
241
* @return true if multi-term queries should be expanded
243
public boolean isExpandMultiTermQuery() {
244
return expandMultiTermQuery;
248
* Controls whether or not multi-term queries are expanded
249
* against a {@link MemoryIndex} {@link IndexReader}.
251
* @param expandMultiTermQuery true if multi-term queries should be expanded
253
public void setExpandMultiTermQuery(boolean expandMultiTermQuery) {
254
this.expandMultiTermQuery = expandMultiTermQuery;
258
* By default, {@link TokenStream}s that are not of the type
259
* {@link CachingTokenFilter} are wrapped in a {@link CachingTokenFilter} to
260
* ensure an efficient reset - if you are already using a different caching
261
* {@link TokenStream} impl and you don't want it to be wrapped, set this to
266
public void setWrapIfNotCachingTokenFilter(boolean wrap) {
267
this.wrapToCaching = wrap;
270
public void setMaxDocCharsToAnalyze(int maxDocCharsToAnalyze) {
271
this.maxCharsToAnalyze = maxDocCharsToAnalyze;