Skip to content

Apache Lucene open-source search software

LUCENE-8249: Implement Matches API for phrase queries

Alan Woodward7d9059ef13df
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txt
index 2535eb15fa0..50e28451c91 100644
--- a/lucene/CHANGES.txt
+++ b/lucene/CHANGES.txt
@@ -150,6 +150,9 @@ New Features
This allows exact hit extraction and will enable implementation of accurate
highlighters. (Alan Woodward, Adrien Grand, David Smiley)
+* LUCENE-8249: Implement Matches API for phrase queries (Alan Woodward, Adrien
+ Grand)
+
* LUCENE-8246: Allow to customize the number of deletes a merge claims. This
helps merge policies in the soft-delete case to correctly implement retention
policies without triggering uncessary merges. (Simon Willnauer, Mike McCandless)
diff --git a/lucene/core/src/java/org/apache/lucene/search/ExactPhraseScorer.java b/lucene/core/src/java/org/apache/lucene/search/ExactPhraseMatcher.java
similarity index 57%
rename from lucene/core/src/java/org/apache/lucene/search/ExactPhraseScorer.java
rename to lucene/core/src/java/org/apache/lucene/search/ExactPhraseMatcher.java
index d7c4f9f6e2b..b95077d0971 100644
--- a/lucene/core/src/java/org/apache/lucene/search/ExactPhraseScorer.java
+++ b/lucene/core/src/java/org/apache/lucene/search/ExactPhraseMatcher.java
@@ -23,7 +23,7 @@ import java.util.List;
import org.apache.lucene.index.PostingsEnum;
-final class ExactPhraseScorer extends Scorer {
+final class ExactPhraseMatcher extends PhraseMatcher {
private static class PostingsAndPosition {
private final PostingsEnum postings;
@@ -36,93 +36,33 @@ final class ExactPhraseScorer extends Scorer {
}
}
- private final DocIdSetIterator conjunction;
private final PostingsAndPosition[] postings;
- private int freq;
+ ExactPhraseMatcher(PhraseQuery.PostingsAndFreq[] postings, float matchCost) {
+ super(approximation(postings), matchCost);
- private final LeafSimScorer docScorer;
- private final boolean needsScores, needsTotalHitCount;
- private float matchCost;
- private float minCompetitiveScore;
-
- ExactPhraseScorer(Weight weight, PhraseQuery.PostingsAndFreq[] postings,
- LeafSimScorer docScorer, ScoreMode scoreMode,
- float matchCost) throws IOException {
- super(weight);
- this.docScorer = docScorer;
- this.needsScores = scoreMode.needsScores();
- this.needsTotalHitCount = scoreMode != ScoreMode.TOP_SCORES;
-
- List<DocIdSetIterator> iterators = new ArrayList<>();
List<PostingsAndPosition> postingsAndPositions = new ArrayList<>();
for(PhraseQuery.PostingsAndFreq posting : postings) {
- iterators.add(posting.postings);
postingsAndPositions.add(new PostingsAndPosition(posting.postings, posting.position));
}
- conjunction = ConjunctionDISI.intersectIterators(iterators);
- assert TwoPhaseIterator.unwrap(conjunction) == null;
this.postings = postingsAndPositions.toArray(new PostingsAndPosition[postingsAndPositions.size()]);
- this.matchCost = matchCost;
}
- @Override
- public void setMinCompetitiveScore(float minScore) {
- minCompetitiveScore = minScore;
- }
-
- @Override
- public TwoPhaseIterator twoPhaseIterator() {
- return new TwoPhaseIterator(conjunction) {
- @Override
- public boolean matches() throws IOException {
- if (needsTotalHitCount == false && minCompetitiveScore > 0) {
- int minFreq = postings[0].postings.freq();
- for (int i = 1; i < postings.length; ++i) {
- minFreq = Math.min(postings[i].postings.freq(), minFreq);
- }
- if (docScorer.score(docID(), minFreq) < minCompetitiveScore) {
- // The maximum score we could get is less than the min competitive score
- return false;
- }
- }
- return phraseFreq() > 0;
- }
-
- @Override
- public float matchCost() {
- return matchCost;
- }
- };
- }
-
- @Override
- public DocIdSetIterator iterator() {
- return TwoPhaseIterator.asDocIdSetIterator(twoPhaseIterator());
- }
-
- @Override
- public String toString() {
- return "ExactPhraseScorer(" + weight + ")";
- }
-
- final int freq() {
- return freq;
- }
-
- @Override
- public int docID() {
- return conjunction.docID();
- }
-
- @Override
- public float score() throws IOException {
- return docScorer.score(docID(), freq);
+ private static DocIdSetIterator approximation(PhraseQuery.PostingsAndFreq[] postings) {
+ List<DocIdSetIterator> iterators = new ArrayList<>();
+ for (PhraseQuery.PostingsAndFreq posting : postings) {
+ iterators.add(posting.postings);
+ }
+ return ConjunctionDISI.intersectIterators(iterators);
}
@Override
- public float getMaxScore(int upTo) throws IOException {
- return docScorer.maxScore();
+ float maxFreq() {
+ int minFreq = postings[0].freq;
+ for (int i = 1; i < postings.length; i++) {
+ minFreq = Math.min(minFreq, postings[i].freq);
+ }
+ return minFreq;
}
/** Advance the given pos enum to the first doc on or after {@code target}.
@@ -140,18 +80,25 @@ final class ExactPhraseScorer extends Scorer {
return true;
}
- private int phraseFreq() throws IOException {
- // reset state
- final PostingsAndPosition[] postings = this.postings;
+ @Override
+ public void reset() throws IOException {
for (PostingsAndPosition posting : postings) {
posting.freq = posting.postings.freq();
- posting.pos = posting.postings.nextPosition();
- posting.upTo = 1;
+ posting.pos = -1;
+ posting.upTo = 0;
}
+ }
- int freq = 0;
+ @Override
+ public boolean nextMatch() throws IOException {
final PostingsAndPosition lead = postings[0];
-
+ if (lead.upTo < lead.freq) {
+ lead.pos = lead.postings.nextPosition();
+ lead.upTo += 1;
+ }
+ else {
+ return false;
+ }
advanceHead:
while (true) {
final int phrasePos = lead.pos - lead.offset;
@@ -172,20 +119,34 @@ final class ExactPhraseScorer extends Scorer {
}
}
}
+ return true;
+ }
+ return false;
+ }
- freq += 1;
- if (needsScores == false) {
- break;
- }
+ @Override
+ float sloppyWeight() {
+ return 1;
+ }
- if (lead.upTo == lead.freq) {
- break;
- }
- lead.pos = lead.postings.nextPosition();
- lead.upTo += 1;
- }
+ @Override
+ public int startPosition() {
+ return postings[0].pos;
+ }
- return this.freq = freq;
+ @Override
+ public int endPosition() {
+ return postings[postings.length - 1].pos;
+ }
+
+ @Override
+ public int startOffset() throws IOException {
+ return postings[0].postings.startOffset();
+ }
+
+ @Override
+ public int endOffset() throws IOException {
+ return postings[postings.length - 1].postings.endOffset();
}
}
diff --git a/lucene/core/src/java/org/apache/lucene/search/MultiPhraseQuery.java b/lucene/core/src/java/org/apache/lucene/search/MultiPhraseQuery.java
index 65d6631e9a7..22b71279012 100644
--- a/lucene/core/src/java/org/apache/lucene/search/MultiPhraseQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/search/MultiPhraseQuery.java
@@ -34,8 +34,8 @@ import org.apache.lucene.index.LeafReader;
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.index.PostingsEnum;
import org.apache.lucene.index.Term;
-import org.apache.lucene.index.TermStates;
import org.apache.lucene.index.TermState;
+import org.apache.lucene.index.TermStates;
import org.apache.lucene.index.Terms;
import org.apache.lucene.index.TermsEnum;
import org.apache.lucene.search.similarities.Similarity;
@@ -187,164 +187,125 @@ public class MultiPhraseQuery extends Query {
return positions;
}
+ @Override
+ public Query rewrite(IndexReader reader) throws IOException {
+ if (termArrays.length == 0) {
+ return new MatchNoDocsQuery("empty MultiPhraseQuery");
+ } else if (termArrays.length == 1) { // optimize one-term case
+ Term[] terms = termArrays[0];
+ BooleanQuery.Builder builder = new BooleanQuery.Builder();
+ for (Term term : terms) {
+ builder.add(new TermQuery(term), BooleanClause.Occur.SHOULD);
+ }
+ return builder.build();
+ } else {
+ return super.rewrite(reader);
+ }
+ }
+
+ @Override
+ public Weight createWeight(IndexSearcher searcher, ScoreMode scoreMode, float boost) throws IOException {
+ final Map<Term,TermStates> termStates = new HashMap<>();
+ return new PhraseWeight(this, field, searcher, scoreMode) {
- private class MultiPhraseWeight extends Weight {
- private final Similarity similarity;
- private final Similarity.SimScorer stats;
- private final Map<Term,TermStates> termStates = new HashMap<>();
- private final ScoreMode scoreMode;
-
- public MultiPhraseWeight(IndexSearcher searcher, ScoreMode scoreMode, float boost)
- throws IOException {
- super(MultiPhraseQuery.this);
- this.scoreMode = scoreMode;
- this.similarity = searcher.getSimilarity();
- final IndexReaderContext context = searcher.getTopReaderContext();
-
- // compute idf
- ArrayList<TermStatistics> allTermStats = new ArrayList<>();
- for(final Term[] terms: termArrays) {
- for (Term term: terms) {
- TermStates ts = termStates.get(term);
- if (ts == null) {
- ts = TermStates.build(context, term, scoreMode.needsScores());
- termStates.put(term, ts);
- }
- if (scoreMode.needsScores()) {
- TermStatistics termStatistics = searcher.termStatistics(term, ts);
- if (termStatistics != null) {
- allTermStats.add(termStatistics);
+ @Override
+ protected Similarity.SimScorer getStats(IndexSearcher searcher) throws IOException {
+ final IndexReaderContext context = searcher.getTopReaderContext();
+
+ // compute idf
+ ArrayList<TermStatistics> allTermStats = new ArrayList<>();
+ for(final Term[] terms: termArrays) {
+ for (Term term: terms) {
+ TermStates ts = termStates.get(term);
+ if (ts == null) {
+ ts = TermStates.build(context, term, scoreMode.needsScores());
+ termStates.put(term, ts);
+ }
+ if (scoreMode.needsScores()) {
+ TermStatistics termStatistics = searcher.termStatistics(term, ts);
+ if (termStatistics != null) {
+ allTermStats.add(termStatistics);
+ }
}
}
}
+ if (allTermStats.isEmpty()) {
+ return null; // none of the terms were found, we won't use sim at all
+ } else {
+ return similarity.scorer(
+ boost,
+ searcher.collectionStatistics(field),
+ allTermStats.toArray(new TermStatistics[allTermStats.size()]));
+ }
}
- if (allTermStats.isEmpty()) {
- stats = null; // none of the terms were found, we won't use sim at all
- } else {
- stats = similarity.scorer(
- boost,
- searcher.collectionStatistics(field),
- allTermStats.toArray(new TermStatistics[allTermStats.size()]));
- }
- }
- @Override
- public void extractTerms(Set<Term> terms) {
- for (final Term[] arr : termArrays) {
- Collections.addAll(terms, arr);
- }
- }
+ @Override
+ protected PhraseMatcher getPhraseMatcher(LeafReaderContext context, boolean exposeOffsets) throws IOException {
+ assert termArrays.length != 0;
+ final LeafReader reader = context.reader();
- @Override
- public Scorer scorer(LeafReaderContext context) throws IOException {
- assert termArrays.length != 0;
- final LeafReader reader = context.reader();
+ PhraseQuery.PostingsAndFreq[] postingsFreqs = new PhraseQuery.PostingsAndFreq[termArrays.length];
- PhraseQuery.PostingsAndFreq[] postingsFreqs = new PhraseQuery.PostingsAndFreq[termArrays.length];
+ final Terms fieldTerms = reader.terms(field);
+ if (fieldTerms == null) {
+ return null;
+ }
- final Terms fieldTerms = reader.terms(field);
- if (fieldTerms == null) {
- return null;
- }
+ // TODO: move this check to createWeight to happen earlier to the user?
+ if (fieldTerms.hasPositions() == false) {
+ throw new IllegalStateException("field \"" + field + "\" was indexed without position data;" +
+ " cannot run MultiPhraseQuery (phrase=" + getQuery() + ")");
+ }
- // TODO: move this check to createWeight to happen earlier to the user?
- if (fieldTerms.hasPositions() == false) {
- throw new IllegalStateException("field \"" + field + "\" was indexed without position data;" +
- " cannot run MultiPhraseQuery (phrase=" + getQuery() + ")");
- }
+ // Reuse single TermsEnum below:
+ final TermsEnum termsEnum = fieldTerms.iterator();
+ float totalMatchCost = 0;
- // Reuse single TermsEnum below:
- final TermsEnum termsEnum = fieldTerms.iterator();
- float totalMatchCost = 0;
+ for (int pos=0; pos<postingsFreqs.length; pos++) {
+ Term[] terms = termArrays[pos];
+ List<PostingsEnum> postings = new ArrayList<>();
- for (int pos=0; pos<postingsFreqs.length; pos++) {
- Term[] terms = termArrays[pos];
- List<PostingsEnum> postings = new ArrayList<>();
+ for (Term term : terms) {
+ TermState termState = termStates.get(term).get(context);
+ if (termState != null) {
+ termsEnum.seekExact(term.bytes(), termState);
+ postings.add(termsEnum.postings(null, exposeOffsets ? PostingsEnum.OFFSETS : PostingsEnum.POSITIONS));
+ totalMatchCost += PhraseQuery.termPositionsCost(termsEnum);
+ }
+ }
- for (Term term : terms) {
- TermState termState = termStates.get(term).get(context);
- if (termState != null) {
- termsEnum.seekExact(term.bytes(), termState);
- postings.add(termsEnum.postings(null, PostingsEnum.POSITIONS));
- totalMatchCost += PhraseQuery.termPositionsCost(termsEnum);
+ if (postings.isEmpty()) {
+ return null;
}
- }
- if (postings.isEmpty()) {
- return null;
- }
+ final PostingsEnum postingsEnum;
+ if (postings.size() == 1) {
+ postingsEnum = postings.get(0);
+ } else {
+ postingsEnum = exposeOffsets ? new UnionFullPostingsEnum(postings) : new UnionPostingsEnum(postings);
+ }
- final PostingsEnum postingsEnum;
- if (postings.size() == 1) {
- postingsEnum = postings.get(0);
- } else {
- postingsEnum = new UnionPostingsEnum(postings);
+ postingsFreqs[pos] = new PhraseQuery.PostingsAndFreq(postingsEnum, positions[pos], terms);
}
- postingsFreqs[pos] = new PhraseQuery.PostingsAndFreq(postingsEnum, positions[pos], terms);
- }
-
- // sort by increasing docFreq order
- if (slop == 0) {
- ArrayUtil.timSort(postingsFreqs);
- }
+ // sort by increasing docFreq order
+ if (slop == 0) {
+ ArrayUtil.timSort(postingsFreqs);
+ return new ExactPhraseMatcher(postingsFreqs, totalMatchCost);
+ }
+ else {
+ return new SloppyPhraseMatcher(postingsFreqs, slop, totalMatchCost);
+ }
- if (slop == 0) {
- return new ExactPhraseScorer(this, postingsFreqs,
- new LeafSimScorer(stats, context.reader(), scoreMode.needsScores(), Integer.MAX_VALUE),
- scoreMode, totalMatchCost);
- } else {
- return new SloppyPhraseScorer(this, postingsFreqs, slop,
- new LeafSimScorer(stats, context.reader(), scoreMode.needsScores(), Float.MAX_VALUE),
- scoreMode.needsScores(), totalMatchCost);
}
- }
- @Override
- public boolean isCacheable(LeafReaderContext ctx) {
- return true;
- }
-
- @Override
- public Explanation explain(LeafReaderContext context, int doc) throws IOException {
- Scorer scorer = scorer(context);
- if (scorer != null) {
- int newDoc = scorer.iterator().advance(doc);
- if (newDoc == doc) {
- float freq = slop == 0 ? ((ExactPhraseScorer)scorer).freq() : ((SloppyPhraseScorer)scorer).sloppyFreq();
- LeafSimScorer docScorer = new LeafSimScorer(stats, context.reader(), scoreMode.needsScores(), Float.MAX_VALUE);
- Explanation freqExplanation = Explanation.match(freq, "phraseFreq=" + freq);
- Explanation scoreExplanation = docScorer.explain(doc, freqExplanation);
- return Explanation.match(
- scoreExplanation.getValue(),
- "weight("+getQuery()+" in "+doc+") [" + similarity.getClass().getSimpleName() + "], result of:",
- scoreExplanation);
+ @Override
+ public void extractTerms(Set<Term> terms) {
+ for (final Term[] arr : termArrays) {
+ Collections.addAll(terms, arr);
}
}
-
- return Explanation.noMatch("no matching term");
- }
- }
-
- @Override
- public Query rewrite(IndexReader reader) throws IOException {
- if (termArrays.length == 0) {
- return new MatchNoDocsQuery("empty MultiPhraseQuery");
- } else if (termArrays.length == 1) { // optimize one-term case
- Term[] terms = termArrays[0];
- BooleanQuery.Builder builder = new BooleanQuery.Builder();
- for (Term term : terms) {
- builder.add(new TermQuery(term), BooleanClause.Occur.SHOULD);
- }
- return builder.build();
- } else {
- return super.rewrite(reader);
- }
- }
-
- @Override
- public Weight createWeight(IndexSearcher searcher, ScoreMode scoreMode, float boost) throws IOException {
- return new MultiPhraseWeight(searcher, scoreMode, boost);
+ };
}
/** Prints a user-readable version of this query. */
@@ -601,4 +562,90 @@ public class MultiPhraseQuery extends Query {
}
}
}
+
+ static class PostingsAndPosition {
+ final PostingsEnum pe;
+ int pos;
+ int upto;
+
+ PostingsAndPosition(PostingsEnum pe) {
+ this.pe = pe;
+ }
+ }
+
+ // Slower version of UnionPostingsEnum that delegates offsets and positions, for
+ // use by MatchesIterator
+ static class UnionFullPostingsEnum extends UnionPostingsEnum {
+
+ int freq = -1;
+ boolean started = false;
+
+ final PriorityQueue<PostingsAndPosition> posQueue;
+ final Collection<PostingsAndPosition> subs;
+
+ UnionFullPostingsEnum(List<PostingsEnum> subs) {
+ super(subs);
+ this.posQueue = new PriorityQueue<PostingsAndPosition>(subs.size()) {
+ @Override
+ protected boolean lessThan(PostingsAndPosition a, PostingsAndPosition b) {
+ return a.pos < b.pos;
+ }
+ };
+ this.subs = new ArrayList<>();
+ for (PostingsEnum pe : subs) {
+ this.subs.add(new PostingsAndPosition(pe));
+ }
+ }
+
+ @Override
+ public int freq() throws IOException {
+ int doc = docID();
+ if (doc == posQueueDoc) {
+ return freq;
+ }
+ freq = 0;
+ started = false;
+ posQueue.clear();
+ for (PostingsAndPosition pp : subs) {
+ if (pp.pe.docID() == doc) {
+ pp.pos = pp.pe.nextPosition();
+ pp.upto = pp.pe.freq();
+ posQueue.add(pp);
+ freq += pp.upto;
+ }
+ }
+ return freq;
+ }
+
+ @Override
+ public int nextPosition() throws IOException {
+ if (started == false) {
+ started = true;
+ return posQueue.top().pos;
+ }
+ if (posQueue.top().upto == 1) {
+ posQueue.pop();
+ return posQueue.top().pos;
+ }
+ posQueue.top().pos = posQueue.top().pe.nextPosition();
+ posQueue.top().upto--;
+ posQueue.updateTop();
+ return posQueue.top().pos;
+ }
+
+ @Override
+ public int startOffset() throws IOException {
+ return posQueue.top().pe.startOffset();
+ }
+
+ @Override
+ public int endOffset() throws IOException {
+ return posQueue.top().pe.endOffset();
+ }
+
+ @Override
+ public BytesRef getPayload() throws IOException {
+ return posQueue.top().pe.getPayload();
+ }
+ }
}
diff --git a/lucene/core/src/java/org/apache/lucene/search/PhraseMatcher.java b/lucene/core/src/java/org/apache/lucene/search/PhraseMatcher.java
new file mode 100644
index 00000000000..81040d517c4
--- /dev/null
+++ b/lucene/core/src/java/org/apache/lucene/search/PhraseMatcher.java
@@ -0,0 +1,91 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+
+package org.apache.lucene.search;
+
+import java.io.IOException;
+
+/**
+ * Base class for exact and sloppy phrase matching
+ *
+ * To find matches on a document, first advance {@link #approximation} to the
+ * relevant document, then call {@link #reset()}. Clients can then call
+ * {@link #nextMatch()} to iterate over the matches
+ */
+abstract class PhraseMatcher {
+
+ protected final DocIdSetIterator approximation;
+ private final float matchCost;
+
+ PhraseMatcher(DocIdSetIterator approximation, float matchCost) {
+ assert TwoPhaseIterator.unwrap(approximation) == null;
+ this.approximation = approximation;
+ this.matchCost = matchCost;
+ }
+
+ /**
+ * An upper bound on the number of possible matches on this document
+ */
+ abstract float maxFreq() throws IOException;
+
+ /**
+ * Called after {@link #approximation} has been advanced
+ */
+ public abstract void reset() throws IOException;
+
+ /**
+ * Find the next match on the current document, returning {@code false} if there
+ * are none.
+ */
+ public abstract boolean nextMatch() throws IOException;
+
+ /**
+ * The slop-adjusted weight of the current match
+ *
+ * The sum of the slop-adjusted weights is used as the freq for scoring
+ */
+ abstract float sloppyWeight();
+
+ /**
+ * The start position of the current match
+ */
+ abstract int startPosition();
+
+ /**
+ * The end position of the current match
+ */
+ abstract int endPosition();
+
+ /**
+ * The start offset of the current match
+ */
+ abstract int startOffset() throws IOException;
+
+ /**
+ * The end offset of the current match
+ */
+ abstract int endOffset() throws IOException;
+
+ /**
+ * An estimate of the average cost of finding all matches on a document
+ *
+ * @see TwoPhaseIterator#matchCost()
+ */
+ public float getMatchCost() {
+ return matchCost;
+ }
+}
diff --git a/lucene/core/src/java/org/apache/lucene/search/PhraseQuery.java b/lucene/core/src/java/org/apache/lucene/search/PhraseQuery.java
index ff1538820d6..16642e51f11 100644
--- a/lucene/core/src/java/org/apache/lucene/search/PhraseQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/search/PhraseQuery.java
@@ -32,8 +32,8 @@ import org.apache.lucene.index.LeafReader;
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.index.PostingsEnum;
import org.apache.lucene.index.Term;
-import org.apache.lucene.index.TermStates;
import org.apache.lucene.index.TermState;
+import org.apache.lucene.index.TermStates;
import org.apache.lucene.index.Terms;
import org.apache.lucene.index.TermsEnum;
import org.apache.lucene.search.similarities.Similarity;
@@ -349,131 +349,6 @@ public class PhraseQuery extends Query {
}
}
- private class PhraseWeight extends Weight {
- private final Similarity similarity;
- private final Similarity.SimScorer stats;
- private final ScoreMode scoreMode;
- private transient TermStates states[];
-
- public PhraseWeight(IndexSearcher searcher, ScoreMode scoreMode, float boost)
- throws IOException {
- super(PhraseQuery.this);
- final int[] positions = PhraseQuery.this.getPositions();
- if (positions.length < 2) {
- throw new IllegalStateException("PhraseWeight does not support less than 2 terms, call rewrite first");
- } else if (positions[0] != 0) {
- throw new IllegalStateException("PhraseWeight requires that the first position is 0, call rewrite first");
- }
- this.scoreMode = scoreMode;
- this.similarity = searcher.getSimilarity();
- final IndexReaderContext context = searcher.getTopReaderContext();
- states = new TermStates[terms.length];
- TermStatistics termStats[] = new TermStatistics[terms.length];
- int termUpTo = 0;
- for (int i = 0; i < terms.length; i++) {
- final Term term = terms[i];
- states[i] = TermStates.build(context, term, scoreMode.needsScores());
- if (scoreMode.needsScores()) {
- TermStatistics termStatistics = searcher.termStatistics(term, states[i]);
- if (termStatistics != null) {
- termStats[termUpTo++] = termStatistics;
- }
- }
- }
- if (termUpTo > 0) {
- stats = similarity.scorer(boost, searcher.collectionStatistics(field), Arrays.copyOf(termStats, termUpTo));
- } else {
- stats = null; // no terms at all, we won't use similarity
- }
- }
-
- @Override
- public void extractTerms(Set<Term> queryTerms) {
- Collections.addAll(queryTerms, terms);
- }
-
- @Override
- public String toString() { return "weight(" + PhraseQuery.this + ")"; }
-
- @Override
- public Scorer scorer(LeafReaderContext context) throws IOException {
- assert terms.length > 0;
- final LeafReader reader = context.reader();
- PostingsAndFreq[] postingsFreqs = new PostingsAndFreq[terms.length];
-
- final Terms fieldTerms = reader.terms(field);
- if (fieldTerms == null) {
- return null;
- }
-
- if (fieldTerms.hasPositions() == false) {
- throw new IllegalStateException("field \"" + field + "\" was indexed without position data; cannot run PhraseQuery (phrase=" + getQuery() + ")");
- }
-
- // Reuse single TermsEnum below:
- final TermsEnum te = fieldTerms.iterator();
- float totalMatchCost = 0;
-
- for (int i = 0; i < terms.length; i++) {
- final Term t = terms[i];
- final TermState state = states[i].get(context);
- if (state == null) { /* term doesnt exist in this segment */
- assert termNotInReader(reader, t): "no termstate found but term exists in reader";
- return null;
- }
- te.seekExact(t.bytes(), state);
- PostingsEnum postingsEnum = te.postings(null, PostingsEnum.POSITIONS);
- postingsFreqs[i] = new PostingsAndFreq(postingsEnum, positions[i], t);
- totalMatchCost += termPositionsCost(te);
- }
-
- // sort by increasing docFreq order
- if (slop == 0) {
- ArrayUtil.timSort(postingsFreqs);
- }
-
- if (slop == 0) { // optimize exact case
- return new ExactPhraseScorer(this, postingsFreqs,
- new LeafSimScorer(stats, context.reader(), scoreMode.needsScores(), Integer.MAX_VALUE),
- scoreMode, totalMatchCost);
- } else {
- return new SloppyPhraseScorer(this, postingsFreqs, slop,
- new LeafSimScorer(stats, context.reader(), scoreMode.needsScores(), Float.MAX_VALUE),
- scoreMode.needsScores(), totalMatchCost);
- }
- }
-
- @Override
- public boolean isCacheable(LeafReaderContext ctx) {
- return true;
- }
-
- // only called from assert
- private boolean termNotInReader(LeafReader reader, Term term) throws IOException {
- return reader.docFreq(term) == 0;
- }
-
- @Override
- public Explanation explain(LeafReaderContext context, int doc) throws IOException {
- Scorer scorer = scorer(context);
- if (scorer != null) {
- int newDoc = scorer.iterator().advance(doc);
- if (newDoc == doc) {
- float freq = slop == 0 ? ((ExactPhraseScorer)scorer).freq() : ((SloppyPhraseScorer)scorer).sloppyFreq();
- LeafSimScorer docScorer = new LeafSimScorer(stats, context.reader(), scoreMode.needsScores(), Float.MAX_VALUE);
- Explanation freqExplanation = Explanation.match(freq, "phraseFreq=" + freq);
- Explanation scoreExplanation = docScorer.explain(doc, freqExplanation);
- return Explanation.match(
- scoreExplanation.getValue(),
- "weight("+getQuery()+" in "+doc+") [" + similarity.getClass().getSimpleName() + "], result of:",
- scoreExplanation);
- }
- }
-
- return Explanation.noMatch("no matching term");
- }
- }
-
/** A guess of
* the average number of simple operations for the initial seek and buffer refill
* per document for the positions of a term.
@@ -511,7 +386,91 @@ public class PhraseQuery extends Query {
@Override
public Weight createWeight(IndexSearcher searcher, ScoreMode scoreMode, float boost) throws IOException {
- return new PhraseWeight(searcher, scoreMode, boost);
+ return new PhraseWeight(this, field, searcher, scoreMode) {
+
+ private transient TermStates states[];
+
+ @Override
+ protected Similarity.SimScorer getStats(IndexSearcher searcher) throws IOException {
+ final int[] positions = PhraseQuery.this.getPositions();
+ if (positions.length < 2) {
+ throw new IllegalStateException("PhraseWeight does not support less than 2 terms, call rewrite first");
+ } else if (positions[0] != 0) {
+ throw new IllegalStateException("PhraseWeight requires that the first position is 0, call rewrite first");
+ }
+ final IndexReaderContext context = searcher.getTopReaderContext();
+ states = new TermStates[terms.length];
+ TermStatistics termStats[] = new TermStatistics[terms.length];
+ int termUpTo = 0;
+ for (int i = 0; i < terms.length; i++) {
+ final Term term = terms[i];
+ states[i] = TermStates.build(context, term, scoreMode.needsScores());
+ if (scoreMode.needsScores()) {
+ TermStatistics termStatistics = searcher.termStatistics(term, states[i]);
+ if (termStatistics != null) {
+ termStats[termUpTo++] = termStatistics;
+ }
+ }
+ }
+ if (termUpTo > 0) {
+ return similarity.scorer(boost, searcher.collectionStatistics(field), Arrays.copyOf(termStats, termUpTo));
+ } else {
+ return null; // no terms at all, we won't use similarity
+ }
+ }
+
+ @Override
+ protected PhraseMatcher getPhraseMatcher(LeafReaderContext context, boolean exposeOffsets) throws IOException {
+ assert terms.length > 0;
+ final LeafReader reader = context.reader();
+ PostingsAndFreq[] postingsFreqs = new PostingsAndFreq[terms.length];
+
+ final Terms fieldTerms = reader.terms(field);
+ if (fieldTerms == null) {
+ return null;
+ }
+
+ if (fieldTerms.hasPositions() == false) {
+ throw new IllegalStateException("field \"" + field + "\" was indexed without position data; cannot run PhraseQuery (phrase=" + getQuery() + ")");
+ }
+
+ // Reuse single TermsEnum below:
+ final TermsEnum te = fieldTerms.iterator();
+ float totalMatchCost = 0;
+
+ for (int i = 0; i < terms.length; i++) {
+ final Term t = terms[i];
+ final TermState state = states[i].get(context);
+ if (state == null) { /* term doesnt exist in this segment */
+ assert termNotInReader(reader, t): "no termstate found but term exists in reader";
+ return null;
+ }
+ te.seekExact(t.bytes(), state);
+ PostingsEnum postingsEnum = te.postings(null, exposeOffsets ? PostingsEnum.OFFSETS : PostingsEnum.POSITIONS);
+ postingsFreqs[i] = new PostingsAndFreq(postingsEnum, positions[i], t);
+ totalMatchCost += termPositionsCost(te);
+ }
+
+ // sort by increasing docFreq order
+ if (slop == 0) {
+ ArrayUtil.timSort(postingsFreqs);
+ return new ExactPhraseMatcher(postingsFreqs, totalMatchCost);
+ }
+ else {
+ return new SloppyPhraseMatcher(postingsFreqs, slop, totalMatchCost);
+ }
+ }
+
+ @Override
+ public void extractTerms(Set<Term> queryTerms) {
+ Collections.addAll(queryTerms, terms);
+ }
+ };
+ }
+
+ // only called from assert
+ private static boolean termNotInReader(LeafReader reader, Term term) throws IOException {
+ return reader.docFreq(term) == 0;
}
/** Prints a user-readable version of this query. */
diff --git a/lucene/core/src/java/org/apache/lucene/search/PhraseScorer.java b/lucene/core/src/java/org/apache/lucene/search/PhraseScorer.java
new file mode 100644
index 00000000000..4e6dab70b6d
--- /dev/null
+++ b/lucene/core/src/java/org/apache/lucene/search/PhraseScorer.java
@@ -0,0 +1,101 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+
+package org.apache.lucene.search;
+
+import java.io.IOException;
+
+class PhraseScorer extends Scorer {
+
+ final PhraseMatcher matcher;
+ final ScoreMode scoreMode;
+ private final LeafSimScorer simScorer;
+ final float matchCost;
+
+ private float minCompetitiveScore = 0;
+ private float freq = 0;
+
+ PhraseScorer(Weight weight, PhraseMatcher matcher, ScoreMode scoreMode, LeafSimScorer simScorer) {
+ super(weight);
+ this.matcher = matcher;
+ this.scoreMode = scoreMode;
+ this.simScorer = simScorer;
+ this.matchCost = matcher.getMatchCost();
+ }
+
+ @Override
+ public TwoPhaseIterator twoPhaseIterator() {
+ return new TwoPhaseIterator(matcher.approximation) {
+ @Override
+ public boolean matches() throws IOException {
+ matcher.reset();
+ if (scoreMode == ScoreMode.TOP_SCORES && minCompetitiveScore > 0) {
+ float maxFreq = matcher.maxFreq();
+ if (simScorer.score(docID(), maxFreq) < minCompetitiveScore) {
+ // The maximum score we could get is less than the min competitive score
+ return false;
+ }
+ }
+ freq = 0;
+ return matcher.nextMatch();
+ }
+
+ @Override
+ public float matchCost() {
+ return matchCost;
+ }
+ };
+ }
+
+ @Override
+ public int docID() {
+ return matcher.approximation.docID();
+ }
+
+ @Override
+ public float score() throws IOException {
+ if (freq == 0) {
+ freq = matcher.sloppyWeight();
+ while (matcher.nextMatch()) {
+ freq += matcher.sloppyWeight();
+ }
+ }
+ return simScorer.score(docID(), freq);
+ }
+
+ @Override
+ public DocIdSetIterator iterator() {
+ return TwoPhaseIterator.asDocIdSetIterator(twoPhaseIterator());
+ }
+
+ @Override
+ public void setMinCompetitiveScore(float minScore) {
+ this.minCompetitiveScore = minScore;
+ }
+
+ @Override
+ public float getMaxScore(int upTo) throws IOException {
+ return simScorer.maxScore();
+ }
+
+ @Override
+ public String toString() {
+ return "PhraseScorer(" + weight + ")";
+ }
+
+
+}
diff --git a/lucene/core/src/java/org/apache/lucene/search/PhraseWeight.java b/lucene/core/src/java/org/apache/lucene/search/PhraseWeight.java
new file mode 100644
index 00000000000..494003fa6f8
--- /dev/null
+++ b/lucene/core/src/java/org/apache/lucene/search/PhraseWeight.java
@@ -0,0 +1,124 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+
+package org.apache.lucene.search;
+
+import java.io.IOException;
+
+import org.apache.lucene.index.LeafReaderContext;
+import org.apache.lucene.search.similarities.Similarity;
+
+abstract class PhraseWeight extends Weight {
+
+ final ScoreMode scoreMode;
+ final Similarity.SimScorer stats;
+ final Similarity similarity;
+ final String field;
+
+ protected PhraseWeight(Query query, String field, IndexSearcher searcher, ScoreMode scoreMode) throws IOException {
+ super(query);
+ this.scoreMode = scoreMode;
+ this.field = field;
+ this.similarity = searcher.getSimilarity();
+ this.stats = getStats(searcher);
+ }
+
+ protected abstract Similarity.SimScorer getStats(IndexSearcher searcher) throws IOException;
+
+ protected abstract PhraseMatcher getPhraseMatcher(LeafReaderContext context, boolean exposeOffsets) throws IOException;
+
+ @Override
+ public Scorer scorer(LeafReaderContext context) throws IOException {
+ PhraseMatcher matcher = getPhraseMatcher(context, false);
+ if (matcher == null)
+ return null;
+ LeafSimScorer simScorer = new LeafSimScorer(stats, context.reader(), scoreMode.needsScores(), Integer.MAX_VALUE);
+ return new PhraseScorer(this, matcher, scoreMode, simScorer);
+ }
+
+ @Override
+ public Explanation explain(LeafReaderContext context, int doc) throws IOException {
+ PhraseMatcher matcher = getPhraseMatcher(context, false);
+ if (matcher == null || matcher.approximation.advance(doc) != doc) {
+ return Explanation.noMatch("no matching terms");
+ }
+ matcher.reset();
+ if (matcher.nextMatch() == false) {
+ return Explanation.noMatch("no matching phrase");
+ }
+ float freq = matcher.sloppyWeight();
+ while (matcher.nextMatch()) {
+ freq += matcher.sloppyWeight();
+ }
+ LeafSimScorer docScorer = new LeafSimScorer(stats, context.reader(), scoreMode.needsScores(), Float.MAX_VALUE);
+ Explanation freqExplanation = Explanation.match(freq, "phraseFreq=" + freq);
+ Explanation scoreExplanation = docScorer.explain(doc, freqExplanation);
+ return Explanation.match(
+ scoreExplanation.getValue(),
+ "weight("+getQuery()+" in "+doc+") [" + similarity.getClass().getSimpleName() + "], result of:",
+ scoreExplanation);
+ }
+
+ @Override
+ public Matches matches(LeafReaderContext context, int doc) throws IOException {
+ return Matches.forField(field, () -> {
+ PhraseMatcher matcher = getPhraseMatcher(context, true);
+ if (matcher == null || matcher.approximation.advance(doc) != doc) {
+ return null;
+ }
+ matcher.reset();
+ if (matcher.nextMatch() == false) {
+ return null;
+ }
+ return new MatchesIterator() {
+ boolean started = false;
+ @Override
+ public boolean next() throws IOException {
+ if (started == false) {
+ return started = true;
+ }
+ return matcher.nextMatch();
+ }
+
+ @Override
+ public int startPosition() {
+ return matcher.startPosition();
+ }
+
+ @Override
+ public int endPosition() {
+ return matcher.endPosition();
+ }
+
+ @Override
+ public int startOffset() throws IOException {
+ return matcher.startOffset();
+ }
+
+ @Override
+ public int endOffset() throws IOException {
+ return matcher.endOffset();
+ }
+ };
+ });
+ }
+
+ @Override
+ public boolean isCacheable(LeafReaderContext ctx) {
+ return true;
+ }
+}
diff --git a/lucene/core/src/java/org/apache/lucene/search/SloppyPhraseScorer.java b/lucene/core/src/java/org/apache/lucene/search/SloppyPhraseMatcher.java
similarity index 76%
rename from lucene/core/src/java/org/apache/lucene/search/SloppyPhraseScorer.java
rename to lucene/core/src/java/org/apache/lucene/search/SloppyPhraseMatcher.java
index 7587b37889b..85d4473d500 100644
--- a/lucene/core/src/java/org/apache/lucene/search/SloppyPhraseScorer.java
+++ b/lucene/core/src/java/org/apache/lucene/search/SloppyPhraseMatcher.java
@@ -24,95 +24,117 @@ import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
+import java.util.List;
import org.apache.lucene.index.Term;
import org.apache.lucene.util.FixedBitSet;
-final class SloppyPhraseScorer extends Scorer {
+/**
+ * Find all slop-valid position-combinations (matches)
+ * encountered while traversing/hopping the PhrasePositions.
+ * <br> The sloppy frequency contribution of a match depends on the distance:
+ * <br> - highest freq for distance=0 (exact match).
+ * <br> - freq gets lower as distance gets higher.
+ * <br>Example: for query "a b"~2, a document "x a b a y" can be matched twice:
+ * once for "a b" (distance=0), and once for "b a" (distance=2).
+ * <br>Possibly not all valid combinations are encountered, because for efficiency
+ * we always propagate the least PhrasePosition. This allows to base on
+ * PriorityQueue and move forward faster.
+ * As result, for example, document "a b c b a"
+ * would score differently for queries "a b c"~4 and "c b a"~4, although
+ * they really are equivalent.
+ * Similarly, for doc "a b c b a f g", query "c b"~2
+ * would get same score as "g f"~2, although "c b"~2 could be matched twice.
+ * We may want to fix this in the future (currently not, for performance reasons).
+ */
+final class SloppyPhraseMatcher extends PhraseMatcher {
- private final DocIdSetIterator conjunction;
private final PhrasePositions[] phrasePositions;
- private float sloppyFreq; //phrase frequency in current doc as computed by phraseFreq().
-
- private final LeafSimScorer docScorer;
-
private final int slop;
private final int numPostings;
private final PhraseQueue pq; // for advancing min position
-
- private int end; // current largest phrase position
+
+ private int end; // current largest phrase position
+
+ private int leadPosition;
+ private int leadOffset;
+ private int currentEndPostings;
+ private int advanceEndPostings;
private boolean hasRpts; // flag indicating that there are repetitions (as checked in first candidate doc)
private boolean checkedRpts; // flag to only check for repetitions in first candidate doc
private boolean hasMultiTermRpts; //
private PhrasePositions[][] rptGroups; // in each group are PPs that repeats each other (i.e. same term), sorted by (query) offset
private PhrasePositions[] rptStack; // temporary stack for switching colliding repeating pps
-
- private int numMatches;
- final boolean needsScores;
- private final float matchCost;
-
- SloppyPhraseScorer(Weight weight, PhraseQuery.PostingsAndFreq[] postings,
- int slop, LeafSimScorer docScorer, boolean needsScores,
- float matchCost) {
- super(weight);
- this.docScorer = docScorer;
- this.needsScores = needsScores;
+
+ private boolean positioned;
+ private int matchLength;
+
+ SloppyPhraseMatcher(PhraseQuery.PostingsAndFreq[] postings, int slop, float matchCost) {
+ super(approximation(postings), matchCost);
this.slop = slop;
- this.numPostings = postings==null ? 0 : postings.length;
+ this.numPostings = postings.length;
pq = new PhraseQueue(postings.length);
- DocIdSetIterator[] iterators = new DocIdSetIterator[postings.length];
phrasePositions = new PhrasePositions[postings.length];
for (int i = 0; i < postings.length; ++i) {
- iterators[i] = postings[i].postings;
phrasePositions[i] = new PhrasePositions(postings[i].postings, postings[i].position, i, postings[i].terms);
}
- conjunction = ConjunctionDISI.intersectIterators(Arrays.asList(iterators));
- assert TwoPhaseIterator.unwrap(conjunction) == null;
- this.matchCost = matchCost;
}
- /**
- * Score a candidate doc for all slop-valid position-combinations (matches)
- * encountered while traversing/hopping the PhrasePositions.
- * <br> The score contribution of a match depends on the distance:
- * <br> - highest score for distance=0 (exact match).
- * <br> - score gets lower as distance gets higher.
- * <br>Example: for query "a b"~2, a document "x a b a y" can be scored twice:
- * once for "a b" (distance=0), and once for "b a" (distance=2).
- * <br>Possibly not all valid combinations are encountered, because for efficiency
- * we always propagate the least PhrasePosition. This allows to base on
- * PriorityQueue and move forward faster.
- * As result, for example, document "a b c b a"
- * would score differently for queries "a b c"~4 and "c b a"~4, although
- * they really are equivalent.
- * Similarly, for doc "a b c b a f g", query "c b"~2
- * would get same score as "g f"~2, although "c b"~2 could be matched twice.
- * We may want to fix this in the future (currently not, for performance reasons).
- */
- private float phraseFreq() throws IOException {
- if (!initPhrasePositions()) {
- return 0.0f;
+ private static DocIdSetIterator approximation(PhraseQuery.PostingsAndFreq[] postings) {
+ List<DocIdSetIterator> iterators = new ArrayList<>();
+ for (PhraseQuery.PostingsAndFreq posting : postings) {
+ iterators.add(posting.postings);
+ }
+ return ConjunctionDISI.intersectIterators(iterators);
+ }
+
+ @Override
+ float maxFreq() throws IOException {
+ // every term position in each postings list can be at the head of at most
+ // one matching phrase, so the maximum possible phrase freq is the sum of
+ // the freqs of the postings lists.
+ float maxFreq = 0;
+ for (PhrasePositions phrasePosition : phrasePositions) {
+ maxFreq += phrasePosition.postings.freq();
+ }
+ return maxFreq;
+ }
+
+ @Override
+ public void reset() throws IOException {
+ this.positioned = initPhrasePositions();
+ this.matchLength = Integer.MAX_VALUE;
+ this.leadPosition = Integer.MAX_VALUE;
+ }
+
+ @Override
+ float sloppyWeight() {
+ return 1f / (1f + matchLength);
+ }
+
+ @Override
+ public boolean nextMatch() throws IOException {
+ if (!positioned) {
+ return false;
}
- float freq = 0.0f;
- numMatches = 0;
PhrasePositions pp = pq.pop();
- int matchLength = end - pp.position;
+ assert pp != null; // if the pq is empty, then positioned == false
+ leadPosition = pp.position + pp.offset;
+ leadOffset = pp.postings.startOffset();
+ currentEndPostings = advanceEndPostings;
+ matchLength = end - pp.position;
int next = pq.top().position;
while (advancePP(pp)) {
if (hasRpts && !advanceRpts(pp)) {
break; // pps exhausted
}
- if (pp.position > next) { // done minimizing current match-length
- if (matchLength <= slop) {
- freq += (1.0 / (1.0 + matchLength)); // score match
- numMatches++;
- if (!needsScores) {
- return freq;
- }
- }
+ if (pp.position > next) { // done minimizing current match-length
pq.add(pp);
+ if (matchLength <= slop) {
+ return true;
+ }
pp = pq.pop();
next = pq.top().position;
matchLength = end - pp.position;
@@ -122,12 +144,50 @@ final class SloppyPhraseScorer extends Scorer {
matchLength = matchLength2;
}
}
+ leadPosition = pp.position + pp.offset;
+ leadOffset = pp.postings.startOffset();
+ currentEndPostings = advanceEndPostings;
+ }
+ positioned = false;
+ return matchLength <= slop;
+ }
+
+ @Override
+ public int startPosition() {
+ // when a match is detected, the top postings is advanced until it has moved
+ // beyond its successor, to ensure that the match is of minimal width. This
+ // means that we need to record the lead position before it is advanced.
+ // However, the priority queue doesn't guarantee that the top postings is in fact the
+ // earliest in the list, so we need to cycle through all terms to check.
+ // this is slow, but Matches is slow anyway...
+ for (PhrasePositions pp : phrasePositions) {
+ leadPosition = Math.min(leadPosition, pp.position + pp.offset);
+ }
+ return leadPosition;
+ }
+
+ @Override
+ public int endPosition() {
+ return phrasePositions[currentEndPostings].position + phrasePositions[currentEndPostings].offset;
+ }
+
+ @Override
+ public int startOffset() throws IOException {
+ // when a match is detected, the top postings is advanced until it has moved
+ // beyond its successor, to ensure that the match is of minimal width. This
+ // means that we need to record the lead offset before it is advanced.
+ // However, the priority queue doesn't guarantee that the top postings is in fact the
+ // earliest in the list, so we need to cycle through all terms to check
+ // this is slow, but Matches is slow anyway...
+ for (PhrasePositions pp : phrasePositions) {
+ leadOffset = Math.min(leadOffset, pp.postings.startOffset());
}
- if (matchLength <= slop) {
- freq += (1.0 / (1.0 + matchLength)); // score match
- numMatches++;
- }
- return freq;
+ return leadOffset;
+ }
+
+ @Override
+ public int endOffset() throws IOException {
+ return phrasePositions[currentEndPostings].postings.endOffset();
}
/** advance a PhrasePosition and update 'end', return false if exhausted */
@@ -137,6 +197,12 @@ final class SloppyPhraseScorer extends Scorer {
}
if (pp.position > end) {
end = pp.position;
+ advanceEndPostings = pp.ord;
+ }
+ if (pp.position == end) {
+ if (pp.ord > advanceEndPostings) {
+ advanceEndPostings = pp.ord;
+ }
}
return true;
}
@@ -241,6 +307,12 @@ final class SloppyPhraseScorer extends Scorer {
pp.firstPosition();
if (pp.position > end) {
end = pp.position;
+ advanceEndPostings = pp.ord;
+ }
+ if (pp.position == end) {
+ if (pp.ord > advanceEndPostings) {
+ advanceEndPostings = pp.ord;
+ }
}
pq.add(pp);
}
@@ -270,6 +342,12 @@ final class SloppyPhraseScorer extends Scorer {
for (PhrasePositions pp : phrasePositions) { // iterate cyclic list: done once handled max
if (pp.position > end) {
end = pp.position;
+ advanceEndPostings = pp.ord;
+ }
+ if (pp.position == end) {
+ if (pp.ord > advanceEndPostings) {
+ advanceEndPostings = pp.ord;
+ }
}
pq.add(pp);
}
@@ -515,77 +593,4 @@ final class SloppyPhraseScorer extends Scorer {
return tg;
}
- int freq() {
- return numMatches;
- }
-
- float sloppyFreq() {
- return sloppyFreq;
- }
-
-// private void printQueue(PrintStream ps, PhrasePositions ext, String title) {
-// //if (min.doc != ?) return;
-// ps.println();
-// ps.println("---- "+title);
-// ps.println("EXT: "+ext);
-// PhrasePositions[] t = new PhrasePositions[pq.size()];
-// if (pq.size()>0) {
-// t[0] = pq.pop();
-// ps.println(" " + 0 + " " + t[0]);
-// for (int i=1; i<t.length; i++) {
-// t[i] = pq.pop();
-// assert t[i-1].position <= t[i].position;
-// ps.println(" " + i + " " + t[i]);
-// }
-// // add them back
-// for (int i=t.length-1; i>=0; i--) {
-// pq.add(t[i]);
-// }
-// }
-// }
-
-
- @Override
- public int docID() {
- return conjunction.docID();
- }
-
- @Override
- public float score() throws IOException {
- return docScorer.score(docID(), sloppyFreq);
- }
-
- @Override
- public float getMaxScore(int upTo) throws IOException {
- return docScorer.maxScore();
- }
-
- @Override
- public String toString() { return "scorer(" + weight + ")"; }
-
- @Override
- public TwoPhaseIterator twoPhaseIterator() {
- return new TwoPhaseIterator(conjunction) {
- @Override
- public boolean matches() throws IOException {
- sloppyFreq = phraseFreq(); // check for phrase
- return sloppyFreq != 0F;
- }
-
- @Override
- public float matchCost() {
- return matchCost;
- }
-
- @Override
- public String toString() {
- return "SloppyPhraseScorer@asTwoPhaseIterator(" + SloppyPhraseScorer.this + ")";
- }
- };
- }
-
- @Override
- public DocIdSetIterator iterator() {
- return TwoPhaseIterator.asDocIdSetIterator(twoPhaseIterator());
- }
}
diff --git a/lucene/core/src/test/org/apache/lucene/search/TestBooleanQuery.java b/lucene/core/src/test/org/apache/lucene/search/TestBooleanQuery.java
index b6da87dd5c5..8397d7cc2b2 100644
--- a/lucene/core/src/test/org/apache/lucene/search/TestBooleanQuery.java
+++ b/lucene/core/src/test/org/apache/lucene/search/TestBooleanQuery.java
@@ -679,7 +679,7 @@ public class TestBooleanQuery extends LuceneTestCase {
final Weight weight = searcher.createWeight(searcher.rewrite(q.build()), ScoreMode.COMPLETE, 1);
final Scorer scorer = weight.scorer(searcher.getIndexReader().leaves().get(0));
- assertTrue(scorer instanceof ExactPhraseScorer);
+ assertTrue(scorer instanceof PhraseScorer);
assertNotNull(scorer.twoPhaseIterator());
reader.close();
diff --git a/lucene/core/src/test/org/apache/lucene/search/TestBooleanScorer.java b/lucene/core/src/test/org/apache/lucene/search/TestBooleanScorer.java
index d847de64333..843c89b8c1a 100644
--- a/lucene/core/src/test/org/apache/lucene/search/TestBooleanScorer.java
+++ b/lucene/core/src/test/org/apache/lucene/search/TestBooleanScorer.java
@@ -23,8 +23,8 @@ import java.util.Set;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
-import org.apache.lucene.document.StringField;
import org.apache.lucene.document.Field.Store;
+import org.apache.lucene.document.StringField;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.index.RandomIndexWriter;
diff --git a/lucene/core/src/test/org/apache/lucene/search/TestMatchesIterator.java b/lucene/core/src/test/org/apache/lucene/search/TestMatchesIterator.java
index 185aad9be93..3855b04ad6b 100644
--- a/lucene/core/src/test/org/apache/lucene/search/TestMatchesIterator.java
+++ b/lucene/core/src/test/org/apache/lucene/search/TestMatchesIterator.java
@@ -95,6 +95,7 @@ public class TestMatchesIterator extends LuceneTestCase {
"w1 w3 w2 w3 zz",
"w1 xx w2 yy w4",
"w1 w2 w1 w4 w2 w3",
+ "a phrase sentence with many phrase sentence iterations of a phrase sentence",
"nothing matches this document"
};
@@ -122,10 +123,10 @@ public class TestMatchesIterator extends LuceneTestCase {
int pos = 1;
while (it.next()) {
//System.out.println(expected[i][pos] + "->" + expected[i][pos + 1] + "[" + expected[i][pos + 2] + "->" + expected[i][pos + 3] + "]");
- assertEquals(expected[pos], it.startPosition());
- assertEquals(expected[pos + 1], it.endPosition());
- assertEquals(expected[pos + 2], it.startOffset());
- assertEquals(expected[pos + 3], it.endOffset());
+ assertEquals("Wrong start position", expected[pos], it.startPosition());
+ assertEquals("Wrong end position", expected[pos + 1], it.endPosition());
+ assertEquals("Wrong start offset", expected[pos + 2], it.startOffset());
+ assertEquals("Wrong end offset", expected[pos + 3], it.endOffset());
pos += 4;
}
assertEquals(expected.length, pos);
@@ -388,4 +389,67 @@ public class TestMatchesIterator extends LuceneTestCase {
assertTrue(fields.contains("id"));
}
+ // 0 1 2 3 4 5 6 7
+ // "a phrase sentence with many phrase sentence iterations of a phrase sentence",
+
+ public void testSloppyPhraseQuery() throws IOException {
+ PhraseQuery pq = new PhraseQuery(4, FIELD_WITH_OFFSETS, "a", "sentence");
+ checkMatches(pq, FIELD_WITH_OFFSETS, new int[][]{
+ { 0 }, { 1 }, { 2 }, { 3 },
+ { 4, 0, 2, 0, 17, 6, 9, 35, 59, 9, 11, 58, 75 }
+ });
+ }
+
+ public void testExactPhraseQuery() throws IOException {
+ PhraseQuery pq = new PhraseQuery(FIELD_WITH_OFFSETS, "phrase", "sentence");
+ checkMatches(pq, FIELD_WITH_OFFSETS, new int[][]{
+ { 0 }, { 1 }, { 2 }, { 3 },
+ { 4, 1, 2, 2, 17, 5, 6, 28, 43, 10, 11, 60, 75 }
+ });
+
+ PhraseQuery pq2 = new PhraseQuery.Builder()
+ .add(new Term(FIELD_WITH_OFFSETS, "a"))
+ .add(new Term(FIELD_WITH_OFFSETS, "sentence"), 2)
+ .build();
+ checkMatches(pq2, FIELD_WITH_OFFSETS, new int[][]{
+ { 0 }, { 1 }, { 2 }, { 3 },
+ { 4, 0, 2, 0, 17, 9, 11, 58, 75 }
+ });
+ }
+
+ // 0 1 2 3 4 5 6 7
+ // "a phrase sentence with many phrase sentence iterations of a phrase sentence",
+
+ public void testSloppyMultiPhraseQuery() throws IOException {
+ MultiPhraseQuery mpq = new MultiPhraseQuery.Builder()
+ .add(new Term(FIELD_WITH_OFFSETS, "phrase"))
+ .add(new Term[]{ new Term(FIELD_WITH_OFFSETS, "sentence"), new Term(FIELD_WITH_OFFSETS, "iterations") })
+ .setSlop(4)
+ .build();
+ checkMatches(mpq, FIELD_WITH_OFFSETS, new int[][]{
+ { 0 }, { 1 }, { 2 }, { 3 },
+ { 4, 1, 2, 2, 17, 5, 7, 28, 54, 5, 7, 28, 54, 10, 11, 60, 75 }
+ });
+ }
+
+ public void testExactMultiPhraseQuery() throws IOException {
+ MultiPhraseQuery mpq = new MultiPhraseQuery.Builder()
+ .add(new Term(FIELD_WITH_OFFSETS, "sentence"))
+ .add(new Term[]{ new Term(FIELD_WITH_OFFSETS, "with"), new Term(FIELD_WITH_OFFSETS, "iterations") })
+ .build();
+ checkMatches(mpq, FIELD_WITH_OFFSETS, new int[][]{
+ { 0 }, { 1 }, { 2 }, { 3 },
+ { 4, 2, 3, 9, 22, 6, 7, 35, 54 }
+ });
+
+ MultiPhraseQuery mpq2 = new MultiPhraseQuery.Builder()
+ .add(new Term[]{ new Term(FIELD_WITH_OFFSETS, "a"), new Term(FIELD_WITH_OFFSETS, "many")})
+ .add(new Term(FIELD_WITH_OFFSETS, "phrase"))
+ .build();
+ checkMatches(mpq2, FIELD_WITH_OFFSETS, new int[][]{
+ { 0 }, { 1 }, { 2 }, { 3 },
+ { 4, 0, 1, 0, 8, 4, 5, 23, 34, 9, 10, 58, 66 }
+ });
+ }
+
}
diff --git a/lucene/core/src/test/org/apache/lucene/search/TestSloppyPhraseQuery.java b/lucene/core/src/test/org/apache/lucene/search/TestSloppyPhraseQuery.java
index 66ee0c56093..bee5126a790 100644
--- a/lucene/core/src/test/org/apache/lucene/search/TestSloppyPhraseQuery.java
+++ b/lucene/core/src/test/org/apache/lucene/search/TestSloppyPhraseQuery.java
@@ -195,10 +195,12 @@ public class TestSloppyPhraseQuery extends LuceneTestCase {
@Override
public void collect(int doc) throws IOException {
totalHits++;
- if (scorer instanceof SloppyPhraseScorer)
- max = Math.max(max, ((SloppyPhraseScorer)scorer).freq());
- else
- max = Math.max(max, ((ExactPhraseScorer)scorer).freq());
+ PhraseScorer ps = (PhraseScorer) scorer;
+ float freq = ps.matcher.sloppyWeight();
+ while (ps.matcher.nextMatch()) {
+ freq += ps.matcher.sloppyWeight();
+ }
+ max = Math.max(max, freq);
}
@Override
@@ -207,7 +209,7 @@ public class TestSloppyPhraseQuery extends LuceneTestCase {
}
}
- /** checks that no scores or freqs are infinite */
+ /** checks that no scores are infinite */
private void assertSaneScoring(PhraseQuery pq, IndexSearcher searcher) throws Exception {
searcher.search(pq, new SimpleCollector() {
Scorer scorer;
@@ -222,7 +224,6 @@ public class TestSloppyPhraseQuery extends LuceneTestCase {
@Override
public void collect(int doc) throws IOException {
- assertFalse(Float.isInfinite(((SloppyPhraseScorer)scorer).freq()));
assertFalse(Float.isInfinite(scorer.score()));
}