Apache Lucene open-source search software
[BlockJoin] Add ParentsChildrenBlockJoinQuery (#14728)
Jinny Wang1584c05b27ac
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txtindex b1843d1812a..0b0596dc281 100644--- a/lucene/CHANGES.txt+++ b/lucene/CHANGES.txt@@ -89,6 +89,9 @@ New Features* GITHUB#14404: Introducing DocValuesMultiRangeQuery.SortedNumericStabbingBuilder into sandbox.(Mikhail Khludnev)+* GITHUB#14565: Add ParentsChildrenBlockJoinQuery that supports parent and child filter in the same query+ along with limiting number of child documents to retrieve per parent. (Jinny Wang)+Improvements---------------------* GITHUB#14458: Add an IndexDeletion policy that retains the last N commits. (Owais Kazi)diff --git a/lucene/join/src/java/org/apache/lucene/search/join/ParentsChildrenBlockJoinQuery.java b/lucene/join/src/java/org/apache/lucene/search/join/ParentsChildrenBlockJoinQuery.javanew file mode 100644index 00000000000..0d14191bace--- /dev/null+++ b/lucene/join/src/java/org/apache/lucene/search/join/ParentsChildrenBlockJoinQuery.java@@ -0,0 +1,499 @@+/*+ * 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.join;++import static org.apache.lucene.search.join.ToChildBlockJoinQuery.INVALID_QUERY_MESSAGE;++import java.io.IOException;+import java.util.ArrayList;+import java.util.Arrays;+import java.util.Collection;+import java.util.HashSet;+import java.util.List;+import java.util.Locale;+import java.util.Set;+import java.util.function.BinaryOperator;+import org.apache.lucene.index.LeafReaderContext;+import org.apache.lucene.search.DocIdSetIterator;+import org.apache.lucene.search.Explanation;+import org.apache.lucene.search.IndexSearcher;+import org.apache.lucene.search.Matches;+import org.apache.lucene.search.MatchesUtils;+import org.apache.lucene.search.Query;+import org.apache.lucene.search.QueryVisitor;+import org.apache.lucene.search.Scorer;+import org.apache.lucene.search.ScorerSupplier;+import org.apache.lucene.search.Weight;+import org.apache.lucene.util.BitSet;++/**+ * A query that returns the matching child documents for matching parent documents indexed together+ * in the same block. The provided parentQuery determines the parent documents of the returned+ * children documents. The provided childQuery determines which matching children documents are+ * being returned. childLimitPerParent is the maximum number of child documents to match per parent+ * document.+ *+ * @lucene.experimental+ */+public class ParentsChildrenBlockJoinQuery extends Query {++ private final BitSetProducer parentFilter;+ private final Query parentQuery;+ private final Query childQuery;+ private final int childLimitPerParent;+ private final BinaryOperator<Float> scoreCombiner;++ /** The default maximum number of child documents to match per parent document. */+ public static final int DEFAULT_CHILD_LIMIT_PER_PARENT = Integer.MAX_VALUE;++ /**+ * Create a ParentsChildrenBlockJoinQuery.+ *+ * @param parentFilter Filter identifying the parent documents.+ * @param parentQuery Query that matches parent documents.+ * @param childQuery Query that matches child documents.+ * @param childLimitPerParent The maximum number of child documents to match per parent.+ */+ public ParentsChildrenBlockJoinQuery(+ BitSetProducer parentFilter, Query parentQuery, Query childQuery, int childLimitPerParent) {+ this(parentFilter, parentQuery, childQuery, childLimitPerParent, Float::sum);+ }++ /**+ * Create a ParentsChildrenBlockJoinQuery with a custom score combiner.+ *+ * @param parentFilter Filter identifying the parent documents.+ * @param parentQuery Query that matches parent documents.+ * @param childQuery Query that matches child documents.+ * @param childLimitPerParent The maximum number of child documents to match per parent.+ * @param scoreCombiner Function to combine parent and child scores.+ */+ public ParentsChildrenBlockJoinQuery(+ BitSetProducer parentFilter,+ Query parentQuery,+ Query childQuery,+ int childLimitPerParent,+ BinaryOperator<Float> scoreCombiner) {+ super();+ if (childLimitPerParent <= 0) {+ throw new IllegalArgumentException(+ "childLimitPerParent must be > 0, got " + childLimitPerParent);+ }+ this.parentFilter = parentFilter;+ this.parentQuery = parentQuery;+ this.childQuery = childQuery;+ this.childLimitPerParent = childLimitPerParent;+ this.scoreCombiner = scoreCombiner;+ }++ /**+ * Create a ParentsChildrenBlockJoinQuery with DEFAULT_CHILD_LIMIT_PER_PARENT.+ *+ * @param parentFilter Filter identifying the parent documents.+ * @param parentQuery Query that matches parent documents.+ * @param childQuery Query that matches child documents.+ */+ public ParentsChildrenBlockJoinQuery(+ BitSetProducer parentFilter, Query parentQuery, Query childQuery) {+ this(parentFilter, parentQuery, childQuery, DEFAULT_CHILD_LIMIT_PER_PARENT);+ }++ @Override+ public void visit(QueryVisitor visitor) {+ visitor.visitLeaf(this);+ }++ @Override+ public Weight createWeight(+ IndexSearcher searcher, org.apache.lucene.search.ScoreMode scoreMode, float boost)+ throws IOException {+ return new ParentsChildrenBlockJoinWeight(+ this,+ parentFilter,+ parentQuery.createWeight(searcher, scoreMode, boost),+ childQuery.createWeight(searcher, scoreMode, boost),+ childLimitPerParent,+ scoreMode.needsScores(),+ scoreCombiner);+ }++ /** Return the parent query. */+ public Query getParentQuery() {+ return parentQuery;+ }++ /** Return the child query. */+ public Query getChildQuery() {+ return childQuery;+ }++ static class ParentsChildrenBlockJoinWeight extends Weight {+ private final BitSetProducer parentFilter;+ private final Weight parentWeight;+ private final Weight childWeight;+ private final int childLimitPerParent;+ private final boolean doScores;+ private final BinaryOperator<Float> scoreCombiner;+ private final Set<LeafReaderContext> seenContexts = new HashSet<>();++ public ParentsChildrenBlockJoinWeight(+ Query query,+ BitSetProducer parentFilter,+ Weight parentWeight,+ Weight childWeight,+ int childLimitPerParent,+ boolean doScores,+ BinaryOperator<Float> scoreCombiner) {+ super(query);+ this.parentFilter = parentFilter;+ this.parentWeight = parentWeight;+ this.childWeight = childWeight;+ this.childLimitPerParent = childLimitPerParent;+ this.doScores = doScores;+ this.scoreCombiner = scoreCombiner;+ }++ @Override+ public Explanation explain(LeafReaderContext context, int doc) throws IOException {+ ParentsChildrenBlockJoinScorer scorer = (ParentsChildrenBlockJoinScorer) scorer(context);+ if (scorer != null && scorer.iterator().advance(doc) == doc) {+ int parentDoc = scorer.getParentDoc();+ int childDoc = scorer.docID();++ return Explanation.match(+ scorer.score(),+ String.format(+ Locale.ROOT,+ "Score based on parent document %d and child document %d ",+ parentDoc + context.docBase,+ childDoc + context.docBase),+ parentWeight.explain(context, parentDoc),+ childWeight.explain(context, childDoc));+ }+ return Explanation.noMatch("Not a match");+ }++ @Override+ public ScorerSupplier scorerSupplier(LeafReaderContext context) throws IOException {+ if (!seenContexts.add(context)) {+ throw new IllegalStateException(+ "ParentsChildrenBlockJoinQuery does not support intraSegment concurrency. Context "+ + context+ + " was already seen.");+ }++ final BitSet parentBits = parentFilter.getBitSet(context);+ if (parentBits == null) {+ return null;+ }+ final ScorerSupplier parentScorerSupplier = parentWeight.scorerSupplier(context);+ final ScorerSupplier childScorerSupplier = childWeight.scorerSupplier(context);++ if (parentScorerSupplier == null || childScorerSupplier == null) {+ return null;+ }++ return new ScorerSupplier() {+ private long cost = -1;++ @Override+ public Scorer get(long leadCost) throws IOException {+ final Scorer parentScorer = parentScorerSupplier.get(leadCost);+ final Scorer childScorer = childScorerSupplier.get(leadCost);+ return new ParentsChildrenBlockJoinScorer(+ parentBits, parentScorer, childScorer, childLimitPerParent, doScores, scoreCombiner);+ }++ @Override+ public long cost() {+ if (cost == -1) {+ // Calculate cost based on parent and child costs+ // The cost should reflect the number of documents that will be visited+ long parentCost = parentScorerSupplier.cost();+ long childCost = childScorerSupplier.cost();+ // The actual cost depends on how many children per parent we'll visit+ cost = Math.min(parentCost * childLimitPerParent, childCost);+ }+ return cost;+ }++ @Override+ public void setTopLevelScoringClause() {+ // Propagate to both parent and child scorers+ parentScorerSupplier.setTopLevelScoringClause();+ childScorerSupplier.setTopLevelScoringClause();+ }+ };+ }++ @Override+ public boolean isCacheable(LeafReaderContext ctx) {+ return parentWeight.isCacheable(ctx) && childWeight.isCacheable(ctx);+ }++ @Override+ public Matches matches(LeafReaderContext context, int doc) throws IOException {+ Matches parentMatch = parentWeight.matches(context, doc);+ Matches childMatch = childWeight.matches(context, doc);++ if (parentMatch == null && childMatch == null) {+ // Neither matches+ return null;+ }+ // Combine non-null matches+ List<Matches> subMatches = new ArrayList<>();+ if (parentMatch != null) subMatches.add(parentMatch);+ if (childMatch != null) subMatches.add(childMatch);+ return MatchesUtils.fromSubMatches(subMatches);+ }+ }++ static class ParentsChildrenBlockJoinScorer extends Scorer {+ private final BitSet parentBits;+ private final Scorer parentScorer;+ private final DocIdSetIterator parentIt;+ private final Scorer childScorer;+ private final DocIdSetIterator childIt;+ private final int childLimitPerParent;+ private final boolean doScores;+ private final BinaryOperator<Float> scoreCombiner;+ private float parentScore;+ private float childScore;++ private int parentDoc = 0;+ private int childDoc = -1;+ private int childDocCount = 0;++ public ParentsChildrenBlockJoinScorer(+ BitSet parentBits,+ Scorer parentScorer,+ Scorer childScorer,+ int childLimitPerParent,+ boolean doScores,+ BinaryOperator<Float> scoreCombiner) {+ this.parentBits = parentBits;+ this.parentScorer = parentScorer;+ this.parentIt = parentScorer.iterator();+ this.childScorer = childScorer;+ this.childIt = childScorer.iterator();+ this.childLimitPerParent = childLimitPerParent;+ this.doScores = doScores;+ this.scoreCombiner = scoreCombiner;+ }++ @Override+ public Collection<ChildScorable> getChildren() {+ return Arrays.asList(+ new ChildScorable(parentScorer, "BLOCK_JOIN"),+ new ChildScorable(childScorer, "BLOCK_JOIN"));+ }++ @Override+ public DocIdSetIterator iterator() {+ return new DocIdSetIterator() {+ @Override+ public int docID() {+ return childDoc;+ }++ @Override+ public int nextDoc() throws IOException {+ if (childDocCount < childLimitPerParent) {+ childDoc = childIt.nextDoc();+ }++ // Need to move to the next parent if we have exhausted the current parent or child is out+ // of+ // the current parent block+ if (childDocCount >= childLimitPerParent || childDoc >= parentDoc) {+ childDocCount = 0;+ parentDoc = parentIt.nextDoc();+ if (parentDoc == 0) {+ // first parent doc has no children+ parentDoc = parentIt.nextDoc();+ }+ validateParentDoc();+ }++ // Adjust the parentIt and childIt so that they are in the same block+ alignParentAndChildIterator();++ if (exhausted()) {+ childDoc = parentDoc = NO_MORE_DOCS;+ return childDoc;+ }++ if (doScores) {+ childScore = childScorer.score();+ parentScore = parentScorer.score();+ }++ childDocCount++;+ return childDoc;+ }++ @Override+ public int advance(int target) throws IOException {+ if (target <= childDoc) {+ return childDoc;+ }++ childDoc = childIt.advance(target);+ if (childDocCount >= childLimitPerParent || childDoc >= parentDoc) {+ // need to move to the next parent block+ childDocCount = 0;+ if (childDoc <= parentDoc) {+ parentDoc = parentIt.nextDoc();+ } else {+ parentDoc = parentIt.advance(childDoc);+ }+ validateParentDoc();++ // Adjust the parentIt and childIt so that they are in the same block+ alignParentAndChildIterator();+ }++ if (exhausted()) {+ childDoc = parentDoc = NO_MORE_DOCS;+ return childDoc;+ }++ if (doScores) {+ childScore = childScorer.score();+ parentScore = parentScorer.score();+ }++ childDocCount++;+ return childDoc;+ }++ private void alignParentAndChildIterator() throws IOException {+ while (!exhausted()) {+ int firstChild = parentBits.prevSetBit(parentDoc - 1) + 1;+ if (childDoc >= firstChild && childDoc < parentDoc) {+ // order is correct , childDoc is within a valid parent block+ break;+ } else if (childDoc < firstChild) {+ // childDoc is before the current parent block, advance the child iterator+ childDoc = childIt.advance(firstChild);+ } else {+ // childDoc is after the current parent block, advance the parent iterator+ // when childDoc equals to parentDoc we skip to the next parent as well+ if (childDoc == parentDoc) {+ parentDoc = parentIt.nextDoc();+ } else {+ parentDoc = parentIt.advance(childDoc);+ }+ validateParentDoc();+ }+ }+ }++ @Override+ public long cost() {+ if (childLimitPerParent == DEFAULT_CHILD_LIMIT_PER_PARENT) {+ // When there's no limit, we'll visit all child documents for each parent+ return childIt.cost();+ } else {+ // When there's a limit, we'll visit at most childLimitPerParent child documents+ // for each parent that matches the parent query+ return Math.min(childIt.cost(), parentIt.cost() * childLimitPerParent);+ }+ }++ private boolean exhausted() {+ return childIt.docID() == NO_MORE_DOCS || parentIt.docID() == NO_MORE_DOCS;+ }+ };+ }++ /** Detect mis-use, where provided parent query in fact sometimes returns child documents. */+ private void validateParentDoc() {+ if (parentDoc != DocIdSetIterator.NO_MORE_DOCS && !parentBits.get(parentDoc)) {+ throw new IllegalStateException(INVALID_QUERY_MESSAGE + parentDoc);+ }+ }++ @Override+ public int docID() {+ return childDoc;+ }++ @Override+ public float score() throws IOException {+ if (doScores) {+ return scoreCombiner.apply(parentScore, childScore);+ }+ return 1.0f;+ }++ @Override+ public float getMaxScore(int upTo) throws IOException {+ return Float.POSITIVE_INFINITY;+ }++ int getParentDoc() {+ return parentDoc;+ }+ }++ @Override+ public Query rewrite(IndexSearcher indexSearcher) throws IOException {+ final Query parentRewrite = parentQuery.rewrite(indexSearcher);+ final Query childRewrite = childQuery.rewrite(indexSearcher);+ if (parentRewrite != parentQuery || childRewrite != childQuery) {+ return new ParentsChildrenBlockJoinQuery(+ parentFilter, parentRewrite, childRewrite, childLimitPerParent);+ } else {+ return super.rewrite(indexSearcher);+ }+ }++ @Override+ public String toString(String field) {+ return "ParentsChildrenBlockJoinQuery(parentQuery="+ + parentQuery+ + ", childQuery="+ + childQuery+ + ")";+ }++ @Override+ public boolean equals(Object other) {+ return sameClassAs(other) && equalsTo(getClass().cast(other));+ }++ private boolean equalsTo(ParentsChildrenBlockJoinQuery other) {+ return parentFilter.equals(other.parentFilter)+ && parentQuery.equals(other.parentQuery)+ && childQuery.equals(other.childQuery)+ && childLimitPerParent == other.childLimitPerParent+ && scoreCombiner.equals(other.scoreCombiner);+ }++ @Override+ public int hashCode() {+ final int prime = 31;+ int hash = classHash();+ hash = prime * hash + parentFilter.hashCode();+ hash = prime * hash + parentQuery.hashCode();+ hash = prime * hash + childQuery.hashCode();+ hash = prime * hash + childLimitPerParent;+ hash = prime * hash + scoreCombiner.hashCode();+ return hash;+ }+}diff --git a/lucene/join/src/test/org/apache/lucene/search/join/TestParentsChildrenBlockJoinQuery.java b/lucene/join/src/test/org/apache/lucene/search/join/TestParentsChildrenBlockJoinQuery.javanew file mode 100644index 00000000000..7890fc0229b--- /dev/null+++ b/lucene/join/src/test/org/apache/lucene/search/join/TestParentsChildrenBlockJoinQuery.java@@ -0,0 +1,505 @@+/*+ * 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.join;++import java.util.ArrayList;+import java.util.Arrays;+import java.util.HashSet;+import java.util.List;+import java.util.Set;+import java.util.stream.Collectors;+import org.apache.lucene.document.*;+import org.apache.lucene.index.IndexReader;+import org.apache.lucene.index.Term;+import org.apache.lucene.search.*;+import org.apache.lucene.store.Directory;+import org.apache.lucene.tests.index.RandomIndexWriter;+import org.apache.lucene.tests.util.LuceneTestCase;+import org.junit.Test;++public class TestParentsChildrenBlockJoinQuery extends LuceneTestCase {++ @Test+ public void testEmptyIndex() throws Exception {+ // No documents to index, just test the query execution+ test(new TestDoc[0][0], new int[0], 10);+ }++ @Test+ public void testOnlyParentDocs() throws Exception {+ // Only parent documents, no children+ TestDoc[][] blocks = {+ {new TestDoc("parent", true, 0)},+ {new TestDoc("parent", true, 1)},+ {new TestDoc("parent", true, 2)}+ };+ int[] expectedDocIds = new int[0];+ test(blocks, expectedDocIds, 10);+ }++ @Test+ public void testFirstParentWithoutChild() throws Exception {+ // First parent has no children, but the second parent has two children+ TestDoc[][] blocks = {+ {new TestDoc("parent", true, 0)},+ {new TestDoc("child", true, 1), new TestDoc("child", true, 2), new TestDoc("parent", true, 3)}+ };+ int[] expectedDocIds = new int[] {1, 2};+ test(blocks, expectedDocIds, 10);+ }++ @Test+ public void testWithRandomizedIndex() throws Exception {++ for (int i = 0; i < 10; i++) {+ // Run multiple iterations to ensure randomness+ if (VERBOSE) {+ System.out.println("Running randomized test iteration: " + i);+ }+ runRandomizedTest();+ }+ }++ private void runRandomizedTest() throws Exception {+ // Random child limit between 1 and 10+ int childLimitPerParent = 1 + random().nextInt(10);++ // Create at least 100 parents+ final int numParents = atLeast(100);+ int docId = 0;++ // Array to store test documents: each parent and its children+ TestDoc[][] testDocs = new TestDoc[numParents][];++ // List to store expected matching document IDs+ List<Integer> expectedMatches = new ArrayList<>();+ for (int parentIdx = 0; parentIdx < numParents; parentIdx++) {+ // Randomly decide if parent matches+ boolean matchingParent = random().nextBoolean();++ // Random number of children (0-19)+ int numChildren = random().nextInt(20);+ testDocs[parentIdx] = new TestDoc[numChildren + 1]; // +1 for parent++ int matchingChildrenCount = 0;++ // Create children+ for (int childIdx = 0; childIdx < numChildren; childIdx++) {+ // Randomly decide if child matches+ boolean matchingChild = random().nextBoolean();+ testDocs[parentIdx][childIdx] = new TestDoc("child", matchingChild, docId);++ // If both parent and child match, and we haven't exceeded child limit+ if (matchingChild && matchingParent) {+ matchingChildrenCount++;+ if (matchingChildrenCount <= childLimitPerParent) {+ expectedMatches.add(docId);+ }+ }+ docId++;+ }++ // Add parent document+ testDocs[parentIdx][numChildren] = new TestDoc("parent", matchingParent, docId);+ docId++;+ }++ // Convert expected matches to array and run test+ int[] expectedMatchArray = expectedMatches.stream().mapToInt(Integer::intValue).toArray();+ test(testDocs, expectedMatchArray, childLimitPerParent);+ }++ @Test+ public void testAdvance() throws Exception {+ // Create test blocks with specific structure to test advance()+ TestDoc[][] blocks = new TestDoc[3][];++ // Block 0: 2 children + 1 parent (parent matches)+ blocks[0] = new TestDoc[3];+ blocks[0][0] = new TestDoc("child", true, 0); // docId=0+ blocks[0][1] = new TestDoc("child", true, 1); // docId=1+ blocks[0][2] = new TestDoc("parent", true, 2); // docId=2++ // Block 1: 3 children + 1 parent (parent matches)+ blocks[1] = new TestDoc[4];+ blocks[1][0] = new TestDoc("child", true, 3); // docId=3+ blocks[1][1] = new TestDoc("child", true, 4); // docId=4+ blocks[1][2] = new TestDoc("child", true, 5); // docId=5+ blocks[1][3] = new TestDoc("parent", true, 6); // docId=6++ // Block 2: 2 children + 1 parent (parent matches)+ blocks[2] = new TestDoc[3];+ blocks[2][0] = new TestDoc("child", true, 7); // docId=7+ blocks[2][1] = new TestDoc("child", true, 8); // docId=8+ blocks[2][2] = new TestDoc("parent", true, 9); // docId=9++ final Directory dir = newDirectory();+ final RandomIndexWriter writer =+ new RandomIndexWriter(+ random(), dir, newIndexWriterConfig().setMergePolicy(newMergePolicy(random(), false)));++ // Add documents+ List<Document> docs = new ArrayList<>();+ for (TestDoc[] block : blocks) {+ for (TestDoc doc : block) {+ docs.add(doc.toDocument());+ }+ writer.addDocuments(docs);+ docs.clear();+ }+ writer.commit();+ writer.forceMerge(1);++ IndexReader reader = writer.getReader();+ writer.close();++ // Do not use Concurrency.INTRA_SEGMENT as that would break childLimitPerParent counting+ IndexSearcher searcher = newSearcher(reader, false, false, Concurrency.NONE);+ BitSetProducer parentFilter =+ new QueryBitSetProducer(new TermQuery(new Term("type", "parent")));+ CheckJoinIndex.check(reader, parentFilter);+ Query parentQuery =+ new BooleanQuery.Builder()+ .add(new TermQuery(new Term("value", "match")), BooleanClause.Occur.MUST)+ .add(new TermQuery(new Term("type", "parent")), BooleanClause.Occur.MUST)+ .build();+ Query childQuery =+ new BooleanQuery.Builder()+ .add(new TermQuery(new Term("value", "match")), BooleanClause.Occur.MUST)+ .add(new TermQuery(new Term("type", "child")), BooleanClause.Occur.MUST)+ .build();++ ParentsChildrenBlockJoinQuery query =+ new ParentsChildrenBlockJoinQuery(parentFilter, parentQuery, childQuery, 2);++ // Test advance() functionality+ Weight weight =+ searcher.createWeight(+ searcher.rewrite(query), org.apache.lucene.search.ScoreMode.COMPLETE, 1);+ Scorer scorer = weight.scorer(reader.leaves().get(0));+ assert scorer != null;+ DocIdSetIterator it = scorer.iterator();++ // Test advance to doc 3 (should skip to first child of second parent)+ assertEquals(3, it.advance(3));++ // Test advance to doc 7 (should skip to first child of third parent)+ assertEquals(7, it.advance(7));++ // Test advance beyond last document+ assertEquals(DocIdSetIterator.NO_MORE_DOCS, it.advance(10));++ reader.close();+ dir.close();+ }++ private void test(TestDoc[][] blocks, int[] expectedDocIds, int childLimitPerParent)+ throws Exception {+ final Directory dir = newDirectory();+ final RandomIndexWriter writer =+ new RandomIndexWriter(+ random(), dir, newIndexWriterConfig().setMergePolicy(newMergePolicy(random(), false)));++ // Add documents based on test case+ final List<Document> docs = new ArrayList<>();+ for (TestDoc[] block : blocks) {+ for (TestDoc doc : block) {+ Document document = doc.toDocument();+ docs.add(document);+ }+ writer.addDocuments(docs);+ docs.clear();+ }+ writer.commit();+ writer.forceMerge(1);++ IndexReader reader = writer.getReader();+ writer.close();++ // Do not use Concurrency.INTRA_SEGMENT as that would break childLimitPerParent counting+ IndexSearcher searcher = newSearcher(reader, false, false, Concurrency.NONE);+ BitSetProducer parentFilter =+ new QueryBitSetProducer(new TermQuery(new Term("type", "parent")));+ CheckJoinIndex.check(reader, parentFilter);+ Query parentQuery =+ new BooleanQuery.Builder()+ .add(new TermQuery(new Term("value", "match")), BooleanClause.Occur.MUST)+ .add(new TermQuery(new Term("type", "parent")), BooleanClause.Occur.MUST)+ .build();+ Query childQuery =+ new BooleanQuery.Builder()+ .add(new TermQuery(new Term("value", "match")), BooleanClause.Occur.MUST)+ .add(new TermQuery(new Term("type", "child")), BooleanClause.Occur.MUST)+ .build();++ ParentsChildrenBlockJoinQuery query =+ new ParentsChildrenBlockJoinQuery(+ parentFilter, parentQuery, childQuery, childLimitPerParent);++ TopDocs results = searcher.search(query, (expectedDocIds.length + 1) * 2);++ try {+ assertEquals(expectedDocIds.length, results.totalHits.value());+ Set<Integer> expectedDocIdSet =+ Arrays.stream(expectedDocIds).boxed().collect(Collectors.toSet());++ // Verify the matching documents+ for (ScoreDoc scoreDoc : results.scoreDocs) {+ Document doc = reader.storedFields().document(scoreDoc.doc);+ String type = doc.getField("type").stringValue();+ Integer id = doc.getField("ID").numericValue().intValue();+ assertEquals("child", type); // All results should be children+ assertTrue(expectedDocIdSet.contains(id));+ }+ } catch (AssertionError e) {+ if (VERBOSE) {+ System.out.println("Test failed. Document structure:");+ System.out.println(visualizeTestDocs(blocks));+ System.out.println("Child limit per parent: " + childLimitPerParent);+ System.out.println("Expected docIds: " + Arrays.toString(expectedDocIds));+ System.out.println("Actual hits: " + results.totalHits.value());++ // Get actual docIds+ int[] actualDocIds = new int[results.scoreDocs.length];+ int i = 0;+ for (ScoreDoc scoreDoc : results.scoreDocs) {+ Document doc = reader.storedFields().document(scoreDoc.doc);+ int id = doc.getField("ID").numericValue().intValue();+ actualDocIds[i++] = id;+ }+ System.out.println("Actual docIds: " + Arrays.toString(actualDocIds));++ // Compare expected vs actual+ Set<Integer> expected = Arrays.stream(expectedDocIds).boxed().collect(Collectors.toSet());+ Set<Integer> actual = Arrays.stream(actualDocIds).boxed().collect(Collectors.toSet());++ Set<Integer> missing = new HashSet<>(expected);+ missing.removeAll(actual);+ if (!missing.isEmpty()) {+ System.out.println("Missing expected docIds: " + missing);+ }++ Set<Integer> unexpected = new HashSet<>(actual);+ unexpected.removeAll(expected);+ if (!unexpected.isEmpty()) {+ System.out.println("Unexpected docIds: " + unexpected);+ }+ }+ throw e;+ }++ reader.close();+ dir.close();+ }++ @Test+ public void testInvalidChildLimit() {+ BitSetProducer parentFilter =+ new QueryBitSetProducer(new TermQuery(new Term("type", "parent")));+ Query parentQuery = new TermQuery(new Term("value", "parent"));+ Query childQuery = new TermQuery(new Term("type", "child"));++ IllegalArgumentException e =+ expectThrows(+ IllegalArgumentException.class,+ () -> new ParentsChildrenBlockJoinQuery(parentFilter, parentQuery, childQuery, 0));+ assertTrue(e.getMessage().contains("childLimitPerParent must be > 0"));+ }++ @Test+ public void testExplain() throws Exception {+ // Create test blocks with specific structure to test explain()+ TestDoc[][] blocks = new TestDoc[2][];++ // Block 0: 2 children + 1 parent (parent matches)+ blocks[0] = new TestDoc[3];+ blocks[0][0] = new TestDoc("child", true, 0); // docId=0+ blocks[0][1] = new TestDoc("child", true, 1); // docId=1+ blocks[0][2] = new TestDoc("parent", true, 2); // docId=2++ // Block 1: 2 children + 1 parent (parent matches)+ blocks[1] = new TestDoc[3];+ blocks[1][0] = new TestDoc("child", true, 3); // docId=3+ blocks[1][1] = new TestDoc("child", false, 4); // docId=4+ blocks[1][2] = new TestDoc("parent", true, 5); // docId=5++ Directory dir = newDirectory();+ final RandomIndexWriter writer =+ new RandomIndexWriter(+ random(), dir, newIndexWriterConfig().setMergePolicy(newMergePolicy(random(), false)));++ // Add documents+ List<Document> docs = new ArrayList<>();+ for (TestDoc[] block : blocks) {+ for (TestDoc doc : block) {+ docs.add(doc.toDocument());+ }+ writer.addDocuments(docs);+ docs.clear();+ }+ writer.commit();+ writer.forceMerge(1);++ IndexReader reader = writer.getReader();+ writer.close();++ // Do not use Concurrency.INTRA_SEGMENT as that would break childLimitPerParent counting+ IndexSearcher searcher = newSearcher(reader, false, false, Concurrency.NONE);+ BitSetProducer parentFilter =+ new QueryBitSetProducer(new TermQuery(new Term("type", "parent")));+ CheckJoinIndex.check(reader, parentFilter);+ Query parentQuery =+ new BooleanQuery.Builder()+ .add(new TermQuery(new Term("value", "match")), BooleanClause.Occur.MUST)+ .add(new TermQuery(new Term("type", "parent")), BooleanClause.Occur.MUST)+ .build();+ Query childQuery =+ new BooleanQuery.Builder()+ .add(new TermQuery(new Term("value", "match")), BooleanClause.Occur.MUST)+ .add(new TermQuery(new Term("type", "child")), BooleanClause.Occur.MUST)+ .build();++ ParentsChildrenBlockJoinQuery query =+ new ParentsChildrenBlockJoinQuery(parentFilter, parentQuery, childQuery, 2);++ // Test explain for a matching child document+ Explanation explanation = searcher.explain(query, 0);+ if (VERBOSE) {+ System.out.println("Explanation for matching child document:");+ System.out.println(explanation);+ }+ assertTrue(explanation.isMatch());++ // Test explain for a non-matching child document+ // Add a non-matching child++ explanation = searcher.explain(query, 4);+ assertFalse(explanation.isMatch());++ reader.close();+ dir.close();+ }++ @Test+ public void testIntraSegmentConcurrencyNotSupported() throws Exception {+ // Create test blocks with specific structure - using a larger number of documents+ final int numParents = atLeast(1000); // Create at least 1000 parents to ensure large segment+ TestDoc[][] blocks = new TestDoc[numParents][];++ int docId = 0;+ for (int parentIdx = 0; parentIdx < numParents; parentIdx++) {+ // Each parent has 5 children+ blocks[parentIdx] = new TestDoc[6]; // 5 children + 1 parent++ // Add children+ for (int childIdx = 0; childIdx < 5; childIdx++) {+ blocks[parentIdx][childIdx] = new TestDoc("child", true, docId++);+ }+ // Add parent+ blocks[parentIdx][5] = new TestDoc("parent", true, docId++);+ }++ Directory dir = newDirectory();+ final RandomIndexWriter writer =+ new RandomIndexWriter(+ random(), dir, newIndexWriterConfig().setMergePolicy(newMergePolicy(random(), false)));++ // Add documents+ List<Document> docs = new ArrayList<>();+ for (TestDoc[] block : blocks) {+ for (TestDoc doc : block) {+ docs.add(doc.toDocument());+ }+ writer.addDocuments(docs);+ docs.clear();+ }+ writer.commit();+ writer.forceMerge(1); // Force merge to ensure we have one large segment++ IndexReader reader = writer.getReader();+ writer.close();++ BitSetProducer parentFilter =+ new QueryBitSetProducer(new TermQuery(new Term("type", "parent")));+ CheckJoinIndex.check(reader, parentFilter);+ Query parentQuery =+ new BooleanQuery.Builder()+ .add(new TermQuery(new Term("value", "match")), BooleanClause.Occur.MUST)+ .add(new TermQuery(new Term("type", "parent")), BooleanClause.Occur.MUST)+ .build();+ Query childQuery =+ new BooleanQuery.Builder()+ .add(new TermQuery(new Term("value", "match")), BooleanClause.Occur.MUST)+ .add(new TermQuery(new Term("type", "child")), BooleanClause.Occur.MUST)+ .build();++ ParentsChildrenBlockJoinQuery query =+ new ParentsChildrenBlockJoinQuery(parentFilter, parentQuery, childQuery, 2);++ for (int i = 0; i < 10; i++) {+ // Verify that searching with IntraSegment concurrency throws the expected exception+ // Note that there are still randomness on whether to slice a single segment, thus we are+ // running the test 10 times+ // And only assert for exception if there are multiple slices+ IndexSearcher searcher = newSearcher(reader, false, false, Concurrency.INTRA_SEGMENT);+ IndexSearcher.LeafSlice[] leafSlices = searcher.getSlices();+ if (leafSlices.length > 1) {+ IllegalStateException e =+ expectThrows(IllegalStateException.class, () -> searcher.search(query, 10));+ assertTrue(+ e.getMessage()+ .contains(+ "ParentsChildrenBlockJoinQuery does not support intraSegment concurrency."));+ }+ }++ reader.close();+ dir.close();+ }++ private record TestDoc(String type, boolean isMatch, int docID) {+ Document toDocument() {+ Document doc = new Document();+ doc.add(new StringField("type", type, Field.Store.YES));+ doc.add(new StoredField("ID", docID));+ if (isMatch) {+ doc.add(new StringField("value", "match", Field.Store.YES));+ } else {+ doc.add(new StringField("value", "nomatch", Field.Store.YES));+ }+ return doc;+ }++ @Override+ public String toString() {+ return type + "(" + (isMatch ? "match" : "nomatch") + ")";+ }+ }++ private String visualizeTestDocs(TestDoc[][] blocks) {+ StringBuilder sb = new StringBuilder();+ sb.append("Test Documents Structure:\n");+ int docId = 0;+ for (int i = 0; i < blocks.length; i++) {+ sb.append("Block ").append(i).append(":\n");+ for (TestDoc doc : blocks[i]) {+ sb.append(" docId=").append(docId++).append(": ").append(doc).append("\n");+ }+ }+ return sb.toString();+ }+}