Apache Lucene open-source search software
DocValuesRangeIterator uses SkipBlockRangeIterator as its approximation (#15989)
Alan Woodward9582ee9b846f
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txtindex 43a28ba723e..134d529a038 100644--- a/lucene/CHANGES.txt+++ b/lucene/CHANGES.txt@@ -304,6 +304,9 @@ Improvements* GITHUB#15574: Introduce TopGroupsCollectorManager to parallelize search when using TopGroupsCollector. (Binlong Gao)+* GITHUB#15989: DocValuesRangeIterator always tries to use skipper-based block iteration+ as its approximation. (Alan Woodward)+Optimizations---------------------* GITHUB#15861: Optimise PhraseScorer by short circuiting non competitive documents in TOP_SCORES mode. (Prithvi S)diff --git a/lucene/core/src/java/org/apache/lucene/document/SortedNumericDocValuesRangeQuery.java b/lucene/core/src/java/org/apache/lucene/document/SortedNumericDocValuesRangeQuery.javaindex 132f1e3cfc9..64ceaa43c96 100644--- a/lucene/core/src/java/org/apache/lucene/document/SortedNumericDocValuesRangeQuery.java+++ b/lucene/core/src/java/org/apache/lucene/document/SortedNumericDocValuesRangeQuery.java@@ -28,6 +28,7 @@ import org.apache.lucene.index.SortedNumericDocValues;import org.apache.lucene.search.ConstantScoreScorerSupplier;import org.apache.lucene.search.ConstantScoreWeight;import org.apache.lucene.search.DocIdSetIterator;+import org.apache.lucene.search.DocValuesRangeIterator;import org.apache.lucene.search.FieldExistsQuery;import org.apache.lucene.search.IndexSearcher;import org.apache.lucene.search.MatchAllDocsQuery;@@ -39,7 +40,6 @@ import org.apache.lucene.search.Query;import org.apache.lucene.search.QueryVisitor;import org.apache.lucene.search.ScoreMode;import org.apache.lucene.search.ScorerSupplier;-import org.apache.lucene.search.SkipBlockRangeIterator;import org.apache.lucene.search.Sort;import org.apache.lucene.search.TwoPhaseIterator;import org.apache.lucene.search.Weight;@@ -137,140 +137,28 @@ final class SortedNumericDocValuesRangeQuery extends NumericDocValuesRangeQueryfinal NumericDocValues singleton = DocValues.unwrapSingleton(values);final DocValuesSkipper skipper = context.reader().getDocValuesSkipper(field);- if (singleton != null && skipper != null) {- final DocIdSetIterator psIterator =- getDocIdSetIteratorOrNullForPrimarySort(context.reader(), singleton, skipper);- if (psIterator != null) {- return ConstantScoreScorerSupplier.fromIterator(psIterator, score(), scoreMode, maxDoc);+ if (singleton != null) {+ if (skipper != null) {+ final DocIdSetIterator psIterator =+ getDocIdSetIteratorOrNullForPrimarySort(context.reader(), singleton, skipper);+ if (psIterator != null) {+ return ConstantScoreScorerSupplier.fromIterator(+ psIterator, score(), scoreMode, maxDoc);+ }}- }-- TwoPhaseIterator iterator;- if (skipper != null) {- // Use SkipBlockRangeIterator as the approximation: block-level skip- // filtering with no DV decoding. This exposes block skips to- // ConjunctionDISI so that when one field's block is NO, other fields- // never decode DV data for that block.- final SkipBlockRangeIterator skipApprox =- new SkipBlockRangeIterator(skipper, lowerValue, upperValue);- iterator =- new TwoPhaseIterator(skipApprox) {- private int cachedBlockEnd = -1;- private int cachedClassification = BLOCK_MAYBE;-- @Override- public boolean matches() throws IOException {- int blockMatch = classifyBlockCached();- if (blockMatch == BLOCK_YES) {- return true;- }- if (blockMatch == BLOCK_IF_DOC_HAS_VALUE) {- if (singleton != null) {- return singleton.advanceExact(skipApprox.docID());- } else {- return values.advanceExact(skipApprox.docID());- }- }- // MAYBE — need to decode DV and check the actual value.- if (singleton != null) {- if (singleton.advanceExact(skipApprox.docID())) {- final long value = singleton.longValue();- return value >= lowerValue && value <= upperValue;- }- } else {- if (values.advanceExact(skipApprox.docID())) {- for (int i = 0, cnt = values.docValueCount(); i < cnt; ++i) {- final long value = values.nextValue();- if (value < lowerValue) {- continue;- }- return value <= upperValue;- }- }- }- return false;- }-- @Override- public int docIDRunEnd() throws IOException {- if (classifyBlockCached() == BLOCK_YES) {- // Only report the current level-0 block as a run. The- // approximation's docIDRunEnd() may expand to higher levels- // that could be MAYBE, not YES.- return cachedBlockEnd + 1;- }- return super.docIDRunEnd();- }-- @Override- public float matchCost() {- return 3; // advanceExact + 2 comparisons- }-- private static final int BLOCK_MAYBE = 0;- private static final int BLOCK_YES = 1;- private static final int BLOCK_IF_DOC_HAS_VALUE = 2;-- private int classifyBlockCached() {- int blockEnd = skipper.maxDocID(0);- if (blockEnd != cachedBlockEnd) {- cachedBlockEnd = blockEnd;- cachedClassification = classifyBlock();- }- return cachedClassification;- }-- private int classifyBlock() {- long blockMin = skipper.minValue(0);- long blockMax = skipper.maxValue(0);- if (blockMin >= lowerValue && blockMax <= upperValue) {- if (skipper.docCount(0) == skipper.maxDocID(0) - skipper.minDocID(0) + 1) {- return BLOCK_YES;- }- return BLOCK_IF_DOC_HAS_VALUE;- }- return BLOCK_MAYBE;- }- };- } else if (singleton != null) {- iterator =- new TwoPhaseIterator(singleton) {- @Override- public boolean matches() throws IOException {- final long value = singleton.longValue();- return value >= lowerValue && value <= upperValue;- }-- @Override- public float matchCost() {- return 2; // 2 comparisons- }- };- } else {- iterator =- new TwoPhaseIterator(values) {- @Override- public boolean matches() throws IOException {- for (int i = 0, count = values.docValueCount(); i < count; ++i) {- final long value = values.nextValue();- if (value < lowerValue) {- continue;- }- // Values are sorted, so the first value that is >= lowerValue is our best- // candidate- return value <= upperValue;- }- return false; // all values were < lowerValue- }-- @Override- public float matchCost() {- return 2; // 2 comparisons- }- };+ return ConstantScoreScorerSupplier.fromIterator(+ TwoPhaseIterator.asDocIdSetIterator(+ DocValuesRangeIterator.forRange(singleton, skipper, lowerValue, upperValue)),+ score(),+ scoreMode,+ maxDoc);}return ConstantScoreScorerSupplier.fromIterator(- TwoPhaseIterator.asDocIdSetIterator(iterator), score(), scoreMode, maxDoc);+ TwoPhaseIterator.asDocIdSetIterator(+ DocValuesRangeIterator.forRange(values, skipper, lowerValue, upperValue)),+ score(),+ scoreMode,+ maxDoc);}@Overridediff --git a/lucene/core/src/java/org/apache/lucene/document/SortedSetDocValuesRangeQuery.java b/lucene/core/src/java/org/apache/lucene/document/SortedSetDocValuesRangeQuery.javaindex dd753c5f7ea..b87f8f72536 100644--- a/lucene/core/src/java/org/apache/lucene/document/SortedSetDocValuesRangeQuery.java+++ b/lucene/core/src/java/org/apache/lucene/document/SortedSetDocValuesRangeQuery.java@@ -169,7 +169,6 @@ final class SortedSetDocValuesRangeQuery extends Query {}final SortedDocValues singleton = DocValues.unwrapSingleton(values);- TwoPhaseIterator iterator;if (singleton != null) {if (skipper != null) {final DocIdSetIterator psIterator =@@ -179,46 +178,11 @@ final class SortedSetDocValuesRangeQuery extends Query {return psIterator;}}- iterator =- new TwoPhaseIterator(singleton) {- @Override- public boolean matches() throws IOException {- final long ord = singleton.ordValue();- return ord >= minOrd && ord <= maxOrd;- }-- @Override- public float matchCost() {- return 2; // 2 comparisons- }- };- } else {- iterator =- new TwoPhaseIterator(values) {- @Override- public boolean matches() throws IOException {- for (int i = 0; i < values.docValueCount(); i++) {- long ord = values.nextOrd();- if (ord < minOrd) {- continue;- }- // Values are sorted, so the first ord that is >= minOrd is our best- // candidate- return ord <= maxOrd;- }- return false; // all ords were < minOrd- }-- @Override- public float matchCost() {- return 2; // 2 comparisons- }- };- }- if (skipper != null) {- iterator = new DocValuesRangeIterator(iterator, skipper, minOrd, maxOrd, false);+ return TwoPhaseIterator.asDocIdSetIterator(+ DocValuesRangeIterator.forOrdinalRange(singleton, skipper, minOrd, maxOrd));}- return TwoPhaseIterator.asDocIdSetIterator(iterator);+ return TwoPhaseIterator.asDocIdSetIterator(+ DocValuesRangeIterator.forOrdinalRange(values, skipper, minOrd, maxOrd));}@Overridediff --git a/lucene/core/src/java/org/apache/lucene/search/DocValuesRangeIterator.java b/lucene/core/src/java/org/apache/lucene/search/DocValuesRangeIterator.javaindex b3b955978d1..918e7ffa580 100644--- a/lucene/core/src/java/org/apache/lucene/search/DocValuesRangeIterator.java+++ b/lucene/core/src/java/org/apache/lucene/search/DocValuesRangeIterator.java@@ -18,201 +18,322 @@ package org.apache.lucene.search;import java.io.IOException;import org.apache.lucene.index.DocValuesSkipper;+import org.apache.lucene.index.NumericDocValues;+import org.apache.lucene.index.SortedDocValues;+import org.apache.lucene.index.SortedNumericDocValues;+import org.apache.lucene.index.SortedSetDocValues;+import org.apache.lucene.index.TermsEnum;+import org.apache.lucene.util.IOBooleanSupplier;+import org.apache.lucene.util.LongBitSet;/**- * Wrapper around a {@link TwoPhaseIterator} for a doc-values range query that speeds things up by- * taking advantage of a {@link DocValuesSkipper}.+ * A {@link TwoPhaseIterator} over doc values that skips documents with values that lie outside a+ * specific range, using a {@link SkipBlockRangeIterator} as an approximation** @lucene.experimental*/-public final class DocValuesRangeIterator extends TwoPhaseIterator {-- enum Match {- /** None of the documents in the range match */- NO,- /** Document values need to be checked to verify matches */- MAYBE,- /** All documents in the range that have a value match */- IF_DOC_HAS_VALUE,- /** All docs in the range match */- YES;+public abstract sealed class DocValuesRangeIterator extends TwoPhaseIterator {++ /**+ * Creates a DocValuesRangeIterator over a NumericDocValues instance+ *+ * @param values the doc values+ * @param skipper an optional skipper to exclude non-matching blocks+ * @param min skip documents with values lower than this+ * @param max skip documents with values higher than this+ */+ public static DocValuesRangeIterator forRange(+ NumericDocValues values, DocValuesSkipper skipper, long min, long max) {+ IOBooleanSupplier check =+ () -> {+ long v = values.longValue();+ return v >= min && v <= max;+ };+ return skipper == null+ ? new DocValuesValueRangeIterator(values, check, 2)+ : new DocValuesBlockRangeIterator(+ values, new SkipBlockRangeIterator(skipper, min, max), check, 2, false);+ }++ /**+ * Creates a DocValuesRangeIterator over a SortedNumericDocValues instance+ *+ * @param values the doc values+ * @param skipper an optional skipper to exclude non-matching blocks+ * @param min skip documents with all values lower than this+ * @param max skip documents with all values higher than this+ */+ public static DocValuesRangeIterator forRange(+ SortedNumericDocValues values, DocValuesSkipper skipper, long min, long max) {+ IOBooleanSupplier check =+ () -> {+ for (int i = 0; i < values.docValueCount(); i++) {+ long v = values.nextValue();+ if (v >= min) {+ return v <= max;+ }+ }+ return false;+ };+ return skipper == null+ ? new DocValuesValueRangeIterator(values, check, 5)+ : new DocValuesBlockRangeIterator(+ values, new SkipBlockRangeIterator(skipper, min, max), check, 2, false);+ }++ /**+ * Creates a DocValuesRangeIterator over a SortedDocValues instance+ *+ * @param values the doc values+ * @param skipper an optional skipper to exclude non-matching blocks+ * @param min skip documents with ordinal values lower than this+ * @param max skip documents with ordinal values higher than this+ */+ public static DocValuesRangeIterator forOrdinalRange(+ SortedDocValues values, DocValuesSkipper skipper, long min, long max) {+ IOBooleanSupplier check =+ () -> {+ long ord = values.ordValue();+ return ord >= min && ord <= max;+ };+ return skipper == null+ ? new DocValuesValueRangeIterator(values, check, 2)+ : new DocValuesBlockRangeIterator(+ values, new SkipBlockRangeIterator(skipper, min, max), check, 2, false);+ }++ /**+ * Creates a DocValuesRangeIterator over a SortedSetDocValues instance+ *+ * @param values the doc values+ * @param skipper an optional skipper to exclude non-matching blocks+ * @param min skip documents with all ordinal values lower than this+ * @param max skip documents with all ordinal values higher than this+ */+ public static DocValuesRangeIterator forOrdinalRange(+ SortedSetDocValues values, DocValuesSkipper skipper, long min, long max) {+ IOBooleanSupplier check =+ () -> {+ for (int i = 0; i < values.docValueCount(); i++) {+ long v = values.nextOrd();+ if (v >= min) {+ return v <= max;+ }+ }+ return false;+ };+ return skipper == null+ ? new DocValuesValueRangeIterator(values, check, 5)+ : new DocValuesBlockRangeIterator(+ values, new SkipBlockRangeIterator(skipper, min, max), check, 5, false);+ }++ private record OrdinalSet(long min, long max, LongBitSet ords) {++ boolean disjoint(DocValuesSkipper skipper) {+ if (skipper == null) {+ return false;+ }+ return min > skipper.maxValue() || max < skipper.minValue();+ }+ }++ private static OrdinalSet buildOrdinalSet(TermsEnum termsEnum, long ordCount) throws IOException {+ if (termsEnum.next() == null) {+ return null;+ }+ // TODO can we be more memory efficient here? eg LongHashSet+ LongBitSet ords = new LongBitSet(ordCount);+ long min = termsEnum.ord();+ ords.set(min);+ long max = min;+ while (termsEnum.next() != null) {+ max = termsEnum.ord();+ ords.set(max);+ }+ return new OrdinalSet(min, max, ords);+ }++ /**+ * Creates a DocValuesRangeIterator over a SortedDocValues instance+ *+ * @param values the doc values+ * @param skipper an optional skipper to exclude non-matching blocks+ * @param terms a TermsEnum containing the ordinal values to match+ */+ public static DocValuesRangeIterator forOrdinalSet(+ SortedDocValues values, DocValuesSkipper skipper, TermsEnum terms) throws IOException {+ OrdinalSet ordinalSet = buildOrdinalSet(terms, values.getValueCount());+ if (ordinalSet == null || ordinalSet.disjoint(skipper)) {+ return new EmptyRangeIterator();+ }+ // TODO add check to OrdinalSet to detect if it can be converted to a range instead+ IOBooleanSupplier check = () -> ordinalSet.ords.get(values.ordValue());+ return skipper == null+ ? new DocValuesValueRangeIterator(values, check, 2)+ : new DocValuesBlockRangeIterator(+ values,+ new SkipBlockRangeIterator(skipper, ordinalSet.min, ordinalSet.max),+ check,+ 2,+ true);}- private final Approximation approximation;- private final TwoPhaseIterator innerTwoPhase;+ /**+ * Creates a DocValuesRangeIterator over a SortedSetDocValues instance+ *+ * @param values the doc values+ * @param skipper an optional skipper to exclude non-matching blocks+ * @param terms a TermsEnum containing the ordinal values to match+ */+ public static DocValuesRangeIterator forOrdinalSet(+ SortedSetDocValues values, DocValuesSkipper skipper, TermsEnum terms) throws IOException {+ OrdinalSet ordinalSet = buildOrdinalSet(terms, values.getValueCount());+ return forOrdinalSet(values, skipper, ordinalSet);+ }- public DocValuesRangeIterator(- TwoPhaseIterator twoPhase,+ /**+ * Creates a DocValuesRangeIterator over a SortedSetDocValues instance+ *+ * @param values the doc values+ * @param skipper an optional skipper to exclude non-matching blocks+ * @param minOrd skip documents with all ordinal values lower than this+ * @param maxOrd skip documents with all ordinal values higher than this+ * @param ords skip documents with all values not in this set+ */+ public static DocValuesRangeIterator forOrdinalSet(+ SortedSetDocValues values,DocValuesSkipper skipper,- long lowerValue,- long upperValue,- boolean queryRangeHasGaps) {- super(- queryRangeHasGaps- ? new RangeWithGapsApproximation(- twoPhase.approximation(), skipper, lowerValue, upperValue)- : new RangeNoGapsApproximation(- twoPhase.approximation(), skipper, lowerValue, upperValue));- this.approximation = (Approximation) approximation();- this.innerTwoPhase = twoPhase;+ long minOrd,+ long maxOrd,+ LongBitSet ords) {+ return forOrdinalSet(values, skipper, new OrdinalSet(minOrd, maxOrd, ords));}- abstract static class Approximation extends AbstractDocIdSetIterator {+ private static DocValuesRangeIterator forOrdinalSet(+ SortedSetDocValues values, DocValuesSkipper skipper, OrdinalSet ordinalSet) {+ if (ordinalSet == null || ordinalSet.disjoint(skipper)) {+ return new EmptyRangeIterator();+ }+ IOBooleanSupplier check =+ () -> {+ for (int i = 0; i < values.docValueCount(); i++) {+ long v = values.nextOrd();+ if (v > ordinalSet.max) {+ return false;+ }+ if (v >= ordinalSet.min && ordinalSet.ords.get(v)) {+ return true;+ }+ }+ return false;+ };+ return skipper == null+ ? new DocValuesValueRangeIterator(values, check, 5)+ : new DocValuesBlockRangeIterator(+ values,+ new SkipBlockRangeIterator(skipper, ordinalSet.min, ordinalSet.max),+ check,+ 5,+ true);+ }- private final DocIdSetIterator innerApproximation;+ private static final class DocValuesBlockRangeIterator extends DocValuesRangeIterator {- protected final DocValuesSkipper skipper;- protected final long lowerValue;- protected final long upperValue;+ private final SkipBlockRangeIterator blockIterator;+ private final DocIdSetIterator disi;+ private final IOBooleanSupplier predicate;+ private final float matchCost;+ private final boolean alwaysCheckPredicate;- // Track a decision for all doc IDs between the current doc ID and upTo inclusive.- Match match = Match.MAYBE;- int upTo;+ private DocValuesBlockRangeIterator(+ DocIdSetIterator disi,+ SkipBlockRangeIterator blockIterator,+ IOBooleanSupplier predicate,+ float matchCost,+ boolean alwaysCheckPredicate) {+ super(blockIterator);+ this.disi = disi;+ this.blockIterator = blockIterator;+ this.predicate = predicate;+ this.matchCost = matchCost;+ this.alwaysCheckPredicate = alwaysCheckPredicate;+ }- Approximation(- DocIdSetIterator innerApproximation,- DocValuesSkipper skipper,- long lowerValue,- long upperValue) {- this.innerApproximation = innerApproximation;- this.skipper = skipper;- this.lowerValue = lowerValue;- this.upperValue = upperValue;- this.upTo = skipper.maxDocID(0);+ private boolean advanceDisi(int target) throws IOException {+ if (disi.docID() >= target) {+ return disi.docID() == target;+ }+ return disi.advance(target) == target;}@Override- public int nextDoc() throws IOException {- return advance(docID() + 1);+ public boolean matches() throws IOException {+ if (alwaysCheckPredicate) {+ return advanceDisi(blockIterator.docID()) && predicate.get();+ }+ return switch (blockIterator.getMatch()) {+ case YES -> true;+ case YES_IF_PRESENT -> advanceDisi(blockIterator.docID());+ case MAYBE -> advanceDisi(blockIterator.docID()) && predicate.get();+ };}@Override- public int advance(int target) throws IOException {- while (true) {- if (target > upTo) {- skipper.advance(target);- // If target doesn't have a value and is between two blocks, it is possible that advance()- // moved to a block that doesn't contain `target`.- target = Math.max(target, skipper.minDocID(0));- if (target == NO_MORE_DOCS) {- return doc = NO_MORE_DOCS;- }- upTo = skipper.maxDocID(0);- match = match(0);-- // If we have a YES or NO decision, see if we still have the same decision on a higher- // level (= on a wider range of doc IDs)- int nextLevel = 1;- while (match != Match.MAYBE- && nextLevel < skipper.numLevels()- && match == match(nextLevel)) {- upTo = skipper.maxDocID(nextLevel);- nextLevel++;- }- }- switch (match) {- case YES:- return doc = target;- case MAYBE:- case IF_DOC_HAS_VALUE:- if (target > innerApproximation.docID()) {- target = innerApproximation.advance(target);- }- if (target <= upTo) {- return doc = target;- }- // Otherwise we are breaking the invariant that `doc` must always be <= upTo, so let- // the loop run one more iteration to advance the skipper.- break;- case NO:- if (upTo == DocIdSetIterator.NO_MORE_DOCS) {- return doc = NO_MORE_DOCS;- }- target = upTo + 1;- break;- default:- throw new AssertionError("Unknown enum constant: " + match);- }+ public int docIDRunEnd() throws IOException {+ if (alwaysCheckPredicate) {+ return blockIterator.docID() + 1;}+ return blockIterator.docIDRunEnd();}@Override- public long cost() {- return innerApproximation.cost();+ public float matchCost() {+ return matchCost;}-- protected abstract Match match(int level);}- private static final class RangeNoGapsApproximation extends Approximation {+ private static final class DocValuesValueRangeIterator extends DocValuesRangeIterator {++ private final IOBooleanSupplier predicate;+ private final float matchCost;- RangeNoGapsApproximation(- DocIdSetIterator innerApproximation,- DocValuesSkipper skipper,- long lowerValue,- long upperValue) {- super(innerApproximation, skipper, lowerValue, upperValue);+ private DocValuesValueRangeIterator(+ DocIdSetIterator disi, IOBooleanSupplier predicate, float matchCost) {+ super(disi);+ this.predicate = predicate;+ this.matchCost = matchCost;}@Override- protected Match match(int level) {- long minValue = skipper.minValue(level);- long maxValue = skipper.maxValue(level);- if (minValue > upperValue || maxValue < lowerValue) {- return Match.NO;- } else if (minValue >= lowerValue && maxValue <= upperValue) {- if (skipper.docCount(level) == skipper.maxDocID(level) - skipper.minDocID(level) + 1) {- return Match.YES;- } else {- return Match.IF_DOC_HAS_VALUE;- }- } else {- return Match.MAYBE;- }+ public boolean matches() throws IOException {+ return predicate.get();+ }++ @Override+ public float matchCost() {+ return matchCost;}}- private static final class RangeWithGapsApproximation extends Approximation {+ private static final class EmptyRangeIterator extends DocValuesRangeIterator {- RangeWithGapsApproximation(- DocIdSetIterator innerApproximation,- DocValuesSkipper skipper,- long lowerValue,- long upperValue) {- super(innerApproximation, skipper, lowerValue, upperValue);+ private EmptyRangeIterator() {+ super(DocIdSetIterator.empty());}@Override- protected Match match(int level) {- long minValue = skipper.minValue(level);- long maxValue = skipper.maxValue(level);- if (minValue > upperValue || maxValue < lowerValue) {- return Match.NO;- } else {- return Match.MAYBE;- }+ public boolean matches() throws IOException {+ return false;}- }- @Override- public final boolean matches() throws IOException {- return switch (approximation.match) {- case YES, IF_DOC_HAS_VALUE -> true;- case MAYBE -> innerTwoPhase.matches();- case NO -> throw new IllegalStateException("Unpositioned approximation");- };- }-- @Override- public int docIDRunEnd() throws IOException {- if (approximation.match == Match.YES) {- return approximation.upTo + 1;+ @Override+ public float matchCost() {+ return 0;}- return super.docIDRunEnd();}- @Override- public float matchCost() {- return innerTwoPhase.matchCost();+ private DocValuesRangeIterator(DocIdSetIterator approximation) {+ super(approximation);}}diff --git a/lucene/core/src/java/org/apache/lucene/search/DocValuesRewriteMethod.java b/lucene/core/src/java/org/apache/lucene/search/DocValuesRewriteMethod.javaindex eb4d0625940..06ae9ae6099 100644--- a/lucene/core/src/java/org/apache/lucene/search/DocValuesRewriteMethod.java+++ b/lucene/core/src/java/org/apache/lucene/search/DocValuesRewriteMethod.java@@ -24,7 +24,6 @@ import org.apache.lucene.index.SortedDocValues;import org.apache.lucene.index.SortedSetDocValues;import org.apache.lucene.index.Terms;import org.apache.lucene.index.TermsEnum;-import org.apache.lucene.util.LongBitSet;/*** Rewrites MultiTermQueries into a filter, using DocValues for term enumeration.@@ -161,76 +160,18 @@ public final class DocValuesRewriteMethod extends MultiTermQuery.RewriteMethod {// query with the values present in the doc values:TermsEnum termsEnum = getTermsEnum(values);assert termsEnum != null;-- if (termsEnum.next() == null) {- // no matching terms- return new ConstantScoreScorer(score(), scoreMode, DocIdSetIterator.empty());- }-// Leverage a DV skipper if one was indexed for the field:DocValuesSkipper skipper = context.reader().getDocValuesSkipper(query.field);-- // Create a bit set for the "term set" ordinals (these are the terms provided by the- // query that are actually present in the doc values field). Cannot use FixedBitSet- // because we require long index (ord):- final LongBitSet termSet = new LongBitSet(values.getValueCount());- long minOrd = termsEnum.ord();- assert minOrd >= 0;- long maxOrd = -1;- do {- long ord = termsEnum.ord();- assert ord >= 0 && ord > maxOrd;- maxOrd = ord;- termSet.set(ord);- } while (termsEnum.next() != null);-- if (skipper != null && (minOrd > skipper.maxValue() || maxOrd < skipper.minValue())) {- return new ConstantScoreScorer(score(), scoreMode, DocIdSetIterator.empty());- }-- final SortedDocValues singleton = DocValues.unwrapSingleton(values);- TwoPhaseIterator iterator;- final long max = maxOrd;- if (singleton != null) {- iterator =- new TwoPhaseIterator(singleton) {- @Override- public boolean matches() throws IOException {- return termSet.get(singleton.ordValue());- }-- @Override- public float matchCost() {- return 3; // lookup in a bitset- }- };- } else {- iterator =- new TwoPhaseIterator(values) {- @Override- public boolean matches() throws IOException {- for (int i = 0; i < values.docValueCount(); i++) {- long value = values.nextOrd();- if (value > max) {- return false; // values are sorted, terminate- } else if (termSet.get(value)) {- return true;- }- }- return false;- }-- @Override- public float matchCost() {- return 3; // lookup in a bitset- }- };- }-- if (skipper != null) {- iterator = new DocValuesRangeIterator(iterator, skipper, minOrd, maxOrd, true);- }- return new ConstantScoreScorer(score(), scoreMode, iterator);+ SortedDocValues singleton = DocValues.unwrapSingleton(values);+ return singleton == null+ ? new ConstantScoreScorer(+ score(),+ scoreMode,+ DocValuesRangeIterator.forOrdinalSet(values, skipper, termsEnum))+ : new ConstantScoreScorer(+ score(),+ scoreMode,+ DocValuesRangeIterator.forOrdinalSet(singleton, skipper, termsEnum));}@Overridediff --git a/lucene/core/src/java/org/apache/lucene/search/SkipBlockRangeIterator.java b/lucene/core/src/java/org/apache/lucene/search/SkipBlockRangeIterator.javaindex fa58efc3690..be4bb2b9ed1 100644--- a/lucene/core/src/java/org/apache/lucene/search/SkipBlockRangeIterator.java+++ b/lucene/core/src/java/org/apache/lucene/search/SkipBlockRangeIterator.java@@ -27,10 +27,22 @@ import org.apache.lucene.util.FixedBitSet;*/public class SkipBlockRangeIterator extends AbstractDocIdSetIterator {+ /** The match state of the current positioned block */+ public enum Match {+ /** All documents in the block match */+ YES,+ /** All documents in the block with a value match */+ YES_IF_PRESENT,+ /** Some of the documents in the block match */+ MAYBE+ }+private final DocValuesSkipper skipper;private final long minValue;private final long maxValue;+ private Match match = Match.MAYBE;+/*** Creates a new SkipBlockRangeIterator*@@ -66,7 +78,32 @@ public class SkipBlockRangeIterator extends AbstractDocIdSetIterator {// Find the next matching block (could be the current block)skipper.advance(minValue, maxValue);- return doc = Math.max(target, skipper.minDocID(0));+ int nextDoc = Math.max(target, skipper.minDocID(0));+ if (nextDoc == DocIdSetIterator.NO_MORE_DOCS) {+ this.match = Match.MAYBE;+ } else {+ this.match = classifyBlock();+ }+ return doc = nextDoc;+ }++ private Match classifyBlock() {+ if (skipper.minValue(0) >= minValue && skipper.maxValue(0) <= maxValue) {+ if (skipper.maxDocID(0) - skipper.minDocID(0) == skipper.docCount(0) - 1) {+ return Match.YES;+ }+ return Match.YES_IF_PRESENT;+ }+ return Match.MAYBE;+ }++ /**+ * Returns the match state of the current positioned block+ *+ * <p>Should only be called when the iterator is positioned+ */+ public Match getMatch() {+ return match;}@Override@@ -76,11 +113,14 @@ public class SkipBlockRangeIterator extends AbstractDocIdSetIterator {@Overridepublic int docIDRunEnd() throws IOException {+ if (match != Match.YES) {+ return doc + 1;+ }int maxDoc = skipper.maxDocID(0);int nextLevel = 1;while (nextLevel < skipper.numLevels()- && skipper.minValue(nextLevel) < maxValue- && skipper.maxValue(nextLevel) > minValue) {+ && skipper.minValue(nextLevel) >= minValue+ && skipper.maxValue(nextLevel) <= maxValue) {maxDoc = skipper.maxDocID(nextLevel);nextLevel++;}diff --git a/lucene/core/src/test/org/apache/lucene/search/BaseDocValuesSkipperTests.java b/lucene/core/src/test/org/apache/lucene/search/BaseDocValuesSkipperTests.javaindex 6e1f5430e0e..cfcd465d642 100644--- a/lucene/core/src/test/org/apache/lucene/search/BaseDocValuesSkipperTests.java+++ b/lucene/core/src/test/org/apache/lucene/search/BaseDocValuesSkipperTests.java@@ -137,32 +137,27 @@ public abstract class BaseDocValuesSkipperTests extends LuceneTestCase {}@Override- @SuppressWarnings("DuplicateBranches")public long minValue(int level) {- int d = doc % 1024;- if (d < 128) {- return queryMin;- } else if (d < 256) {- return queryMax + 1;- } else if (d < 768) {- return queryMin - 1;- } else {- return queryMin - 1;- }+ int dStart = minDocID(level) % 1024;+ int dEnd = maxDocID(level) % 1024;+ long min = Long.MAX_VALUE;+ if (dStart <= 127 && dEnd >= 0) min = Math.min(min, queryMin);+ if (dStart <= 255 && dEnd >= 128) min = Math.min(min, queryMax + 1);+ if (dStart <= 511 && dEnd >= 256) min = Math.min(min, queryMin - 1);+ if (dEnd >= 512) min = Math.min(min, queryMin - 1);+ return min;}@Overridepublic long maxValue(int level) {- int d = doc % 1024;- if (d < 128) {- return queryMax;- } else if (d < 256) {- return queryMax + 1;- } else if (d < 768) {- return queryMin - 1;- } else {- return queryMax + 1;- }+ int dStart = minDocID(level) % 1024;+ int dEnd = maxDocID(level) % 1024;+ long max = Long.MIN_VALUE;+ if (dStart <= 127 && dEnd >= 0) max = Math.max(max, queryMax);+ if (dStart <= 255 && dEnd >= 128) max = Math.max(max, queryMax + 1);+ if (dStart <= 511 && dEnd >= 256) max = Math.max(max, queryMin - 1);+ if (dEnd >= 512) max = Math.max(max, queryMax + 1);+ return max;}@Overridediff --git a/lucene/core/src/test/org/apache/lucene/search/TestDocValuesOrdinalRangeIterator.java b/lucene/core/src/test/org/apache/lucene/search/TestDocValuesOrdinalRangeIterator.javanew file mode 100644index 00000000000..e3c860b8d8e--- /dev/null+++ b/lucene/core/src/test/org/apache/lucene/search/TestDocValuesOrdinalRangeIterator.java@@ -0,0 +1,493 @@+/*+ * 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 java.util.ArrayList;+import java.util.List;+import org.apache.lucene.index.DocValuesSkipper;+import org.apache.lucene.index.SortedDocValues;+import org.apache.lucene.index.SortedSetDocValues;+import org.apache.lucene.util.BytesRef;++/**+ * Tests {@link DocValuesRangeIterator#forOrdinalRange} for both single-valued ({@link+ * SortedDocValues}) and multi-valued ({@link SortedSetDocValues}) ordinals. Parallel to {@link+ * TestDocValuesRangeIterator} and {@link TestSortedNumericDocValuesRangeIterator}.+ */+public class TestDocValuesOrdinalRangeIterator extends BaseDocValuesSkipperTests {++ private static final long QUERY_MIN = 10;+ private static final long QUERY_MAX = 20;++ // ---- Shared helpers ----++ private static boolean docHasValue(int doc) {+ return doc < 1024 || (doc < 2048 && (doc & 1) == 0);+ }++ private static List<Integer> collectMatches(DocValuesRangeIterator iter) throws IOException {+ List<Integer> matches = new ArrayList<>();+ DocIdSetIterator approx = iter.approximation();+ while (approx.nextDoc() != DocIdSetIterator.NO_MORE_DOCS) {+ if (iter.matches()) {+ matches.add(approx.docID());+ }+ }+ return matches;+ }++ // ==========================================================================+ // SortedDocValues (single-valued ordinals)+ // ==========================================================================++ private static int singleOrdinal(int doc, long queryMin, long queryMax) {+ int d = doc % 1024;+ if (d < 128) {+ return (int) ((queryMin + queryMax) >> 1);+ } else if (d < 256) {+ return (int) (queryMax + 1);+ } else if (d < 512) {+ return (int) (queryMin - 1);+ } else {+ return switch ((d / 2) % 3) {+ case 0 -> (int) (queryMin - 1);+ case 1 -> (int) (queryMax + 1);+ case 2 -> (int) ((queryMin + queryMax) >> 1);+ default -> throw new AssertionError();+ };+ }+ }++ private static boolean singleOrdInRange(int doc) {+ int ord = singleOrdinal(doc, QUERY_MIN, QUERY_MAX);+ return ord >= QUERY_MIN && ord <= QUERY_MAX;+ }++ private static List<Integer> expectedSingleOrdMatches() {+ List<Integer> matches = new ArrayList<>();+ for (int doc = 0; doc < 2048; doc++) {+ if (docHasValue(doc) && singleOrdInRange(doc)) {+ matches.add(doc);+ }+ }+ return matches;+ }++ private static SortedDocValues sortedDocValues(long queryMin, long queryMax) {+ return new SortedDocValues() {+ int doc = -1;++ @Override+ public int ordValue() {+ return singleOrdinal(doc, queryMin, queryMax);+ }++ @Override+ public BytesRef lookupOrd(int ord) {+ throw new UnsupportedOperationException();+ }++ @Override+ public int getValueCount() {+ return (int) (queryMax + 10);+ }++ @Override+ public boolean advanceExact(int target) {+ throw new UnsupportedOperationException();+ }++ @Override+ public int docID() {+ return doc;+ }++ @Override+ public int nextDoc() throws IOException {+ return advance(doc + 1);+ }++ @Override+ public int advance(int target) {+ if (target < 1024) {+ return doc = target;+ } else if (target < 2048) {+ doc = target + (target & 1);+ return doc < 2048 ? doc : (doc = DocIdSetIterator.NO_MORE_DOCS);+ } else {+ return doc = DocIdSetIterator.NO_MORE_DOCS;+ }+ }++ @Override+ public long cost() {+ return 42;+ }+ };+ }++ private DocValuesRangeIterator createSortedDocValuesIterator(boolean multiLevel) {+ SortedDocValues values = sortedDocValues(QUERY_MIN, QUERY_MAX);+ DocValuesSkipper skipper = docValuesSkipper(QUERY_MIN, QUERY_MAX, multiLevel);+ return DocValuesRangeIterator.forOrdinalRange(values, skipper, QUERY_MIN, QUERY_MAX);+ }++ // --- SortedDocValues: Correctness ---++ public void testSortedDocValuesCorrectResultsSingleLevel() throws IOException {+ assertEquals(expectedSingleOrdMatches(), collectMatches(createSortedDocValuesIterator(false)));+ }++ public void testSortedDocValuesCorrectResultsMultipleLevels() throws IOException {+ assertEquals(expectedSingleOrdMatches(), collectMatches(createSortedDocValuesIterator(true)));+ }++ // --- SortedDocValues: Approximation skipping ---++ public void testSortedDocValuesApproximationSkips() throws IOException {+ DocValuesRangeIterator iter = createSortedDocValuesIterator(true);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();++ assertEquals(512, approx.advance(128));+ assertEquals(1536, approx.advance(1200));+ assertEquals(DocIdSetIterator.NO_MORE_DOCS, approx.advance(2048));+ }++ // --- SortedDocValues: Match classification ---++ public void testSortedDocValuesYesMatch() throws IOException {+ DocValuesRangeIterator iter = createSortedDocValuesIterator(true);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();++ approx.advance(0);+ assertEquals(SkipBlockRangeIterator.Match.YES, approx.getMatch());+ assertTrue(iter.matches());+ }++ public void testSortedDocValuesMaybeMatch() throws IOException {+ DocValuesRangeIterator iter = createSortedDocValuesIterator(true);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();++ approx.advance(512);+ assertEquals(SkipBlockRangeIterator.Match.MAYBE, approx.getMatch());++ // d=512: (512/2)%3 = 1 → ord above range+ assertFalse(iter.matches());++ // d=514: (514/2)%3 = 2 → ord in range+ approx.advance(514);+ assertTrue(iter.matches());++ // d=516: (516/2)%3 = 0 → ord below range+ approx.advance(516);+ assertFalse(iter.matches());+ }++ public void testSortedDocValuesYesIfPresent() throws IOException {+ DocValuesRangeIterator iter = createSortedDocValuesIterator(true);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();++ approx.advance(1024);+ assertEquals(SkipBlockRangeIterator.Match.YES_IF_PRESENT, approx.getMatch());+ assertTrue(iter.matches());++ approx.advance(1025);+ assertFalse(iter.matches());+ }++ // --- SortedDocValues: docIdRunEnd ---++ public void testSortedDocValuesDocIdRunEnd() throws IOException {+ DocValuesRangeIterator iter = createSortedDocValuesIterator(true);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();++ approx.advance(0);+ assertEquals(128, iter.docIDRunEnd());++ approx.advance(64);+ assertEquals(128, iter.docIDRunEnd());++ approx.advance(512);+ assertEquals(513, iter.docIDRunEnd());++ approx.advance(1024);+ assertEquals(1025, iter.docIDRunEnd());+ }++ // ==========================================================================+ // SortedSetDocValues (multi-valued ordinals)+ // ==========================================================================++ /**+ * Returns the two sorted ordinals for a given doc. Same block-level min/max as the single-valued+ * case, but with multi-value behaviors:+ *+ * <ul>+ * <li>Case 0 (mixed region): ords bracket the range — no match+ * <li>Case 1 (mixed region): first ord in range — immediate match+ * <li>Case 2 (mixed region): only second ord in range — match via iteration+ * </ul>+ */+ private static long[] ordinalPair(int doc, long queryMin, long queryMax) {+ int d = doc % 1024;+ long mid = (queryMin + queryMax) >> 1;+ if (d < 128) {+ return new long[] {queryMin, queryMax};+ } else if (d < 256) {+ return new long[] {queryMax + 1, queryMax + 1};+ } else if (d < 512) {+ return new long[] {queryMin - 1, queryMin - 1};+ } else {+ return switch ((d / 2) % 3) {+ case 0 -> new long[] {queryMin - 1, queryMax + 1};+ case 1 -> new long[] {queryMin, queryMax + 1};+ case 2 -> new long[] {queryMin - 1, mid};+ default -> throw new AssertionError();+ };+ }+ }++ private static boolean multiOrdInRange(int doc) {+ long[] ords = ordinalPair(doc, QUERY_MIN, QUERY_MAX);+ for (long ord : ords) {+ if (ord >= QUERY_MIN && ord <= QUERY_MAX) {+ return true;+ }+ }+ return false;+ }++ private static List<Integer> expectedMultiOrdMatches() {+ List<Integer> matches = new ArrayList<>();+ for (int doc = 0; doc < 2048; doc++) {+ if (docHasValue(doc) && multiOrdInRange(doc)) {+ matches.add(doc);+ }+ }+ return matches;+ }++ private static SortedSetDocValues sortedSetDocValues(long queryMin, long queryMax) {+ return new SortedSetDocValues() {+ int doc = -1;+ int ordIdx = 0;++ @Override+ public long nextOrd() {+ long[] ords = ordinalPair(doc, queryMin, queryMax);+ return ords[ordIdx++];+ }++ @Override+ public int docValueCount() {+ return 2;+ }++ @Override+ public BytesRef lookupOrd(long ord) {+ throw new UnsupportedOperationException();+ }++ @Override+ public long getValueCount() {+ return queryMax + 10;+ }++ @Override+ public boolean advanceExact(int target) {+ throw new UnsupportedOperationException();+ }++ @Override+ public int docID() {+ return doc;+ }++ @Override+ public int nextDoc() throws IOException {+ return advance(doc + 1);+ }++ @Override+ public int advance(int target) {+ ordIdx = 0;+ if (target < 1024) {+ return doc = target;+ } else if (target < 2048) {+ doc = target + (target & 1);+ return doc < 2048 ? doc : (doc = DocIdSetIterator.NO_MORE_DOCS);+ } else {+ return doc = DocIdSetIterator.NO_MORE_DOCS;+ }+ }++ @Override+ public long cost() {+ return 42;+ }+ };+ }++ private DocValuesRangeIterator createSortedSetDocValuesIterator(boolean multiLevel) {+ SortedSetDocValues values = sortedSetDocValues(QUERY_MIN, QUERY_MAX);+ DocValuesSkipper skipper = docValuesSkipper(QUERY_MIN, QUERY_MAX, multiLevel);+ return DocValuesRangeIterator.forOrdinalRange(values, skipper, QUERY_MIN, QUERY_MAX);+ }++ // --- SortedSetDocValues: Correctness ---++ public void testSortedSetDocValuesCorrectResultsSingleLevel() throws IOException {+ assertEquals(+ expectedMultiOrdMatches(), collectMatches(createSortedSetDocValuesIterator(false)));+ }++ public void testSortedSetDocValuesCorrectResultsMultipleLevels() throws IOException {+ assertEquals(expectedMultiOrdMatches(), collectMatches(createSortedSetDocValuesIterator(true)));+ }++ // --- SortedSetDocValues: Multi-value specific behavior ---++ public void testSortedSetMatchOnFirstOrdinal() throws IOException {+ // Doc 512: (512/2)%3 = 1 → ords [queryMin, queryMax+1]+ // First ordinal is in range → immediate match.+ DocValuesRangeIterator iter = createSortedSetDocValuesIterator(true);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();+ approx.advance(512);+ assertTrue(iter.matches());+ }++ public void testSortedSetMatchOnSecondOrdinal() throws IOException {+ // Doc 514: (514/2)%3 = 2 → ords [queryMin-1, mid]+ // First ordinal below range, second ordinal in range → match.+ DocValuesRangeIterator iter = createSortedSetDocValuesIterator(true);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();+ approx.advance(514);+ assertTrue(iter.matches());+ }++ public void testSortedSetNoMatchWhenOrdinalsBracketRange() throws IOException {+ // Doc 516: (516/2)%3 = 0 → ords [queryMin-1, queryMax+1]+ // Ordinals span below and above range, but none falls within it.+ DocValuesRangeIterator iter = createSortedSetDocValuesIterator(true);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();+ approx.advance(516);+ assertFalse(iter.matches());+ }++ // --- SortedSetDocValues: Approximation skipping ---++ public void testSortedSetApproximationSkipsAboveRange() throws IOException {+ DocValuesRangeIterator iter = createSortedSetDocValuesIterator(true);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();+ assertEquals(512, approx.advance(128));+ }++ public void testSortedSetApproximationSkipsBelowRange() throws IOException {+ DocValuesRangeIterator iter = createSortedSetDocValuesIterator(true);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();+ assertEquals(512, approx.advance(300));+ }++ public void testSortedSetApproximationSkipsSparseNonMatching() throws IOException {+ DocValuesRangeIterator iter = createSortedSetDocValuesIterator(true);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();+ assertEquals(1536, approx.advance(1200));+ }++ public void testSortedSetApproximationExhausted() throws IOException {+ DocValuesRangeIterator iter = createSortedSetDocValuesIterator(true);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();+ assertEquals(DocIdSetIterator.NO_MORE_DOCS, approx.advance(2048));+ }++ // --- SortedSetDocValues: Match classification ---++ public void testSortedSetYesMatch() throws IOException {+ DocValuesRangeIterator iter = createSortedSetDocValuesIterator(true);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();++ approx.advance(0);+ assertEquals(SkipBlockRangeIterator.Match.YES, approx.getMatch());+ assertTrue(iter.matches());+ }++ public void testSortedSetYesMatchDoesNotAdvanceDocValues() throws IOException {+ SortedSetDocValues values = sortedSetDocValues(QUERY_MIN, QUERY_MAX);+ DocValuesSkipper skipper = docValuesSkipper(QUERY_MIN, QUERY_MAX, true);+ DocValuesRangeIterator iter =+ DocValuesRangeIterator.forOrdinalRange(values, skipper, QUERY_MIN, QUERY_MAX);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();++ approx.advance(100);+ assertEquals(SkipBlockRangeIterator.Match.YES, approx.getMatch());+ assertTrue(iter.matches());+ assertTrue(values.docID() < approx.docID());+ }++ public void testSortedSetMaybeMatchChecksMultipleOrdinals() throws IOException {+ DocValuesRangeIterator iter = createSortedSetDocValuesIterator(true);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();++ // d=512: case 1 → [queryMin, queryMax+1] → match on first ordinal+ approx.advance(512);+ assertEquals(SkipBlockRangeIterator.Match.MAYBE, approx.getMatch());+ assertTrue(iter.matches());++ // d=514: case 2 → [queryMin-1, mid] → match on second ordinal+ approx.advance(514);+ assertTrue(iter.matches());++ // d=516: case 0 → [queryMin-1, queryMax+1] → no match (brackets range)+ approx.advance(516);+ assertFalse(iter.matches());+ }++ public void testSortedSetYesIfPresent() throws IOException {+ DocValuesRangeIterator iter = createSortedSetDocValuesIterator(true);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();++ approx.advance(1024);+ assertEquals(SkipBlockRangeIterator.Match.YES_IF_PRESENT, approx.getMatch());+ assertTrue(iter.matches());++ approx.advance(1025);+ assertFalse(iter.matches());+ }++ // --- SortedSetDocValues: docIdRunEnd ---++ public void testSortedSetDocIdRunEnd() throws IOException {+ DocValuesRangeIterator iter = createSortedSetDocValuesIterator(true);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();++ approx.advance(0);+ assertEquals(SkipBlockRangeIterator.Match.YES, approx.getMatch());+ assertEquals(128, iter.docIDRunEnd());++ approx.advance(64);+ assertEquals(128, iter.docIDRunEnd());++ approx.advance(512);+ assertEquals(SkipBlockRangeIterator.Match.MAYBE, approx.getMatch());+ assertEquals(513, iter.docIDRunEnd());++ approx.advance(1024);+ assertEquals(SkipBlockRangeIterator.Match.YES_IF_PRESENT, approx.getMatch());+ assertEquals(1025, iter.docIDRunEnd());+ }+}diff --git a/lucene/core/src/test/org/apache/lucene/search/TestDocValuesOrdinalSetIterator.java b/lucene/core/src/test/org/apache/lucene/search/TestDocValuesOrdinalSetIterator.javanew file mode 100644index 00000000000..53cd9b424aa--- /dev/null+++ b/lucene/core/src/test/org/apache/lucene/search/TestDocValuesOrdinalSetIterator.java@@ -0,0 +1,570 @@+/*+ * 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 java.util.ArrayList;+import java.util.List;+import org.apache.lucene.index.DocValuesSkipper;+import org.apache.lucene.index.ImpactsEnum;+import org.apache.lucene.index.PostingsEnum;+import org.apache.lucene.index.SortedDocValues;+import org.apache.lucene.index.SortedSetDocValues;+import org.apache.lucene.index.TermState;+import org.apache.lucene.index.TermsEnum;+import org.apache.lucene.util.AttributeSource;+import org.apache.lucene.util.BytesRef;+import org.apache.lucene.util.IOBooleanSupplier;++/**+ * Tests {@code DocValuesRangeIterator#forOrdinalSet} for both single-valued ({@link+ * SortedDocValues}) and multi-valued ({@link SortedSetDocValues}) ordinals.+ *+ * <p>Unlike the ordinal range tests, the ordinal set has a gap: ordinal 15 (the midpoint of [10,+ * 20]) is excluded. This means docs with ordinal 15 are within the bounding range but NOT in the+ * matching set, exercising the predicate-always-checked behavior of {@code alwaysCheckPredicate}.+ */+public class TestDocValuesOrdinalSetIterator extends BaseDocValuesSkipperTests {++ private static final long QUERY_MIN = 10;+ private static final long QUERY_MAX = 20;+ private static final long GAP_ORD = 15;++ /** Matching ordinals: all of [10, 20] except 15. */+ private static final long[] MATCHING_ORDS = {10, 11, 12, 13, 14, 16, 17, 18, 19, 20};++ /**+ * Fake TermsEnum that iterates over a fixed array of ordinals. Only {@code next()} and {@code+ * ord()} are needed by {@code DocValuesRangeIterator#forOrdinalSet()}.+ */+ private static TermsEnum fakeTermsEnum(long[] ordinals) {+ return new TermsEnum() {+ int idx = -1;++ @Override+ public BytesRef next() {+ idx++;+ if (idx >= ordinals.length) {+ return null;+ }+ return new BytesRef("term" + ordinals[idx]);+ }++ @Override+ public long ord() {+ return ordinals[idx];+ }++ @Override+ public AttributeSource attributes() {+ throw new UnsupportedOperationException();+ }++ @Override+ public boolean seekExact(BytesRef text) {+ throw new UnsupportedOperationException();+ }++ @Override+ public IOBooleanSupplier prepareSeekExact(BytesRef text) {+ throw new UnsupportedOperationException();+ }++ @Override+ public SeekStatus seekCeil(BytesRef text) {+ throw new UnsupportedOperationException();+ }++ @Override+ public void seekExact(long ord) {+ throw new UnsupportedOperationException();+ }++ @Override+ public void seekExact(BytesRef term, TermState state) {+ throw new UnsupportedOperationException();+ }++ @Override+ public BytesRef term() {+ throw new UnsupportedOperationException();+ }++ @Override+ public int docFreq() {+ throw new UnsupportedOperationException();+ }++ @Override+ public long totalTermFreq() {+ throw new UnsupportedOperationException();+ }++ @Override+ public PostingsEnum postings(PostingsEnum reuse, int flags) {+ throw new UnsupportedOperationException();+ }++ @Override+ public ImpactsEnum impacts(int flags) {+ throw new UnsupportedOperationException();+ }++ @Override+ public TermState termState() {+ throw new UnsupportedOperationException();+ }+ };+ }++ private static boolean ordInSet(long ord) {+ return ord >= QUERY_MIN && ord <= QUERY_MAX && ord != GAP_ORD;+ }++ // ---- Shared helpers ----++ private static boolean docHasValue(int doc) {+ return doc < 1024 || (doc < 2048 && (doc & 1) == 0);+ }++ private static List<Integer> collectMatches(DocValuesRangeIterator iter) throws IOException {+ List<Integer> matches = new ArrayList<>();+ DocIdSetIterator approx = iter.approximation();+ while (approx.nextDoc() != DocIdSetIterator.NO_MORE_DOCS) {+ if (iter.matches()) {+ matches.add(approx.docID());+ }+ }+ return matches;+ }++ // ==========================================================================+ // SortedDocValues (single-valued ordinals with a set)+ // ==========================================================================++ /**+ * Single ordinal per doc. Uses ordinal 14 (in the set) for the in-range region, and ordinal 15+ * (in the gap) for the mixed region's case 2.+ */+ private static int singleOrdinal(int doc) {+ int d = doc % 1024;+ if (d < 128) {+ return 14;+ } else if (d < 256) {+ return (int) (QUERY_MAX + 1);+ } else if (d < 512) {+ return (int) (QUERY_MIN - 1);+ } else {+ return switch ((d / 2) % 3) {+ case 0 -> (int) (QUERY_MIN - 1);+ case 1 -> (int) (QUERY_MAX + 1);+ case 2 -> (int) GAP_ORD;+ default -> throw new AssertionError();+ };+ }+ }++ private static List<Integer> expectedSingleOrdMatches() {+ List<Integer> matches = new ArrayList<>();+ for (int doc = 0; doc < 2048; doc++) {+ if (docHasValue(doc) && ordInSet(singleOrdinal(doc))) {+ matches.add(doc);+ }+ }+ return matches;+ }++ private static SortedDocValues sortedDocValues() {+ return new SortedDocValues() {+ int doc = -1;++ @Override+ public int ordValue() {+ return singleOrdinal(doc);+ }++ @Override+ public BytesRef lookupOrd(int ord) {+ throw new UnsupportedOperationException();+ }++ @Override+ public int getValueCount() {+ return (int) (QUERY_MAX + 10);+ }++ @Override+ public boolean advanceExact(int target) {+ throw new UnsupportedOperationException();+ }++ @Override+ public int docID() {+ return doc;+ }++ @Override+ public int nextDoc() throws IOException {+ return advance(doc + 1);+ }++ @Override+ public int advance(int target) {+ if (target < 1024) {+ return doc = target;+ } else if (target < 2048) {+ doc = target + (target & 1);+ return doc < 2048 ? doc : (doc = DocIdSetIterator.NO_MORE_DOCS);+ } else {+ return doc = DocIdSetIterator.NO_MORE_DOCS;+ }+ }++ @Override+ public long cost() {+ return 42;+ }+ };+ }++ private DocValuesRangeIterator createSortedDocValuesIterator(boolean multiLevel)+ throws IOException {+ SortedDocValues values = sortedDocValues();+ DocValuesSkipper skipper = docValuesSkipper(QUERY_MIN, QUERY_MAX, multiLevel);+ return DocValuesRangeIterator.forOrdinalSet(values, skipper, fakeTermsEnum(MATCHING_ORDS));+ }++ // --- SortedDocValues: Correctness ---++ public void testSortedDocValuesCorrectResultsSingleLevel() throws IOException {+ assertEquals(expectedSingleOrdMatches(), collectMatches(createSortedDocValuesIterator(false)));+ }++ public void testSortedDocValuesCorrectResultsMultipleLevels() throws IOException {+ assertEquals(expectedSingleOrdMatches(), collectMatches(createSortedDocValuesIterator(true)));+ }++ // --- SortedDocValues: Gap ordinal is rejected ---++ public void testSortedDocValuesGapOrdinalRejected() throws IOException {+ // Doc 514: (514/2)%3 = 2 → ordinal 15 (in [10,20] but NOT in set)+ // With forOrdinalRange this would match; with forOrdinalSet it must not.+ DocValuesRangeIterator iter = createSortedDocValuesIterator(true);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();+ approx.advance(514);+ assertFalse(iter.matches());+ }++ public void testSortedDocValuesInSetOrdinalAccepted() throws IOException {+ // Doc 0: ordinal 14 (in set) → match+ DocValuesRangeIterator iter = createSortedDocValuesIterator(true);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();+ approx.advance(0);+ assertTrue(iter.matches());+ }++ // --- SortedDocValues: YES blocks still check predicate ---++ public void testSortedDocValuesYesBlockChecksPredicate() throws IOException {+ SortedDocValues values = sortedDocValues();+ DocValuesSkipper skipper = docValuesSkipper(QUERY_MIN, QUERY_MAX, true);+ DocValuesRangeIterator iter =+ DocValuesRangeIterator.forOrdinalSet(values, skipper, fakeTermsEnum(MATCHING_ORDS));+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();++ // Block 0-63 is classified YES, but predicate is still checked+ approx.advance(0);+ assertEquals(SkipBlockRangeIterator.Match.YES, approx.getMatch());+ // ordinal 14 is in the set → match+ assertTrue(iter.matches());+ // doc values iterator was advanced (predicate was checked)+ assertEquals(0, values.docID());+ }++ // --- SortedDocValues: Approximation skipping ---++ public void testSortedDocValuesApproximationSkips() throws IOException {+ DocValuesRangeIterator iter = createSortedDocValuesIterator(true);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();++ assertEquals(512, approx.advance(128));+ assertEquals(1536, approx.advance(1200));+ assertEquals(DocIdSetIterator.NO_MORE_DOCS, approx.advance(2048));+ }++ // --- SortedDocValues: docIdRunEnd is conservative with ordinal sets ---++ public void testSortedDocValuesDocIdRunEndAlwaysDocPlusOne() throws IOException {+ DocValuesRangeIterator iter = createSortedDocValuesIterator(true);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();++ // Even in a YES block, docIdRunEnd returns doc+1 because ordinal sets+ // may have gaps that the block-level check cannot detect.+ approx.advance(0);+ assertEquals(SkipBlockRangeIterator.Match.YES, approx.getMatch());+ assertEquals(1, iter.docIDRunEnd());++ approx.advance(64);+ assertEquals(65, iter.docIDRunEnd());++ // MAYBE block: same behavior as forOrdinalRange+ approx.advance(512);+ assertEquals(SkipBlockRangeIterator.Match.MAYBE, approx.getMatch());+ assertEquals(513, iter.docIDRunEnd());++ // YES_IF_PRESENT block: also doc+1+ approx.advance(1024);+ assertEquals(SkipBlockRangeIterator.Match.YES_IF_PRESENT, approx.getMatch());+ assertEquals(1025, iter.docIDRunEnd());+ }++ // ==========================================================================+ // SortedSetDocValues (multi-valued ordinals with a set)+ // ==========================================================================++ /**+ * Two sorted ordinals per doc. In the mixed region:+ *+ * <ul>+ * <li>Case 0: [9, 21] — both outside set → no match+ * <li>Case 1: [10, 21] — first ordinal 10 is in set → match+ * <li>Case 2: [9, 15] — second ordinal 15 is in gap → no match (unlike forOrdinalRange!)+ * </ul>+ */+ private static long[] ordinalPair(int doc) {+ int d = doc % 1024;+ if (d < 128) {+ return new long[] {QUERY_MIN, QUERY_MAX};+ } else if (d < 256) {+ return new long[] {QUERY_MAX + 1, QUERY_MAX + 1};+ } else if (d < 512) {+ return new long[] {QUERY_MIN - 1, QUERY_MIN - 1};+ } else {+ return switch ((d / 2) % 3) {+ case 0 -> new long[] {QUERY_MIN - 1, QUERY_MAX + 1};+ case 1 -> new long[] {QUERY_MIN, QUERY_MAX + 1};+ case 2 -> new long[] {QUERY_MIN - 1, GAP_ORD};+ default -> throw new AssertionError();+ };+ }+ }++ private static boolean multiOrdInSet(int doc) {+ long[] ords = ordinalPair(doc);+ for (long ord : ords) {+ if (ordInSet(ord)) {+ return true;+ }+ }+ return false;+ }++ private static List<Integer> expectedMultiOrdMatches() {+ List<Integer> matches = new ArrayList<>();+ for (int doc = 0; doc < 2048; doc++) {+ if (docHasValue(doc) && multiOrdInSet(doc)) {+ matches.add(doc);+ }+ }+ return matches;+ }++ private static SortedSetDocValues sortedSetDocValues() {+ return new SortedSetDocValues() {+ int doc = -1;+ int ordIdx = 0;++ @Override+ public long nextOrd() {+ long[] ords = ordinalPair(doc);+ return ords[ordIdx++];+ }++ @Override+ public int docValueCount() {+ return 2;+ }++ @Override+ public BytesRef lookupOrd(long ord) {+ throw new UnsupportedOperationException();+ }++ @Override+ public long getValueCount() {+ return QUERY_MAX + 10;+ }++ @Override+ public boolean advanceExact(int target) {+ throw new UnsupportedOperationException();+ }++ @Override+ public int docID() {+ return doc;+ }++ @Override+ public int nextDoc() throws IOException {+ return advance(doc + 1);+ }++ @Override+ public int advance(int target) {+ ordIdx = 0;+ if (target < 1024) {+ return doc = target;+ } else if (target < 2048) {+ doc = target + (target & 1);+ return doc < 2048 ? doc : (doc = DocIdSetIterator.NO_MORE_DOCS);+ } else {+ return doc = DocIdSetIterator.NO_MORE_DOCS;+ }+ }++ @Override+ public long cost() {+ return 42;+ }+ };+ }++ private DocValuesRangeIterator createSortedSetDocValuesIterator(boolean multiLevel)+ throws IOException {+ SortedSetDocValues values = sortedSetDocValues();+ DocValuesSkipper skipper = docValuesSkipper(QUERY_MIN, QUERY_MAX, multiLevel);+ return DocValuesRangeIterator.forOrdinalSet(values, skipper, fakeTermsEnum(MATCHING_ORDS));+ }++ // --- SortedSetDocValues: Correctness ---++ public void testSortedSetDocValuesCorrectResultsSingleLevel() throws IOException {+ assertEquals(+ expectedMultiOrdMatches(), collectMatches(createSortedSetDocValuesIterator(false)));+ }++ public void testSortedSetDocValuesCorrectResultsMultipleLevels() throws IOException {+ assertEquals(expectedMultiOrdMatches(), collectMatches(createSortedSetDocValuesIterator(true)));+ }++ // --- SortedSetDocValues: Gap ordinal behavior ---++ public void testSortedSetGapOrdinalRejected() throws IOException {+ // Doc 514: case 2 → ords [9, 15]. Ordinal 15 is in [10,20] but NOT in set.+ // With forOrdinalRange this would match; with forOrdinalSet it must not.+ DocValuesRangeIterator iter = createSortedSetDocValuesIterator(true);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();+ approx.advance(514);+ assertFalse(iter.matches());+ }++ public void testSortedSetMatchOnFirstOrdinalInSet() throws IOException {+ // Doc 512: case 1 → ords [10, 21]. Ordinal 10 is in set → match.+ DocValuesRangeIterator iter = createSortedSetDocValuesIterator(true);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();+ approx.advance(512);+ assertTrue(iter.matches());+ }++ public void testSortedSetNoMatchWhenOrdinalsBracketRange() throws IOException {+ // Doc 516: case 0 → ords [9, 21]. Neither ordinal is in the set.+ DocValuesRangeIterator iter = createSortedSetDocValuesIterator(true);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();+ approx.advance(516);+ assertFalse(iter.matches());+ }++ // --- SortedSetDocValues: YES blocks still check predicate ---++ public void testSortedSetYesBlockChecksPredicate() throws IOException {+ SortedSetDocValues values = sortedSetDocValues();+ DocValuesSkipper skipper = docValuesSkipper(QUERY_MIN, QUERY_MAX, true);+ DocValuesRangeIterator iter =+ DocValuesRangeIterator.forOrdinalSet(values, skipper, fakeTermsEnum(MATCHING_ORDS));+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();++ approx.advance(0);+ assertEquals(SkipBlockRangeIterator.Match.YES, approx.getMatch());+ // Ords [10, 20]: 10 is in set → match, but only because predicate was checked+ assertTrue(iter.matches());+ // doc values iterator was advanced (predicate was checked)+ assertEquals(0, values.docID());+ }++ // --- SortedSetDocValues: Approximation skipping ---++ public void testSortedSetApproximationSkipsAboveRange() throws IOException {+ DocValuesRangeIterator iter = createSortedSetDocValuesIterator(true);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();+ assertEquals(512, approx.advance(128));+ }++ public void testSortedSetApproximationSkipsBelowRange() throws IOException {+ DocValuesRangeIterator iter = createSortedSetDocValuesIterator(true);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();+ assertEquals(512, approx.advance(300));+ }++ public void testSortedSetApproximationSkipsSparseNonMatching() throws IOException {+ DocValuesRangeIterator iter = createSortedSetDocValuesIterator(true);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();+ assertEquals(1536, approx.advance(1200));+ }++ public void testSortedSetApproximationExhausted() throws IOException {+ DocValuesRangeIterator iter = createSortedSetDocValuesIterator(true);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();+ assertEquals(DocIdSetIterator.NO_MORE_DOCS, approx.advance(2048));+ }++ // --- SortedSetDocValues: docIdRunEnd ---++ public void testSortedSetDocIdRunEndAlwaysDocPlusOne() throws IOException {+ DocValuesRangeIterator iter = createSortedSetDocValuesIterator(true);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();++ approx.advance(0);+ assertEquals(SkipBlockRangeIterator.Match.YES, approx.getMatch());+ assertEquals(1, iter.docIDRunEnd());++ approx.advance(512);+ assertEquals(SkipBlockRangeIterator.Match.MAYBE, approx.getMatch());+ assertEquals(513, iter.docIDRunEnd());++ approx.advance(1024);+ assertEquals(SkipBlockRangeIterator.Match.YES_IF_PRESENT, approx.getMatch());+ assertEquals(1025, iter.docIDRunEnd());+ }++ // --- SortedSetDocValues: YES_IF_PRESENT ---++ public void testSortedSetYesIfPresent() throws IOException {+ DocValuesRangeIterator iter = createSortedSetDocValuesIterator(true);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();++ // Sparse region: even doc has value, odd doc does not+ approx.advance(1024);+ assertEquals(SkipBlockRangeIterator.Match.YES_IF_PRESENT, approx.getMatch());+ // Ords [10, 20], 10 in set → match+ assertTrue(iter.matches());++ approx.advance(1025);+ // Odd doc has no value → no match+ assertFalse(iter.matches());+ }+}diff --git a/lucene/core/src/test/org/apache/lucene/search/TestDocValuesRangeIterator.java b/lucene/core/src/test/org/apache/lucene/search/TestDocValuesRangeIterator.javaindex 838eec1377b..d94806545b0 100644--- a/lucene/core/src/test/org/apache/lucene/search/TestDocValuesRangeIterator.java+++ b/lucene/core/src/test/org/apache/lucene/search/TestDocValuesRangeIterator.java@@ -17,157 +17,277 @@package org.apache.lucene.search;import java.io.IOException;-import java.util.concurrent.atomic.AtomicBoolean;+import java.util.ArrayList;+import java.util.List;import org.apache.lucene.index.DocValuesSkipper;import org.apache.lucene.index.NumericDocValues;public class TestDocValuesRangeIterator extends BaseDocValuesSkipperTests {- public void testSingleLevel() throws IOException {- doTestBasics(false);+ private static final long QUERY_MIN = 10;+ private static final long QUERY_MAX = 20;++ private static boolean valueInRange(int doc) {+ int d = doc % 1024;+ long value;+ if (d < 128) {+ value = (QUERY_MIN + QUERY_MAX) >> 1;+ } else if (d < 256) {+ value = QUERY_MAX + 1;+ } else if (d < 512) {+ value = QUERY_MIN - 1;+ } else {+ value =+ switch ((d / 2) % 3) {+ case 0 -> QUERY_MIN - 1;+ case 1 -> QUERY_MAX + 1;+ case 2 -> (QUERY_MIN + QUERY_MAX) >> 1;+ default -> throw new AssertionError();+ };+ }+ return value >= QUERY_MIN && value <= QUERY_MAX;}- public void testMultipleLevels() throws IOException {- doTestBasics(true);+ private static boolean docHasValue(int doc) {+ return doc < 1024 || (doc < 2048 && (doc & 1) == 0);}- private void doTestBasics(boolean doLevels) throws IOException {- long queryMin = 10;- long queryMax = 20;+ /**+ * Compute expected matching docs. With the corrected aggregating skipper, YES and YES_IF_PRESENT+ * blocks only contain docs whose values are genuinely within the query range, so the expected+ * matches are simply all docs that have a value in range.+ */+ private static List<Integer> expectedMatches() {+ List<Integer> matches = new ArrayList<>();+ for (int doc = 0; doc < 2048; doc++) {+ if (docHasValue(doc) && valueInRange(doc)) {+ matches.add(doc);+ }+ }+ return matches;+ }- // Test with both gaps and no-gaps in the ranges:- NumericDocValues values = docValues(queryMin, queryMax);- NumericDocValues values2 = docValues(queryMin, queryMax);+ private static List<Integer> collectMatches(DocValuesRangeIterator iter) throws IOException {+ List<Integer> matches = new ArrayList<>();+ DocIdSetIterator approx = iter.approximation();+ while (approx.nextDoc() != DocIdSetIterator.NO_MORE_DOCS) {+ if (iter.matches()) {+ matches.add(approx.docID());+ }+ }+ return matches;+ }- AtomicBoolean twoPhaseCalled = new AtomicBoolean();- TwoPhaseIterator twoPhase = twoPhaseIterator(values, queryMin, queryMax, twoPhaseCalled);- AtomicBoolean twoPhaseCalled2 = new AtomicBoolean();- TwoPhaseIterator twoPhase2 = twoPhaseIterator(values2, queryMin, queryMax, twoPhaseCalled2);+ private DocValuesRangeIterator createIterator(boolean multiLevel) {+ NumericDocValues values = docValues(QUERY_MIN, QUERY_MAX);+ DocValuesSkipper skipper = docValuesSkipper(QUERY_MIN, QUERY_MAX, multiLevel);+ return DocValuesRangeIterator.forRange(values, skipper, QUERY_MIN, QUERY_MAX);+ }- DocValuesSkipper skipper = docValuesSkipper(queryMin, queryMax, doLevels);- DocValuesSkipper skipper2 = docValuesSkipper(queryMin, queryMax, doLevels);+ // --- Correctness: all matching docs are found and no false positives ---- DocValuesRangeIterator rangeIterator =- new DocValuesRangeIterator(twoPhase, skipper, queryMin, queryMax, false);- DocValuesRangeIterator rangeIteratorWithGaps =- new DocValuesRangeIterator(twoPhase2, skipper2, queryMin, queryMax, true);- DocValuesRangeIterator.Approximation rangeApproximation =- (DocValuesRangeIterator.Approximation) rangeIterator.approximation();- DocValuesRangeIterator.Approximation rangeApproximationWithGaps =- (DocValuesRangeIterator.Approximation) rangeIteratorWithGaps.approximation();+ public void testCorrectResultsSingleLevel() throws IOException {+ assertEquals(expectedMatches(), collectMatches(createIterator(false)));+ }- assertEquals(100, rangeApproximation.advance(100));- assertEquals(100, rangeApproximationWithGaps.advance(100));- assertEquals(DocValuesRangeIterator.Match.YES, rangeApproximation.match);- assertEquals(DocValuesRangeIterator.Match.MAYBE, rangeApproximationWithGaps.match);- assertEquals(255, rangeApproximation.upTo);- assertEquals(256, rangeIterator.docIDRunEnd());- if (doLevels) {- assertEquals(127, rangeApproximationWithGaps.upTo);- } else {- assertEquals(255, rangeApproximationWithGaps.upTo);- }- assertEquals(rangeApproximationWithGaps.docID(), rangeIteratorWithGaps.docIDRunEnd());- assertTrue(rangeIterator.matches());- assertTrue(rangeIteratorWithGaps.matches());- assertTrue(values.docID() < rangeApproximation.docID()); // we did not advance doc values- assertEquals(- values2.docID(), rangeApproximationWithGaps.docID()); // we _did_ advance doc values- assertFalse(twoPhaseCalled.get());- assertTrue(twoPhaseCalled2.get());- twoPhaseCalled2.set(false);-- assertEquals(768, rangeApproximation.advance(300));- assertEquals(768, rangeApproximationWithGaps.advance(300));- assertEquals(DocValuesRangeIterator.Match.MAYBE, rangeApproximation.match);- assertEquals(DocValuesRangeIterator.Match.MAYBE, rangeApproximationWithGaps.match);- assertEquals(rangeApproximation.docID(), rangeIterator.docIDRunEnd());- assertEquals(rangeApproximationWithGaps.docID(), rangeIteratorWithGaps.docIDRunEnd());- if (doLevels) {- assertEquals(831, rangeApproximation.upTo);- assertEquals(831, rangeApproximationWithGaps.upTo);- } else {- assertEquals(1023, rangeApproximation.upTo);- assertEquals(1023, rangeApproximationWithGaps.upTo);- }- for (int i = 0; i < 10; ++i) {- assertEquals(values.docID(), rangeApproximation.docID());- assertEquals(values2.docID(), rangeApproximationWithGaps.docID());- assertEquals(twoPhase.matches(), rangeIterator.matches());- assertEquals(twoPhase2.matches(), rangeIteratorWithGaps.matches());- assertTrue(twoPhaseCalled.get());- assertTrue(twoPhaseCalled2.get());- twoPhaseCalled.set(false);- twoPhaseCalled2.set(false);- rangeApproximation.nextDoc();- rangeApproximationWithGaps.nextDoc();- }+ public void testCorrectResultsMultipleLevels() throws IOException {+ assertEquals(expectedMatches(), collectMatches(createIterator(true)));+ }- assertEquals(1100, rangeApproximation.advance(1099));- assertEquals(1100, rangeApproximationWithGaps.advance(1099));- assertEquals(DocValuesRangeIterator.Match.IF_DOC_HAS_VALUE, rangeApproximation.match);- assertEquals(DocValuesRangeIterator.Match.MAYBE, rangeApproximationWithGaps.match);- assertEquals(1024 + 256 - 1, rangeApproximation.upTo);- assertEquals(rangeApproximation.docID(), rangeIterator.docIDRunEnd());- assertEquals(rangeApproximationWithGaps.docID(), rangeIteratorWithGaps.docIDRunEnd());- if (doLevels) {- assertEquals(1024 + 128 - 1, rangeApproximationWithGaps.upTo);- } else {- assertEquals(1024 + 256 - 1, rangeApproximationWithGaps.upTo);- }- assertEquals(values.docID(), rangeApproximation.docID());- assertEquals(values2.docID(), rangeApproximationWithGaps.docID());- assertTrue(rangeIterator.matches());- assertTrue(rangeIteratorWithGaps.matches());- assertFalse(twoPhaseCalled.get());- assertTrue(twoPhaseCalled2.get());- twoPhaseCalled2.set(false);-- assertEquals(1024 + 768, rangeApproximation.advance(1024 + 300));- assertEquals(1024 + 768, rangeApproximationWithGaps.advance(1024 + 300));- assertEquals(DocValuesRangeIterator.Match.MAYBE, rangeApproximation.match);- assertEquals(DocValuesRangeIterator.Match.MAYBE, rangeApproximationWithGaps.match);- assertEquals(rangeApproximation.docID(), rangeIterator.docIDRunEnd());- assertEquals(rangeApproximationWithGaps.docID(), rangeIteratorWithGaps.docIDRunEnd());- if (doLevels) {- assertEquals(1024 + 831, rangeApproximation.upTo);- assertEquals(1024 + 831, rangeApproximationWithGaps.upTo);- } else {- assertEquals(2047, rangeApproximation.upTo);- assertEquals(2047, rangeApproximationWithGaps.upTo);- }- for (int i = 0; i < 10; ++i) {- assertEquals(values.docID(), rangeApproximation.docID());- assertEquals(values2.docID(), rangeApproximationWithGaps.docID());- assertEquals(twoPhase.matches(), rangeIterator.matches());- assertEquals(twoPhase2.matches(), rangeIteratorWithGaps.matches());- assertTrue(twoPhaseCalled.get());- assertTrue(twoPhaseCalled2.get());- twoPhaseCalled.set(false);- twoPhaseCalled2.set(false);- rangeApproximation.nextDoc();- rangeApproximationWithGaps.nextDoc();- }+ // --- Approximation correctly skips non-matching blocks ---- assertEquals(DocIdSetIterator.NO_MORE_DOCS, rangeApproximation.advance(2048));- assertEquals(DocIdSetIterator.NO_MORE_DOCS, rangeApproximationWithGaps.advance(2048));+ public void testApproximationSkipsAboveRangeBlock() throws IOException {+ DocValuesRangeIterator iter = createIterator(true);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();++ // Docs 128-511 are in blocks above or below the query range.+ // The first MAYBE block starts at 512 (where mixed values begin).+ assertEquals(512, approx.advance(128));}- private static TwoPhaseIterator twoPhaseIterator(- NumericDocValues values, long queryMin, long queryMax, AtomicBoolean twoPhaseCalled) {- return new TwoPhaseIterator(values) {+ public void testApproximationSkipsBelowRangeBlock() throws IOException {+ DocValuesRangeIterator iter = createIterator(true);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();- @Override- public boolean matches() throws IOException {- twoPhaseCalled.set(true);- long v = values.longValue();- return v >= queryMin && v <= queryMax;- }+ // Docs 256-511 are below range; skip to the first MAYBE block at 512.+ assertEquals(512, approx.advance(300));+ }- @Override- public float matchCost() {- return 2f; // 2 comparisons- }- };+ public void testApproximationSkipsFromEndOfMatchingBlock() throws IOException {+ DocValuesRangeIterator iter = createIterator(true);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();++ assertEquals(100, approx.advance(100));+ // Advancing past the last YES block boundary at 127 should skip to 512+ assertEquals(512, approx.advance(128));+ }++ public void testApproximationIteratesWithinMatchingBlock() throws IOException {+ DocValuesRangeIterator iter = createIterator(true);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();++ assertEquals(10, approx.advance(10));+ assertEquals(11, approx.nextDoc());+ assertEquals(12, approx.nextDoc());+ assertEquals(50, approx.advance(50));+ }++ public void testApproximationSkipsSparseNonMatchingBlocks() throws IOException {+ DocValuesRangeIterator iter = createIterator(true);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();++ // In the sparse region (1024-2047), docs 1152-1535 are in non-matching+ // blocks (above-range then below-range), so they should be skipped.+ assertEquals(1536, approx.advance(1200));+ }++ public void testApproximationExhausted() throws IOException {+ DocValuesRangeIterator iter = createIterator(true);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();++ assertEquals(DocIdSetIterator.NO_MORE_DOCS, approx.advance(2048));+ }++ // --- Match classification ---++ public void testYesMatchInDenseBlock() throws IOException {+ DocValuesRangeIterator iter = createIterator(true);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();++ approx.advance(0);+ assertEquals(SkipBlockRangeIterator.Match.YES, approx.getMatch());+ assertTrue(iter.matches());+ }++ public void testYesMatchDoesNotAdvanceDocValues() throws IOException {+ NumericDocValues values = docValues(QUERY_MIN, QUERY_MAX);+ DocValuesSkipper skipper = docValuesSkipper(QUERY_MIN, QUERY_MAX, true);+ DocValuesRangeIterator iter =+ DocValuesRangeIterator.forRange(values, skipper, QUERY_MIN, QUERY_MAX);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();++ approx.advance(100);+ assertEquals(SkipBlockRangeIterator.Match.YES, approx.getMatch());+ assertTrue(iter.matches());+ assertTrue(values.docID() < approx.docID());+ }++ public void testMaybeMatchClassification() throws IOException {+ DocValuesRangeIterator iter = createIterator(true);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();++ // Docs 512+ are in blocks with mixed values -> MAYBE+ approx.advance(512);+ assertEquals(SkipBlockRangeIterator.Match.MAYBE, approx.getMatch());+ }++ public void testMaybeMatchChecksValues() throws IOException {+ DocValuesRangeIterator iter = createIterator(true);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();++ approx.advance(512);++ // d=512: (512/2)%3 = 1 -> value above range+ assertFalse(iter.matches());++ // d=514: (514/2)%3 = 2 -> value in range+ approx.advance(514);+ assertTrue(iter.matches());++ // d=515: (515/2)%3 = 2 -> value in range+ approx.advance(515);+ assertTrue(iter.matches());++ // d=516: (516/2)%3 = 0 -> value below range+ approx.advance(516);+ assertFalse(iter.matches());+ }++ public void testYesIfPresentInSparseBlock() throws IOException {+ DocValuesRangeIterator iter = createIterator(true);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();++ // Sparse block with values in range: all values match but not all docs+ // have a value, so the block is classified YES_IF_PRESENT.+ approx.advance(1024);+ assertEquals(SkipBlockRangeIterator.Match.YES_IF_PRESENT, approx.getMatch());+ // Even doc has a value -> match+ assertTrue(iter.matches());++ approx.advance(1025);+ assertEquals(SkipBlockRangeIterator.Match.YES_IF_PRESENT, approx.getMatch());+ // Odd doc has no value -> no match+ assertFalse(iter.matches());+ }++ // --- docIdRunEnd ---++ public void testDocIdRunEndYesBlockMultipleLevels() throws IOException {+ DocValuesRangeIterator iter = createIterator(true);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();++ // 3 levels: level 0 blocks are 64 docs wide.+ // At doc 0: level 0 block is 0-63 (YES). Level 1 block 0-127 also has+ // all values in range, so docIdRunEnd extends to 128. But level 2 block+ // 0-255 includes docs 128-255 with values above range, so the+ // containment check fails and the run stops at the level 1 boundary.+ approx.advance(0);+ assertEquals(SkipBlockRangeIterator.Match.YES, approx.getMatch());+ assertEquals(128, iter.docIDRunEnd());+ }++ public void testDocIdRunEndExtendsFromMiddleOfBlock() throws IOException {+ DocValuesRangeIterator iter = createIterator(true);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();++ // At doc 64: level 0 block is 64-127, level 1 is 0-127 (all in range).+ // Level 2 is 0-255 which includes above-range values -> stop at level 1.+ approx.advance(64);+ assertEquals(SkipBlockRangeIterator.Match.YES, approx.getMatch());+ assertEquals(128, iter.docIDRunEnd());++ approx.advance(100);+ assertEquals(128, iter.docIDRunEnd());+ }++ public void testDocIdRunEndConsistentAcrossYesBlock() throws IOException {+ DocValuesRangeIterator iter = createIterator(true);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();++ // With 3 levels, docs 0-127 are in YES blocks (two level-0 blocks:+ // 0-63 and 64-127). Both extend to the level 1 boundary at 128, but+ // not further (level 2 includes above-range docs 128-255).+ for (int doc = 0; doc < 128; doc++) {+ approx.advance(doc);+ assertEquals(SkipBlockRangeIterator.Match.YES, approx.getMatch());+ assertEquals(+ "docIdRunEnd at doc " + doc + " should extend to level 1 boundary",+ 128,+ iter.docIDRunEnd());+ }+ }++ public void testDocIdRunEndMaybeBlock() throws IOException {+ DocValuesRangeIterator iter = createIterator(true);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();++ // MAYBE blocks cannot guarantee all docs match, so docIdRunEnd = doc + 1+ approx.advance(512);+ assertEquals(SkipBlockRangeIterator.Match.MAYBE, approx.getMatch());+ assertEquals(513, iter.docIDRunEnd());++ approx.advance(800);+ assertEquals(SkipBlockRangeIterator.Match.MAYBE, approx.getMatch());+ assertEquals(801, iter.docIDRunEnd());+ }++ public void testDocIdRunEndYesIfPresentBlock() throws IOException {+ DocValuesRangeIterator iter = createIterator(true);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();++ // YES_IF_PRESENT blocks have gaps, so docIdRunEnd = doc + 1+ approx.advance(1024);+ assertEquals(SkipBlockRangeIterator.Match.YES_IF_PRESENT, approx.getMatch());+ assertEquals(1025, iter.docIDRunEnd());}}diff --git a/lucene/core/src/test/org/apache/lucene/search/TestSkipBlockRangeIterator.java b/lucene/core/src/test/org/apache/lucene/search/TestSkipBlockRangeIterator.javaindex 3f0423c8802..a6031faf871 100644--- a/lucene/core/src/test/org/apache/lucene/search/TestSkipBlockRangeIterator.java+++ b/lucene/core/src/test/org/apache/lucene/search/TestSkipBlockRangeIterator.java@@ -27,26 +27,26 @@ public class TestSkipBlockRangeIterator extends BaseDocValuesSkipperTests {SkipBlockRangeIterator it = new SkipBlockRangeIterator(skipper, 10, 20);assertEquals(0, it.nextDoc());- assertEquals(256, it.docIDRunEnd());+ assertEquals(128, it.docIDRunEnd());assertEquals(100, it.advance(100));- assertEquals(768, it.advance(300));- assertEquals(1024, it.docIDRunEnd());+ assertEquals(512, it.advance(300));+ assertEquals(513, it.docIDRunEnd());assertEquals(1100, it.advance(1100));- assertEquals(1280, it.docIDRunEnd());- assertEquals(1792, it.advance(1500));- assertEquals(2048, it.docIDRunEnd());+ assertEquals(1101, it.docIDRunEnd());+ assertEquals(1536, it.advance(1500));+ assertEquals(1537, it.docIDRunEnd());assertEquals(DocIdSetIterator.NO_MORE_DOCS, it.advance(2050));}public void testIntoBitSet() throws Exception {DocValuesSkipper skipper = docValuesSkipper(10, 20, true);SkipBlockRangeIterator it = new SkipBlockRangeIterator(skipper, 10, 20);- assertEquals(768, it.advance(300));+ assertEquals(512, it.advance(300));FixedBitSet bitSet = new FixedBitSet(2048);- it.intoBitSet(1500, bitSet, 768);+ it.intoBitSet(1500, bitSet, 512);FixedBitSet expected = new FixedBitSet(2048);- expected.set(0, 512);+ expected.set(0, 640);assertEquals(expected, bitSet);}diff --git a/lucene/core/src/test/org/apache/lucene/search/TestSortedNumericDocValuesRangeIterator.java b/lucene/core/src/test/org/apache/lucene/search/TestSortedNumericDocValuesRangeIterator.javanew file mode 100644index 00000000000..f1226491aec--- /dev/null+++ b/lucene/core/src/test/org/apache/lucene/search/TestSortedNumericDocValuesRangeIterator.java@@ -0,0 +1,366 @@+/*+ * 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 java.util.ArrayList;+import java.util.List;+import org.apache.lucene.index.DocValuesSkipper;+import org.apache.lucene.index.SortedNumericDocValues;++/**+ * Tests {@link DocValuesRangeIterator#forRange(SortedNumericDocValues, DocValuesSkipper, long,+ * long)} with multi-valued documents. Parallel to {@link TestDocValuesRangeIterator} which tests+ * single-valued {@link org.apache.lucene.index.NumericDocValues}.+ *+ * <p>Each document has two values in sorted order. The three cases in the mixed region exercise+ * distinct multi-value behaviors:+ *+ * <ul>+ * <li>Case 0: values bracket the query range (below and above) — no match+ * <li>Case 1: first value is in range — immediate match+ * <li>Case 2: only the second value is in range — match via iteration+ * </ul>+ */+public class TestSortedNumericDocValuesRangeIterator extends BaseDocValuesSkipperTests {++ private static final long QUERY_MIN = 10;+ private static final long QUERY_MAX = 20;++ /**+ * Returns the two sorted values for a given doc. Block-level min/max values are consistent with+ * the skipper from {@link BaseDocValuesSkipperTests#docValuesSkipper}.+ */+ private static long[] docValuePair(int doc, long queryMin, long queryMax) {+ int d = doc % 1024;+ long mid = (queryMin + queryMax) >> 1;+ if (d < 128) {+ return new long[] {queryMin, queryMax};+ } else if (d < 256) {+ return new long[] {queryMax + 1, queryMax + 1};+ } else if (d < 512) {+ return new long[] {queryMin - 1, queryMin - 1};+ } else {+ return switch ((d / 2) % 3) {+ case 0 -> new long[] {queryMin - 1, queryMax + 1};+ case 1 -> new long[] {queryMin, queryMax + 1};+ case 2 -> new long[] {queryMin - 1, mid};+ default -> throw new AssertionError();+ };+ }+ }++ private static boolean valueInRange(int doc) {+ long[] vals = docValuePair(doc, QUERY_MIN, QUERY_MAX);+ for (long v : vals) {+ if (v >= QUERY_MIN && v <= QUERY_MAX) {+ return true;+ }+ }+ return false;+ }++ private static boolean docHasValue(int doc) {+ return doc < 1024 || (doc < 2048 && (doc & 1) == 0);+ }++ private static List<Integer> expectedMatches() {+ List<Integer> matches = new ArrayList<>();+ for (int doc = 0; doc < 2048; doc++) {+ if (docHasValue(doc) && valueInRange(doc)) {+ matches.add(doc);+ }+ }+ return matches;+ }++ private static SortedNumericDocValues sortedNumericDocValues(long queryMin, long queryMax) {+ return new SortedNumericDocValues() {+ int doc = -1;+ int valueIdx = 0;++ @Override+ public boolean advanceExact(int target) throws IOException {+ throw new UnsupportedOperationException();+ }++ @Override+ public int docID() {+ return doc;+ }++ @Override+ public int nextDoc() throws IOException {+ return advance(doc + 1);+ }++ @Override+ public int advance(int target) throws IOException {+ valueIdx = 0;+ if (target < 1024) {+ return doc = target;+ } else if (target < 2048) {+ doc = target + (target & 1);+ return doc < 2048 ? doc : (doc = DocIdSetIterator.NO_MORE_DOCS);+ } else {+ return doc = DocIdSetIterator.NO_MORE_DOCS;+ }+ }++ @Override+ public int docValueCount() {+ return 2;+ }++ @Override+ public long nextValue() {+ long[] vals = docValuePair(doc, queryMin, queryMax);+ return vals[valueIdx++];+ }++ @Override+ public long cost() {+ return 42;+ }+ };+ }++ private static List<Integer> collectMatches(DocValuesRangeIterator iter) throws IOException {+ List<Integer> matches = new ArrayList<>();+ DocIdSetIterator approx = iter.approximation();+ while (approx.nextDoc() != DocIdSetIterator.NO_MORE_DOCS) {+ if (iter.matches()) {+ matches.add(approx.docID());+ }+ }+ return matches;+ }++ private DocValuesRangeIterator createIterator(boolean multiLevel) {+ SortedNumericDocValues values = sortedNumericDocValues(QUERY_MIN, QUERY_MAX);+ DocValuesSkipper skipper = docValuesSkipper(QUERY_MIN, QUERY_MAX, multiLevel);+ return DocValuesRangeIterator.forRange(values, skipper, QUERY_MIN, QUERY_MAX);+ }++ // --- Correctness: all matching docs are found and no false positives ---++ public void testCorrectResultsSingleLevel() throws IOException {+ assertEquals(expectedMatches(), collectMatches(createIterator(false)));+ }++ public void testCorrectResultsMultipleLevels() throws IOException {+ assertEquals(expectedMatches(), collectMatches(createIterator(true)));+ }++ // --- Multi-value specific behavior ---++ public void testMatchOnFirstValueInRange() throws IOException {+ // Doc 512: (512/2)%3 = 1 → values [queryMin, queryMax+1]+ // First value is in range → immediate match.+ DocValuesRangeIterator iter = createIterator(true);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();+ approx.advance(512);+ assertTrue(iter.matches());+ }++ public void testMatchOnSecondValue() throws IOException {+ // Doc 514: (514/2)%3 = 2 → values [queryMin-1, mid]+ // First value below range (skipped), second value in range → match.+ DocValuesRangeIterator iter = createIterator(true);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();+ approx.advance(514);+ assertTrue(iter.matches());+ }++ public void testNoMatchWhenValuesBracketRange() throws IOException {+ // Doc 516: (516/2)%3 = 0 → values [queryMin-1, queryMax+1]+ // Values span below and above the range, but none falls within it.+ // The sorted-value optimization correctly rejects: first value < min+ // is skipped, second value >= min but > max → no match.+ DocValuesRangeIterator iter = createIterator(true);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();+ approx.advance(516);+ assertFalse(iter.matches());+ }++ // --- Approximation correctly skips non-matching blocks ---++ public void testApproximationSkipsAboveRangeBlock() throws IOException {+ DocValuesRangeIterator iter = createIterator(true);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();+ assertEquals(512, approx.advance(128));+ }++ public void testApproximationSkipsBelowRangeBlock() throws IOException {+ DocValuesRangeIterator iter = createIterator(true);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();+ assertEquals(512, approx.advance(300));+ }++ public void testApproximationSkipsFromEndOfMatchingBlock() throws IOException {+ DocValuesRangeIterator iter = createIterator(true);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();+ assertEquals(100, approx.advance(100));+ assertEquals(512, approx.advance(128));+ }++ public void testApproximationIteratesWithinMatchingBlock() throws IOException {+ DocValuesRangeIterator iter = createIterator(true);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();+ assertEquals(10, approx.advance(10));+ assertEquals(11, approx.nextDoc());+ assertEquals(12, approx.nextDoc());+ assertEquals(50, approx.advance(50));+ }++ public void testApproximationSkipsSparseNonMatchingBlocks() throws IOException {+ DocValuesRangeIterator iter = createIterator(true);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();+ assertEquals(1536, approx.advance(1200));+ }++ public void testApproximationExhausted() throws IOException {+ DocValuesRangeIterator iter = createIterator(true);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();+ assertEquals(DocIdSetIterator.NO_MORE_DOCS, approx.advance(2048));+ }++ // --- Match classification ---++ public void testYesMatchInDenseBlock() throws IOException {+ DocValuesRangeIterator iter = createIterator(true);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();+ approx.advance(0);+ assertEquals(SkipBlockRangeIterator.Match.YES, approx.getMatch());+ assertTrue(iter.matches());+ }++ public void testYesMatchDoesNotAdvanceDocValues() throws IOException {+ SortedNumericDocValues values = sortedNumericDocValues(QUERY_MIN, QUERY_MAX);+ DocValuesSkipper skipper = docValuesSkipper(QUERY_MIN, QUERY_MAX, true);+ DocValuesRangeIterator iter =+ DocValuesRangeIterator.forRange(values, skipper, QUERY_MIN, QUERY_MAX);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();++ approx.advance(100);+ assertEquals(SkipBlockRangeIterator.Match.YES, approx.getMatch());+ assertTrue(iter.matches());+ assertTrue(values.docID() < approx.docID());+ }++ public void testMaybeMatchClassification() throws IOException {+ DocValuesRangeIterator iter = createIterator(true);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();+ approx.advance(512);+ assertEquals(SkipBlockRangeIterator.Match.MAYBE, approx.getMatch());+ }++ public void testMaybeMatchChecksMultipleValues() throws IOException {+ DocValuesRangeIterator iter = createIterator(true);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();++ // d=512: case 1 → [queryMin, queryMax+1] → match on first value+ approx.advance(512);+ assertTrue(iter.matches());++ // d=514: case 2 → [queryMin-1, mid] → match on second value+ approx.advance(514);+ assertTrue(iter.matches());++ // d=515: case 2 → same pair → match on second value+ approx.advance(515);+ assertTrue(iter.matches());++ // d=516: case 0 → [queryMin-1, queryMax+1] → no match (brackets range)+ approx.advance(516);+ assertFalse(iter.matches());+ }++ public void testYesIfPresentInSparseBlock() throws IOException {+ DocValuesRangeIterator iter = createIterator(true);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();++ approx.advance(1024);+ assertEquals(SkipBlockRangeIterator.Match.YES_IF_PRESENT, approx.getMatch());+ // Even doc has a value → match+ assertTrue(iter.matches());++ approx.advance(1025);+ assertEquals(SkipBlockRangeIterator.Match.YES_IF_PRESENT, approx.getMatch());+ // Odd doc has no value → no match+ assertFalse(iter.matches());+ }++ // --- docIdRunEnd ---++ public void testDocIdRunEndYesBlockMultipleLevels() throws IOException {+ DocValuesRangeIterator iter = createIterator(true);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();++ approx.advance(0);+ assertEquals(SkipBlockRangeIterator.Match.YES, approx.getMatch());+ assertEquals(128, iter.docIDRunEnd());+ }++ public void testDocIdRunEndExtendsFromMiddleOfBlock() throws IOException {+ DocValuesRangeIterator iter = createIterator(true);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();++ approx.advance(64);+ assertEquals(SkipBlockRangeIterator.Match.YES, approx.getMatch());+ assertEquals(128, iter.docIDRunEnd());++ approx.advance(100);+ assertEquals(128, iter.docIDRunEnd());+ }++ public void testDocIdRunEndConsistentAcrossYesBlock() throws IOException {+ DocValuesRangeIterator iter = createIterator(true);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();++ for (int doc = 0; doc < 128; doc++) {+ approx.advance(doc);+ assertEquals(SkipBlockRangeIterator.Match.YES, approx.getMatch());+ assertEquals(+ "docIdRunEnd at doc " + doc + " should extend to level 1 boundary",+ 128,+ iter.docIDRunEnd());+ }+ }++ public void testDocIdRunEndMaybeBlock() throws IOException {+ DocValuesRangeIterator iter = createIterator(true);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();++ approx.advance(512);+ assertEquals(SkipBlockRangeIterator.Match.MAYBE, approx.getMatch());+ assertEquals(513, iter.docIDRunEnd());++ approx.advance(800);+ assertEquals(SkipBlockRangeIterator.Match.MAYBE, approx.getMatch());+ assertEquals(801, iter.docIDRunEnd());+ }++ public void testDocIdRunEndYesIfPresentBlock() throws IOException {+ DocValuesRangeIterator iter = createIterator(true);+ SkipBlockRangeIterator approx = (SkipBlockRangeIterator) iter.approximation();++ approx.advance(1024);+ assertEquals(SkipBlockRangeIterator.Match.YES_IF_PRESENT, approx.getMatch());+ assertEquals(1025, iter.docIDRunEnd());+ }+}diff --git a/lucene/sandbox/src/java/org/apache/lucene/sandbox/search/SortedNumericDocValuesMultiRangeQuery.java b/lucene/sandbox/src/java/org/apache/lucene/sandbox/search/SortedNumericDocValuesMultiRangeQuery.javaindex 46aeaac6a5e..dc87ec6e647 100644--- a/lucene/sandbox/src/java/org/apache/lucene/sandbox/search/SortedNumericDocValuesMultiRangeQuery.java+++ b/lucene/sandbox/src/java/org/apache/lucene/sandbox/search/SortedNumericDocValuesMultiRangeQuery.java@@ -31,12 +31,13 @@ import org.apache.lucene.index.LeafReaderContext;import org.apache.lucene.index.SortedNumericDocValues;import org.apache.lucene.search.ConstantScoreScorerSupplier;import org.apache.lucene.search.ConstantScoreWeight;-import org.apache.lucene.search.DocValuesRangeIterator;+import org.apache.lucene.search.DocIdSetIterator;import org.apache.lucene.search.IndexSearcher;import org.apache.lucene.search.Query;import org.apache.lucene.search.QueryVisitor;import org.apache.lucene.search.ScoreMode;import org.apache.lucene.search.ScorerSupplier;+import org.apache.lucene.search.SkipBlockRangeIterator;import org.apache.lucene.search.TwoPhaseIterator;import org.apache.lucene.search.Weight;@@ -221,14 +222,21 @@ public class SortedNumericDocValuesMultiRangeQuery extends Query {}SortedNumericDocValues values = DocValues.getSortedNumeric(context.reader(), fieldName);- TwoPhaseIterator iterator;- iterator =- new TwoPhaseIterator(values) {+ DocIdSetIterator approximation = values;+ if (skipper != null) {+ approximation = new SkipBlockRangeIterator(skipper, lowerValue, upperValue);+ }+ TwoPhaseIterator iterator =+ new TwoPhaseIterator(approximation) {final DocValuesMultiRangeQuery.LongRange lookupVal =new DocValuesMultiRangeQuery.LongRange(-Long.MAX_VALUE, -Long.MAX_VALUE);@Overridepublic boolean matches() throws IOException {+ int doc = approximation().docID();+ if (values.docID() < doc && values.advance(doc) != doc) {+ return false;+ }NavigableSet<DocValuesMultiRangeQuery.LongRange> rangeTree = sortedClauses;for (int i = 0, count = values.docValueCount(); i < count; ++i) {final long value = values.nextValue();@@ -259,11 +267,6 @@ public class SortedNumericDocValuesMultiRangeQuery extends Query {return sortedClauses.size();}};- if (skipper != null) {- iterator =- new DocValuesRangeIterator(- iterator, skipper, lowerValue, upperValue, sortedClauses.size() > 1);- }return ConstantScoreScorerSupplier.fromIterator(TwoPhaseIterator.asDocIdSetIterator(iterator), score(), scoreMode, maxDoc);}diff --git a/lucene/sandbox/src/java/org/apache/lucene/sandbox/search/SortedSetDocValuesMultiRangeQuery.java b/lucene/sandbox/src/java/org/apache/lucene/sandbox/search/SortedSetDocValuesMultiRangeQuery.javaindex aef7034c286..bdfe0edaf70 100644--- a/lucene/sandbox/src/java/org/apache/lucene/sandbox/search/SortedSetDocValuesMultiRangeQuery.java+++ b/lucene/sandbox/src/java/org/apache/lucene/sandbox/search/SortedSetDocValuesMultiRangeQuery.java@@ -37,7 +37,6 @@ import org.apache.lucene.search.QueryVisitor;import org.apache.lucene.search.ScoreMode;import org.apache.lucene.search.Scorer;import org.apache.lucene.search.ScorerSupplier;-import org.apache.lucene.search.TwoPhaseIterator;import org.apache.lucene.search.Weight;import org.apache.lucene.util.BytesRef;import org.apache.lucene.util.LongBitSet;@@ -195,59 +194,26 @@ public class SortedSetDocValuesMultiRangeQuery extends Query {List<OrdRange> ordRanges = new ArrayList<>();createOrdRanges(values, ordRanges);if (ordRanges.isEmpty()) {- return empty();+ return new ConstantScoreScorer(score(), scoreMode, DocIdSetIterator.empty());}- LongBitSet matchingOrdsShifted = null;long minOrd = ordRanges.getFirst().lower, maxOrd = ordRanges.getLast().upper;DocValuesSkipper skipper = context.reader().getDocValuesSkipper(fieldName);-- if (skipper != null && (minOrd > skipper.maxValue() || maxOrd < skipper.minValue())) {- return empty();- }-- if (ordRanges.size() > 1) {- matchingOrdsShifted = new LongBitSet(maxOrd + 1 - minOrd);- for (OrdRange range : ordRanges) {- matchingOrdsShifted.set(- range.lower - minOrd, range.upper - minOrd + 1); // up is exclusive- }+ if (ordRanges.size() == 1) {+ return new ConstantScoreScorer(+ score(),+ scoreMode,+ DocValuesRangeIterator.forOrdinalRange(values, skipper, minOrd, maxOrd));}- TwoPhaseIterator iterator;- LongBitSet finalMatchingOrdsShifted = matchingOrdsShifted;- iterator =- new TwoPhaseIterator(values) {- // TODO unwrap singleton?- @Override- public boolean matches() throws IOException {- for (int i = 0; i < values.docValueCount(); i++) {- long ord = values.nextOrd();- if (ord >= minOrd && ord <= maxOrd) {- if (finalMatchingOrdsShifted == null // singleton- || finalMatchingOrdsShifted.get(ord - minOrd)) {- return true;- }- }- }- return false;- }- @Override- public float matchCost() {- return 2; // 2 comparisons- }- };- // }- if (skipper != null) {- iterator =- new DocValuesRangeIterator(- iterator, skipper, minOrd, maxOrd, matchingOrdsShifted != null);+ LongBitSet matchingOrds = new LongBitSet(maxOrd + 1);+ for (OrdRange ordRange : ordRanges) {+ matchingOrds.set(ordRange.lower, ordRange.upper + 1);}- return new ConstantScoreScorer(score(), scoreMode, iterator);- }-- protected ConstantScoreScorer empty() {- return new ConstantScoreScorer(score(), scoreMode, DocIdSetIterator.empty());+ return new ConstantScoreScorer(+ score(),+ scoreMode,+ DocValuesRangeIterator.forOrdinalSet(values, skipper, minOrd, maxOrd, matchingOrds));}@Override