Apache Lucene open-source search software
Bulk nextDocsAndScores for constant-score disjunction clauses (#16394)
Chengxi Shi61e22dd3e60e
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txtindex 2cf190740d8..426775464c2 100644--- a/lucene/CHANGES.txt+++ b/lucene/CHANGES.txt@@ -349,6 +349,11 @@ ImprovementsOptimizations---------------------+* GITHUB#16394: Add DocIdSetIterator#intoArray, which DisjunctionDISIApproximation implements by+ loading a window of doc IDs through #intoBitSet rather than one nextDoc() call per match.+ ConstantScoreScorer#nextDocsAndScores now builds on it, which avoids a priority-queue update per+ matching doc under MaxScoreBulkScorer's term-at-a-time scoring. (Chengxi Shi)+* GITHUG#16280: Single-pass writeString fast path for short strings in ByteBuffersDataOutput (neoremind)* GITHUB#16146: Speed up no-score filtered-optional Boolean queries by routing dense conjunctions with cached FixedBitSet filtersdiff --git a/lucene/core/src/java/org/apache/lucene/search/ConstantScoreScorer.java b/lucene/core/src/java/org/apache/lucene/search/ConstantScoreScorer.javaindex e428191c413..43b5da3dce5 100644--- a/lucene/core/src/java/org/apache/lucene/search/ConstantScoreScorer.java+++ b/lucene/core/src/java/org/apache/lucene/search/ConstantScoreScorer.java@@ -58,9 +58,27 @@ public final class ConstantScoreScorer extends Scorer {@Overridepublic void intoBitSet(int upTo, FixedBitSet bitSet, int offset) throws IOException {+ if (doc != delegate.docID()) {+ // The delegate was swapped for an empty iterator (see setMinCompetitiveScore); the+ // default implementation terminates via nextDoc() without touching the stale delegate+ // position.+ super.intoBitSet(upTo, bitSet, offset);+ return;+ }delegate.intoBitSet(upTo, bitSet, offset);doc = delegate.docID();}++ @Override+ public int intoArray(int upTo, int[] docs) throws IOException {+ if (doc != delegate.docID()) {+ // See #intoBitSet.+ return super.intoArray(upTo, docs);+ }+ int size = delegate.intoArray(upTo, docs);+ doc = delegate.docID();+ return size;+ }}private final float score;@@ -154,20 +172,29 @@ public final class ConstantScoreScorer extends Scorer {return score;}+ // Number of doc IDs that a single #nextDocsAndScores call loads at a time. It matches+ // MaxScoreBulkScorer#INNER_WINDOW_SIZE, so that iterators which load doc IDs in bulk, such as+ // disjunctions, can cover a full inner scoring window in a single call.+ private static final int BATCH_SIZE = 4096;+@Overridepublic void nextDocsAndScores(int upTo, Bits liveDocs, DocAndFloatFeatureBuffer buffer)throws IOException {- int batchSize = 64;- buffer.growNoCopy(batchSize);- int size = 0;DocIdSetIterator iterator = iterator();- for (int doc = iterator.docID(); doc < upTo && size < batchSize; doc = iterator.nextDoc()) {- if (liveDocs == null || liveDocs.get(doc)) {- buffer.docs[size] = doc;- ++size;+ buffer.growNoCopy(BATCH_SIZE);+ for (; ; ) {+ buffer.size = iterator.intoArray(upTo, buffer.docs);+ Arrays.fill(buffer.features, 0, buffer.size, score);+ if (liveDocs == null || buffer.size == 0) {+ break;+ }+ buffer.apply(liveDocs);+ // An empty buffer indicates that there are no docs left before upTo. We may be unlucky, and+ // there are docs left, but all docs from the current batch happen to be marked as deleted.+ // So we need to iterate until we find a batch that has at least one non-deleted doc.+ if (buffer.size != 0) {+ break;}}- Arrays.fill(buffer.features, 0, size, score);- buffer.size = size;}}diff --git a/lucene/core/src/java/org/apache/lucene/search/DisjunctionDISIApproximation.java b/lucene/core/src/java/org/apache/lucene/search/DisjunctionDISIApproximation.javaindex ef5b1bbbff9..c3bba2746c5 100644--- a/lucene/core/src/java/org/apache/lucene/search/DisjunctionDISIApproximation.java+++ b/lucene/core/src/java/org/apache/lucene/search/DisjunctionDISIApproximation.java@@ -31,6 +31,11 @@ import org.apache.lucene.util.FixedBitSet;*/public final class DisjunctionDISIApproximation extends AbstractDocIdSetIterator {+ // Doc ID window that a single #intoArray call loads at a time. It matches+ // MaxScoreBulkScorer#INNER_WINDOW_SIZE and DenseConjunctionBulkScorer#WINDOW_SIZE so that a+ // single window covers a full scoring window, with a bit set that stays cache-resident.+ private static final int WINDOW_SIZE = 4096;+public static DisjunctionDISIApproximation of(Collection<? extends DisiWrapper> subIterators, long leadCost) {@@ -44,6 +49,7 @@ public final class DisjunctionDISIApproximation extends AbstractDocIdSetIteratorprivate final long cost;private DisiWrapper leadTop;private int minOtherDoc;+ private FixedBitSet window; // lazily allocated by #intoArraypublic DisjunctionDISIApproximation(Collection<? extends DisiWrapper> subIterators, long leadCost) {@@ -161,6 +167,32 @@ public final class DisjunctionDISIApproximation extends AbstractDocIdSetIteratordoc = Math.min(leadTop.doc, minOtherDoc);}+ @Override+ public int intoArray(int upTo, int[] docs) throws IOException {+ assert docs.length > 0;+ // Loading a window of doc IDs through #intoBitSet performs one bulk load and one heap update+ // per sub-iterator, while advancing one doc at a time performs a heap update per matching doc.+ // The current doc always falls into the first window, so the loop below normally runs a single+ // iteration. It only guards against a window that yields no doc, which callers would read as+ // "no doc left below upTo".+ int windowSize = Math.min(docs.length, WINDOW_SIZE);+ while (doc < upTo) {+ if (window == null) {+ window = new FixedBitSet(WINDOW_SIZE);+ } else {+ window.clear();+ }+ int windowMin = doc;+ int windowMax = (int) Math.min(upTo, (long) windowMin + windowSize);+ intoBitSet(windowMax, window, windowMin);+ int size = window.intoArray(0, windowMax - windowMin, windowMin, docs);+ if (size != 0) {+ return size;+ }+ }+ return 0;+ }+/** Return the linked list of iterators positioned on the current doc. */public DisiWrapper topList() {if (leadTop.doc < minOtherDoc) {diff --git a/lucene/core/src/java/org/apache/lucene/search/DocIdSetIterator.java b/lucene/core/src/java/org/apache/lucene/search/DocIdSetIterator.javaindex 9443985c20f..aa6e3331ecb 100644--- a/lucene/core/src/java/org/apache/lucene/search/DocIdSetIterator.java+++ b/lucene/core/src/java/org/apache/lucene/search/DocIdSetIterator.java@@ -209,6 +209,39 @@ public abstract class DocIdSetIterator {}}+ /**+ * Copy doc IDs of this iterator into the given array, starting at the current {@link #docID()}+ * and stopping before {@code upTo}, and return the number of copied doc IDs. At most {@code+ * docs.length} doc IDs are copied, so callers must call this method repeatedly in order to+ * consume all doc IDs below {@code upTo}. Upon return, this iterator is positioned on the first+ * doc ID that has not been copied.+ *+ * <p>A return value of {@code 0} means that this iterator has no doc ID left below {@code upTo}.+ * Implementations must never return {@code 0} while doc IDs below {@code upTo} remain.+ *+ * <p>This should behave exactly as if implemented as below, which is the default implementation:+ *+ * <pre><code class="language-java">+ * int size = 0;+ * for (int doc = docID(); doc < upTo && size < docs.length; doc = nextDoc()) {+ * docs[size++] = doc;+ * }+ * return size;+ * </code></pre>+ *+ * <p><b>Note</b>: The given array must not be empty. Behaviour is undefined if this iterator is+ * unpositioned.+ *+ * @lucene.internal+ */+ public int intoArray(int upTo, int[] docs) throws IOException {+ int size = 0;+ for (int doc = docID(); doc < upTo && size < docs.length; doc = nextDoc()) {+ docs[size++] = doc;+ }+ return size;+ }+/*** Returns the end of the run of consecutive doc IDs that match this {@link DocIdSetIterator} and* that contains the current {@link #docID()}, that is: one plus the last doc ID of the run.diff --git a/lucene/core/src/test/org/apache/lucene/search/TestConstantScoreScorer.java b/lucene/core/src/test/org/apache/lucene/search/TestConstantScoreScorer.javaindex c18cd88a2f7..ca1cc45f98b 100644--- a/lucene/core/src/test/org/apache/lucene/search/TestConstantScoreScorer.java+++ b/lucene/core/src/test/org/apache/lucene/search/TestConstantScoreScorer.java@@ -20,6 +20,7 @@ import static org.apache.lucene.search.BooleanClause.Occur;import static org.apache.lucene.search.DocIdSetIterator.NO_MORE_DOCS;import java.io.IOException;+import java.util.ArrayList;import java.util.List;import org.apache.lucene.analysis.Analyzer;import org.apache.lucene.document.Document;@@ -32,7 +33,12 @@ import org.apache.lucene.index.Term;import org.apache.lucene.store.Directory;import org.apache.lucene.tests.analysis.MockAnalyzer;import org.apache.lucene.tests.index.RandomIndexWriter;+import org.apache.lucene.tests.search.AssertingScorer;import org.apache.lucene.tests.util.LuceneTestCase;+import org.apache.lucene.tests.util.TestUtil;+import org.apache.lucene.util.BitSetIterator;+import org.apache.lucene.util.Bits;+import org.apache.lucene.util.FixedBitSet;public class TestConstantScoreScorer extends LuceneTestCase {private static final String FIELD = "f";@@ -221,6 +227,158 @@ public class TestConstantScoreScorer extends LuceneTestCase {}}+ /**+ * An empty {@link DocAndFloatFeatureBuffer} tells callers that the iterator has no doc left+ * before {@code upTo}, so batches whose docs are all deleted must not be reported as such.+ */+ public void testNextDocsAndScoresSkipsFullyDeletedBatches() throws IOException {+ int maxDoc = 10_000;+ int firstLiveDoc = 9_000;+ Bits liveDocs =+ new Bits() {+ @Override+ public boolean get(int index) {+ return index >= firstLiveDoc;+ }++ @Override+ public int length() {+ return maxDoc;+ }+ };++ for (ScoreMode scoreMode : new ScoreMode[] {ScoreMode.COMPLETE, ScoreMode.TOP_SCORES}) {+ for (boolean disjunction : new boolean[] {false, true}) {+ DocIdSetIterator disi;+ if (disjunction) {+ disi =+ DisjunctionDISIApproximation.of(+ List.of(+ new DisiWrapper(+ new ConstantScoreScorer(+ 1f, ScoreMode.COMPLETE_NO_SCORES, DocIdSetIterator.range(0, 5_000)),+ false),+ new DisiWrapper(+ new ConstantScoreScorer(+ 1f,+ ScoreMode.COMPLETE_NO_SCORES,+ DocIdSetIterator.range(5_000, maxDoc)),+ false)),+ maxDoc);+ } else {+ disi = DocIdSetIterator.all(maxDoc);+ }++ ConstantScoreScorer scorer = new ConstantScoreScorer(2f, scoreMode, disi);+ assertEquals(0, scorer.iterator().nextDoc());++ DocAndFloatFeatureBuffer buffer = new DocAndFloatFeatureBuffer();+ List<Integer> collected = new ArrayList<>();+ for (scorer.nextDocsAndScores(maxDoc, liveDocs, buffer);+ buffer.size > 0;+ scorer.nextDocsAndScores(maxDoc, liveDocs, buffer)) {+ for (int i = 0; i < buffer.size; ++i) {+ collected.add(buffer.docs[i]);+ assertEquals(2f, buffer.features[i], 0f);+ }+ }++ List<Integer> expected = new ArrayList<>();+ for (int doc = firstLiveDoc; doc < maxDoc; ++doc) {+ expected.add(doc);+ }+ assertEquals(expected, collected);+ }+ }+ }++ /**+ * Randomized companion to the test above. Reaching a fully deleted batch takes a doc ID range+ * that spans more than one batch together with deletions that cluster, so uniformly random+ * deletions over the small indexes that most randomized tests build never get there. Scorers are+ * wrapped in {@link AssertingScorer} so that the buffer contract is checked as well.+ */+ public void testNextDocsAndScoresRandomClusteredDeletions() throws IOException {+ int iters = atLeast(10);+ for (int iter = 0; iter < iters; ++iter) {+ int maxDoc = TestUtil.nextInt(random(), 12_000, 30_000);+ float density = 1f / (1 << random().nextInt(3));++ FixedBitSet matches = new FixedBitSet(maxDoc);+ for (int doc = 0; doc < maxDoc; ++doc) {+ if (random().nextFloat() < density) {+ matches.set(doc);+ }+ }+ if (matches.cardinality() == 0) {+ continue;+ }++ // A run of deleted docs wide enough to swallow a whole batch whatever its alignment, plus+ // scattered deletions.+ FixedBitSet liveDocs = new FixedBitSet(maxDoc);+ liveDocs.set(0, maxDoc);+ int runLength = TestUtil.nextInt(random(), 2 * 4096, 3 * 4096);+ int runStart = TestUtil.nextInt(random(), 0, maxDoc - runLength);+ liveDocs.clear(runStart, runStart + runLength);+ for (int i = 0, scattered = random().nextInt(100); i < scattered; ++i) {+ liveDocs.clear(random().nextInt(maxDoc));+ }++ List<Integer> expected = new ArrayList<>();+ for (int doc = 0; doc < maxDoc; ++doc) {+ if (matches.get(doc) && liveDocs.get(doc)) {+ expected.add(doc);+ }+ }++ DocIdSetIterator disi;+ if (random().nextBoolean()) {+ int numSubs = TestUtil.nextInt(random(), 2, 4);+ FixedBitSet[] subSets = new FixedBitSet[numSubs];+ for (int i = 0; i < numSubs; ++i) {+ subSets[i] = new FixedBitSet(maxDoc);+ }+ for (int doc = 0; doc < maxDoc; ++doc) {+ if (matches.get(doc)) {+ subSets[random().nextInt(numSubs)].set(doc);+ }+ }+ List<DisiWrapper> subs = new ArrayList<>();+ for (FixedBitSet subSet : subSets) {+ subs.add(+ new DisiWrapper(+ new ConstantScoreScorer(+ 1f,+ ScoreMode.COMPLETE_NO_SCORES,+ new BitSetIterator(subSet, subSet.cardinality())),+ false));+ }+ disi = DisjunctionDISIApproximation.of(subs, maxDoc);+ } else {+ disi = new BitSetIterator(matches, matches.cardinality());+ }++ ScoreMode scoreMode = random().nextBoolean() ? ScoreMode.COMPLETE : ScoreMode.TOP_SCORES;+ Scorer scorer =+ AssertingScorer.wrap(new ConstantScoreScorer(2f, scoreMode, disi), true, false);+ scorer.iterator().nextDoc();++ DocAndFloatFeatureBuffer buffer = new DocAndFloatFeatureBuffer();+ List<Integer> collected = new ArrayList<>();+ for (scorer.nextDocsAndScores(maxDoc, liveDocs, buffer);+ buffer.size > 0;+ scorer.nextDocsAndScores(maxDoc, liveDocs, buffer)) {+ for (int i = 0; i < buffer.size; ++i) {+ collected.add(buffer.docs[i]);+ assertEquals(2f, buffer.features[i], 0f);+ }+ }++ assertEquals(expected, collected);+ }+ }+public void testEarlyTermination() throws IOException {Analyzer analyzer = new MockAnalyzer(random());Directory dir = newDirectory();diff --git a/lucene/core/src/test/org/apache/lucene/search/TestDisjunctionDISIApproximation.java b/lucene/core/src/test/org/apache/lucene/search/TestDisjunctionDISIApproximation.javaindex 8f17a19187d..96aea5387cb 100644--- a/lucene/core/src/test/org/apache/lucene/search/TestDisjunctionDISIApproximation.java+++ b/lucene/core/src/test/org/apache/lucene/search/TestDisjunctionDISIApproximation.java@@ -17,8 +17,11 @@package org.apache.lucene.search;import java.io.IOException;+import java.util.ArrayList;import java.util.Arrays;+import java.util.List;import org.apache.lucene.tests.util.LuceneTestCase;+import org.apache.lucene.tests.util.TestUtil;public class TestDisjunctionDISIApproximation extends LuceneTestCase {@@ -64,6 +67,89 @@ public class TestDisjunctionDISIApproximation extends LuceneTestCase {assertEquals(110, iterator.docIDRunEnd());}+ public void testIntoArray() throws IOException {+ DisjunctionDISIApproximation iterator =+ disjunction(100_000, DocIdSetIterator.range(10, 20), DocIdSetIterator.range(15, 30));+ assertEquals(10, iterator.nextDoc());++ // The bulk window is bounded by the length of the target array, so that no match is dropped.+ int[] docs = new int[8];+ assertEquals(8, iterator.intoArray(DocIdSetIterator.NO_MORE_DOCS, docs));+ assertArrayEquals(new int[] {10, 11, 12, 13, 14, 15, 16, 17}, docs);+ assertEquals(18, iterator.docID());++ docs = new int[64];+ assertEquals(12, iterator.intoArray(DocIdSetIterator.NO_MORE_DOCS, docs));+ for (int i = 0; i < 12; ++i) {+ assertEquals(18 + i, docs[i]);+ }+ assertEquals(DocIdSetIterator.NO_MORE_DOCS, iterator.docID());+ assertEquals(0, iterator.intoArray(DocIdSetIterator.NO_MORE_DOCS, docs));+ }++ public void testIntoArrayReturnsSameDocsAsNextDoc() throws IOException {+ for (int iter = 0; iter < 100; ++iter) {+ int maxDoc = TestUtil.nextInt(random(), 1, 20_000);+ int numClauses = TestUtil.nextInt(random(), 2, 5);+ int[][] ranges = new int[numClauses][];+ for (int i = 0; i < numClauses; ++i) {+ int min = random().nextInt(maxDoc);+ ranges[i] = new int[] {min, TestUtil.nextInt(random(), min + 1, maxDoc + 1)};+ }+ long leadCost = random().nextBoolean() ? 1 : Long.MAX_VALUE;++ List<Integer> expected = new ArrayList<>();+ DocIdSetIterator reference = disjunction(leadCost, ranges(ranges));+ for (int doc = reference.nextDoc();+ doc != DocIdSetIterator.NO_MORE_DOCS;+ doc = reference.nextDoc()) {+ expected.add(doc);+ }++ // #intoArray loads doc IDs by windows rather than one at a time, so it may return fewer doc+ // IDs per call than the default implementation. It must still return the exact same doc IDs+ // overall, and never return an empty array while doc IDs below upTo remain.+ List<Integer> actual = new ArrayList<>();+ DocIdSetIterator iterator = disjunction(leadCost, ranges(ranges));+ iterator.nextDoc();+ while (iterator.docID() != DocIdSetIterator.NO_MORE_DOCS) {+ int[] docs = new int[TestUtil.nextInt(random(), 1, 4096)];+ int upTo = iterator.docID() + random().nextInt(5_000);+ int size = iterator.intoArray(upTo, docs);+ if (size == 0) {+ assertTrue(iterator.docID() >= upTo);+ continue;+ }+ assertTrue(size <= docs.length);+ for (int i = 0; i < size; ++i) {+ assertTrue(docs[i] < upTo);+ actual.add(docs[i]);+ }+ assertTrue(iterator.docID() > docs[size - 1]);+ }+ assertEquals(expected, actual);+ }+ }++ private static DocIdSetIterator[] ranges(int[][] ranges) {+ DocIdSetIterator[] iterators = new DocIdSetIterator[ranges.length];+ for (int i = 0; i < ranges.length; ++i) {+ iterators[i] = DocIdSetIterator.range(ranges[i][0], ranges[i][1]);+ }+ return iterators;+ }++ private static DisjunctionDISIApproximation disjunction(+ long leadCost, DocIdSetIterator... clauses) {+ List<DisiWrapper> wrappers = new ArrayList<>();+ for (DocIdSetIterator clause : clauses) {+ wrappers.add(+ new DisiWrapper(+ new ConstantScoreScorer(1f, ScoreMode.COMPLETE_NO_SCORES, clause), false));+ }+ return new DisjunctionDISIApproximation(wrappers, leadCost);+ }+public void testDocIDRunEndDoesNotScanOtherIterators() throws IOException {DocIdSetIterator clause1 = DocIdSetIterator.range(10_000, 30_000);DocIdSetIterator clause2 = DocIdSetIterator.range(20_000, 50_000);diff --git a/lucene/core/src/test/org/apache/lucene/search/TestDocIdSetIterator.java b/lucene/core/src/test/org/apache/lucene/search/TestDocIdSetIterator.javaindex 7a4508f05a4..62c2f6340d3 100644--- a/lucene/core/src/test/org/apache/lucene/search/TestDocIdSetIterator.java+++ b/lucene/core/src/test/org/apache/lucene/search/TestDocIdSetIterator.java@@ -130,6 +130,32 @@ public class TestDocIdSetIterator extends LuceneTestCase {}}+ public void testIntoArray() throws Exception {+ DocIdSetIterator disi = DocIdSetIterator.range(5, 20);+ assertEquals(5, disi.nextDoc());++ // Stops when the array is full and leaves the iterator on the first doc that was not copied.+ int[] docs = new int[4];+ assertEquals(4, disi.intoArray(20, docs));+ assertArrayEquals(new int[] {5, 6, 7, 8}, docs);+ assertEquals(9, disi.docID());++ // Stops on upTo, which is exclusive.+ assertEquals(2, disi.intoArray(11, docs));+ assertEquals(9, docs[0]);+ assertEquals(10, docs[1]);+ assertEquals(11, disi.docID());++ // No doc left below upTo.+ assertEquals(0, disi.intoArray(11, docs));+ assertEquals(11, disi.docID());++ docs = new int[16];+ assertEquals(9, disi.intoArray(NO_MORE_DOCS, docs));+ assertEquals(NO_MORE_DOCS, disi.docID());+ assertEquals(0, disi.intoArray(NO_MORE_DOCS, docs));+ }+public void testDocIDRunEndAll() throws IOException {DocIdSetIterator it = DocIdSetIterator.all(13);assertEquals(0, it.nextDoc());diff --git a/lucene/test-framework/src/java/org/apache/lucene/tests/search/AssertingScorer.java b/lucene/test-framework/src/java/org/apache/lucene/tests/search/AssertingScorer.javaindex f0ef919761c..263a44f24ac 100644--- a/lucene/test-framework/src/java/org/apache/lucene/tests/search/AssertingScorer.java+++ b/lucene/test-framework/src/java/org/apache/lucene/tests/search/AssertingScorer.java@@ -298,5 +298,12 @@ public class AssertingScorer extends Scorer {state = IteratorState.ITERATING;}}+ assert buffer.size != 0 || doc >= upTo+ : "An empty buffer means that no doc is left before upTo="+ + upTo+ + ", but the iterator is on doc="+ + doc+ + ". Implementations that filter the buffer, e.g. on liveDocs, must keep loading"+ + " batches until one is non-empty.";}}