Skip to content

Apache Lucene open-source search software

Optimize disjunction docIDRunEnd (#16142)

Costin Leau8e90c661ca63
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txt
index ec542061d6f..529baa17db8 100644
--- a/lucene/CHANGES.txt
+++ b/lucene/CHANGES.txt
@@ -469,6 +469,8 @@ Optimizations
* GITHUB#15991: Load dense filters into bitset in MaxScoreBulkScorer. (Prithvi S)
+* GITHUB#16142: Optimize disjunction #docIDRunEnd to skip runs of excluded documents. (Costin Leau)
+
Bug Fixes
---------------------
* GITHUB#15754: Fix HTMLStripCharFilter to prevent tags from incorrectly consuming subsequent
diff --git a/lucene/benchmark-jmh/src/java/org/apache/lucene/benchmark/jmh/MustNotBooleanQueryBenchmark.java b/lucene/benchmark-jmh/src/java/org/apache/lucene/benchmark/jmh/MustNotBooleanQueryBenchmark.java
new file mode 100644
index 00000000000..1527314142a
--- /dev/null
+++ b/lucene/benchmark-jmh/src/java/org/apache/lucene/benchmark/jmh/MustNotBooleanQueryBenchmark.java
@@ -0,0 +1,165 @@
+/*
+ * 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.benchmark.jmh;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.concurrent.TimeUnit;
+import org.apache.lucene.document.Document;
+import org.apache.lucene.document.Field;
+import org.apache.lucene.document.StringField;
+import org.apache.lucene.index.DirectoryReader;
+import org.apache.lucene.index.IndexReader;
+import org.apache.lucene.index.IndexWriter;
+import org.apache.lucene.index.IndexWriterConfig;
+import org.apache.lucene.index.Term;
+import org.apache.lucene.search.BooleanClause.Occur;
+import org.apache.lucene.search.BooleanQuery;
+import org.apache.lucene.search.IndexSearcher;
+import org.apache.lucene.search.MatchAllDocsQuery;
+import org.apache.lucene.search.Query;
+import org.apache.lucene.search.TermQuery;
+import org.apache.lucene.search.TotalHitCountCollectorManager;
+import org.apache.lucene.store.Directory;
+import org.apache.lucene.store.MMapDirectory;
+import org.apache.lucene.util.IOUtils;
+import org.openjdk.jmh.annotations.Benchmark;
+import org.openjdk.jmh.annotations.BenchmarkMode;
+import org.openjdk.jmh.annotations.Fork;
+import org.openjdk.jmh.annotations.Level;
+import org.openjdk.jmh.annotations.Measurement;
+import org.openjdk.jmh.annotations.Mode;
+import org.openjdk.jmh.annotations.OutputTimeUnit;
+import org.openjdk.jmh.annotations.Param;
+import org.openjdk.jmh.annotations.Scope;
+import org.openjdk.jmh.annotations.Setup;
+import org.openjdk.jmh.annotations.State;
+import org.openjdk.jmh.annotations.TearDown;
+import org.openjdk.jmh.annotations.Warmup;
+
+/**
+ * Benchmarks dense interleaved MUST_NOT term disjunctions over a MatchAllDocsQuery.
+ *
+ * <p>Most documents are indexed with every prohibited term except one rotating hole, which keeps
+ * term posting lists dense enough that {@code DisjunctionDISIApproximation} splits some clauses
+ * into linear-scanned iterators. Periodic pass-through documents have no prohibited terms, so the
+ * query returns a small non-zero hit count while repeatedly invoking {@code ReqExclBulkScorer} and
+ * the exclusion disjunction's {@code docIDRunEnd()} path. The default setup builds 10M documents
+ * and force-merges to one segment to match the target regression scenario.
+ */
+@State(Scope.Benchmark)
+@BenchmarkMode(Mode.Throughput)
+@OutputTimeUnit(TimeUnit.SECONDS)
+@Warmup(iterations = 3, time = 3)
+@Measurement(iterations = 5, time = 5)
+@Fork(
+ value = 1,
+ warmups = 1,
+ jvmArgsAppend = {"-Xmx4g", "-Xms4g", "-XX:+AlwaysPreTouch"})
+public class MustNotBooleanQueryBenchmark {
+
+ private static final String EXCLUDED_FIELD = "excluded";
+ private static final String EXCLUDED_TERM_PREFIX = "term";
+ private static final int PASS_THROUGH_INTERVAL = 128;
+
+ private Directory dir;
+ private IndexReader reader;
+ private IndexSearcher searcher;
+ private Path path;
+ private Query query;
+ private TotalHitCountCollectorManager collectorManager;
+
+ @State(Scope.Benchmark)
+ public static class Params {
+ @Param({"10000000"})
+ public int docCount;
+
+ @Param({"3", "7", "11"})
+ public int mustNotTermCount;
+ }
+
+ @Setup(Level.Trial)
+ public void setup(Params params) throws IOException {
+ path = Files.createTempDirectory("mustNotBooleanQuery");
+ dir = MMapDirectory.open(path);
+
+ try (IndexWriter writer = new IndexWriter(dir, new IndexWriterConfig())) {
+ for (int docID = 0; docID < params.docCount; docID++) {
+ writer.addDocument(document(docID, params.mustNotTermCount));
+ }
+ writer.forceMerge(1);
+ reader = DirectoryReader.open(writer);
+ }
+
+ searcher = new IndexSearcher(reader);
+ searcher.setQueryCache(null);
+ query = query(params.mustNotTermCount);
+ collectorManager = new TotalHitCountCollectorManager(searcher.getSlices());
+ int expectedHitCount = (params.docCount - 1) / PASS_THROUGH_INTERVAL + 1;
+ int actualHitCount = searcher.search(query, collectorManager);
+ if (actualHitCount != expectedHitCount) {
+ throw new AssertionError("expected " + expectedHitCount + " hits but got " + actualHitCount);
+ }
+ }
+
+ private static Document document(int docID, int mustNotTermCount) {
+ Document doc = new Document();
+ if (docID % PASS_THROUGH_INTERVAL == 0) {
+ return doc;
+ }
+ int missingTerm = docID % mustNotTermCount;
+ for (int termOrd = 0; termOrd < mustNotTermCount; termOrd++) {
+ if (termOrd != missingTerm) {
+ doc.add(new StringField(EXCLUDED_FIELD, term(termOrd), Field.Store.NO));
+ }
+ }
+ return doc;
+ }
+
+ private static Query query(int mustNotTermCount) {
+ BooleanQuery.Builder builder = new BooleanQuery.Builder();
+ builder.add(MatchAllDocsQuery.INSTANCE, Occur.FILTER);
+ for (int termOrd = 0; termOrd < mustNotTermCount; termOrd++) {
+ builder.add(new TermQuery(new Term(EXCLUDED_FIELD, term(termOrd))), Occur.MUST_NOT);
+ }
+ return builder.build();
+ }
+
+ private static String term(int termOrd) {
+ return EXCLUDED_TERM_PREFIX + termOrd;
+ }
+
+ @TearDown(Level.Trial)
+ public void tearDown() throws IOException {
+ try {
+ IOUtils.close(reader, dir);
+ } finally {
+ reader = null;
+ dir = null;
+ if (path != null) {
+ IOUtils.rm(path);
+ path = null;
+ }
+ }
+ }
+
+ @Benchmark
+ public int searchMustNot() throws IOException {
+ return searcher.search(query, collectorManager);
+ }
+}
diff --git a/lucene/core/src/java/org/apache/lucene/search/DisjunctionDISIApproximation.java b/lucene/core/src/java/org/apache/lucene/search/DisjunctionDISIApproximation.java
index a408e8f9b0c..ef5b1bbbff9 100644
--- a/lucene/core/src/java/org/apache/lucene/search/DisjunctionDISIApproximation.java
+++ b/lucene/core/src/java/org/apache/lucene/search/DisjunctionDISIApproximation.java
@@ -187,12 +187,15 @@ public final class DisjunctionDISIApproximation extends AbstractDocIdSetIterator
@Override
public int docIDRunEnd() throws IOException {
- // We're only looking at the "top" clauses. In theory, we may be able to find longer runs if
- // other clauses have overlapping runs with the runs of the top clauses, but does it actually
- // happen in practice and would it buy much?
+ // Trade off longer run detection for a cheaper per-doc call: only inspect heap-led clauses
+ // that are already positioned on the current doc. Other iterators may be coincident with the
+ // current doc and have longer runs, or be the only clauses on the current doc, but scanning
+ // them here would cost O(N) on every call.
int maxDocIDRunEnd = super.docIDRunEnd();
- for (DisiWrapper w = topList(); w != null; w = w.next) {
- maxDocIDRunEnd = Math.max(maxDocIDRunEnd, w.approximation.docIDRunEnd());
+ if (leadTop.doc == doc) {
+ for (DisiWrapper w = leadIterators.topList(); w != null; w = w.next) {
+ maxDocIDRunEnd = Math.max(maxDocIDRunEnd, w.approximation.docIDRunEnd());
+ }
}
return maxDocIDRunEnd;
}
diff --git a/lucene/core/src/test/org/apache/lucene/search/TestDisjunctionDISIApproximation.java b/lucene/core/src/test/org/apache/lucene/search/TestDisjunctionDISIApproximation.java
index 3d13f76c35a..8f17a19187d 100644
--- a/lucene/core/src/test/org/apache/lucene/search/TestDisjunctionDISIApproximation.java
+++ b/lucene/core/src/test/org/apache/lucene/search/TestDisjunctionDISIApproximation.java
@@ -19,7 +19,6 @@ package org.apache.lucene.search;
import java.io.IOException;
import java.util.Arrays;
import org.apache.lucene.tests.util.LuceneTestCase;
-import org.apache.lucene.tests.util.TestUtil;
public class TestDisjunctionDISIApproximation extends LuceneTestCase {
@@ -27,7 +26,6 @@ public class TestDisjunctionDISIApproximation extends LuceneTestCase {
DocIdSetIterator clause1 = DocIdSetIterator.range(10_000, 30_000);
DocIdSetIterator clause2 = DocIdSetIterator.range(20_000, 50_000);
DocIdSetIterator clause3 = DocIdSetIterator.range(60_000, 60_001);
- long leadCost = TestUtil.nextLong(random(), 1, 100_000);
Scorer scorer1 = new ConstantScoreScorer(1f, ScoreMode.COMPLETE_NO_SCORES, clause1);
Scorer scorer2 = new ConstantScoreScorer(1f, ScoreMode.COMPLETE_NO_SCORES, clause2);
Scorer scorer3 = new ConstantScoreScorer(1f, ScoreMode.COMPLETE_NO_SCORES, clause3);
@@ -37,7 +35,8 @@ public class TestDisjunctionDISIApproximation extends LuceneTestCase {
new DisiWrapper(scorer1, false),
new DisiWrapper(scorer2, false),
new DisiWrapper(scorer3, false)),
- leadCost);
+ // High enough to keep all clauses in the lead heap.
+ 100_000);
assertEquals(10_000, iterator.nextDoc());
assertEquals(30_000, iterator.docIDRunEnd());
assertEquals(25_000, iterator.advance(25_000));
@@ -45,4 +44,45 @@ public class TestDisjunctionDISIApproximation extends LuceneTestCase {
assertEquals(60_000, iterator.advance(50_000));
assertEquals(60_001, iterator.docIDRunEnd());
}
+
+ public void testDocIDRunEndOnlyUsesLeadIteratorsWhenBothClausesMatchAndOtherHasLongerRun()
+ throws IOException {
+ DocIdSetIterator heapClause = DocIdSetIterator.range(100, 110);
+ DocIdSetIterator otherIteratorClause = DocIdSetIterator.range(100, 200);
+ Scorer heapScorer = new ConstantScoreScorer(1f, ScoreMode.COMPLETE_NO_SCORES, heapClause);
+ Scorer otherIteratorScorer =
+ new ConstantScoreScorer(1f, ScoreMode.COMPLETE_NO_SCORES, otherIteratorClause);
+ DocIdSetIterator iterator =
+ new DisjunctionDISIApproximation(
+ Arrays.asList(
+ new DisiWrapper(heapScorer, false), new DisiWrapper(otherIteratorScorer, false)),
+ // Low enough to put the shorter, lower-cost clause in the lead heap and the longer,
+ // higher-cost clause in otherIterators.
+ 10);
+ // Both clauses match doc 100, but the longer otherIterator run is ignored.
+ assertEquals(100, iterator.nextDoc());
+ assertEquals(110, iterator.docIDRunEnd());
+ }
+
+ public void testDocIDRunEndDoesNotScanOtherIterators() throws IOException {
+ DocIdSetIterator clause1 = DocIdSetIterator.range(10_000, 30_000);
+ DocIdSetIterator clause2 = DocIdSetIterator.range(20_000, 50_000);
+ DocIdSetIterator clause3 = DocIdSetIterator.range(60_000, 60_001);
+ Scorer scorer1 = new ConstantScoreScorer(1f, ScoreMode.COMPLETE_NO_SCORES, clause1);
+ Scorer scorer2 = new ConstantScoreScorer(1f, ScoreMode.COMPLETE_NO_SCORES, clause2);
+ Scorer scorer3 = new ConstantScoreScorer(1f, ScoreMode.COMPLETE_NO_SCORES, clause3);
+ DocIdSetIterator iterator =
+ new DisjunctionDISIApproximation(
+ Arrays.asList(
+ new DisiWrapper(scorer1, false),
+ new DisiWrapper(scorer2, false),
+ new DisiWrapper(scorer3, false)),
+ 1);
+ assertEquals(10_000, iterator.nextDoc());
+ assertEquals(10_001, iterator.docIDRunEnd());
+ assertEquals(25_000, iterator.advance(25_000));
+ assertEquals(25_001, iterator.docIDRunEnd());
+ assertEquals(60_000, iterator.advance(50_000));
+ assertEquals(60_001, iterator.docIDRunEnd());
+ }
}