Apache Lucene open-source search software
Introduce BlockGroupingCollectorManager (#15936)
gaobinlongd27d080d1013
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txtindex 552f8022f85..ffc420a7ad8 100644--- a/lucene/CHANGES.txt+++ b/lucene/CHANGES.txt@@ -379,6 +379,8 @@ Improvements* GITHUB#15603, GITHUB#15995: Introduce TopGroupsCollectorManager to parallelize search when using TopGroupsCollector. (Binlong Gao)+* GITHUB#15936: Introduce BlockGroupingCollectorManager to parallelize search when using BlockGroupingCollector. (Binlong Gao)+* GITHUB#15565: Introduce AllGroupHeadsCollectorManager to parallelize search when using AllGroupHeadsCollector. (Binlong Gao)* GITHUB#15989: DocValuesRangeIterator always tries to use skipper-based block iterationdiff --git a/lucene/grouping/src/java/org/apache/lucene/search/grouping/BlockGroupingCollector.java b/lucene/grouping/src/java/org/apache/lucene/search/grouping/BlockGroupingCollector.javaindex 6e87825080e..428a8c8a9b5 100644--- a/lucene/grouping/src/java/org/apache/lucene/search/grouping/BlockGroupingCollector.java+++ b/lucene/grouping/src/java/org/apache/lucene/search/grouping/BlockGroupingCollector.java@@ -60,11 +60,6 @@ import org.apache.lucene.util.PriorityQueue;** @lucene.experimental*/--// TODO: TopGroups.merge() won't work with TopGroups returned by this collector, because-// each block will be on a different shard. Add a specialized merge() static method-// to this collector?-public class BlockGroupingCollector extends SimpleCollector {private int[] pendingSubDocs;diff --git a/lucene/grouping/src/java/org/apache/lucene/search/grouping/BlockGroupingCollectorManager.java b/lucene/grouping/src/java/org/apache/lucene/search/grouping/BlockGroupingCollectorManager.javanew file mode 100644index 00000000000..3e7a9a6d728--- /dev/null+++ b/lucene/grouping/src/java/org/apache/lucene/search/grouping/BlockGroupingCollectorManager.java@@ -0,0 +1,161 @@+/*+ * 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.grouping;++import java.io.IOException;+import java.util.ArrayList;+import java.util.Collection;+import java.util.List;+import org.apache.lucene.search.CollectorManager;+import org.apache.lucene.search.Sort;+import org.apache.lucene.search.Weight;++/**+ * A {@link CollectorManager} for {@link BlockGroupingCollector} that merges results from multiple+ * collectors into a single {@link TopGroups}. This is intended for use with concurrent search,+ * where each slice is searched by a separate {@link BlockGroupingCollector}.+ *+ * <p>Documents must be indexed as blocks using {@link+ * org.apache.lucene.index.IndexWriter#addDocuments IndexWriter.addDocuments()} or {@link+ * org.apache.lucene.index.IndexWriter#updateDocuments IndexWriter.updateDocuments()}.+ *+ * <p><b>NOTE</b>: All documents in a group block must be processed by the same {@link+ * BlockGroupingCollector} instance. This means that the {@link+ * org.apache.lucene.search.IndexSearcher}'s slices must not split a segment in a way that places+ * documents from the same block into different slices. The default {@link+ * org.apache.lucene.search.IndexSearcher#slices} implementation (inter-segment only) satisfies this+ * constraint. If intra-segment concurrency is desired, the caller must override {@link+ * org.apache.lucene.search.IndexSearcher#slices} to ensure each doc block falls entirely within one+ * slice.+ *+ * <p>See {@link BlockGroupingCollector} for more details.+ *+ * <p>Example usage:+ *+ * <pre class="prettyprint">+ * IndexSearcher searcher = ...; // your IndexSearcher+ * Query lastDocPerGroupQuery = new TermQuery(new Term("groupEnd", "true"));+ * Weight lastDocPerGroup = searcher.createWeight(+ * searcher.rewrite(lastDocPerGroupQuery), ScoreMode.COMPLETE_NO_SCORES, 1);+ *+ * BlockGroupingCollectorManager<BytesRef> manager = new BlockGroupingCollectorManager<>(+ * Sort.RELEVANCE, // groupSort+ * 0, // groupOffset+ * 10, // topNGroups+ * true, // needsScores+ * lastDocPerGroup,+ * Sort.RELEVANCE, // withinGroupSort+ * 0, // withinGroupOffset+ * 5); // maxDocsPerGroup+ *+ * TopGroups<BytesRef> result = searcher.search(query, manager);+ * </pre>+ *+ * @lucene.experimental+ */+public class BlockGroupingCollectorManager<T>+ implements CollectorManager<BlockGroupingCollector, TopGroups<T>> {++ private final Sort groupSort;+ private final int groupOffset;+ private final int topNGroups;+ private final boolean needsScores;+ private final Weight lastDocPerGroup;++ private final Sort withinGroupSort;+ private final int withinGroupOffset;+ private final int maxDocsPerGroup;++ /**+ * Creates a new BlockGroupingCollectorManager.+ *+ * @param groupSort the sort used to rank groups+ * @param groupOffset the offset into the groups to start returning from+ * @param topNGroups the number of top groups to collect+ * @param needsScores whether scores are needed (must be true if groupSort or withinGroupSort uses+ * scores)+ * @param lastDocPerGroup a {@link Weight} that matches the last document in each group block+ * @param withinGroupSort the sort used to rank documents within each group+ * @param withinGroupOffset the offset into each group's documents to start returning from+ * @param maxDocsPerGroup the maximum number of documents to return per group+ */+ public BlockGroupingCollectorManager(+ Sort groupSort,+ int groupOffset,+ int topNGroups,+ boolean needsScores,+ Weight lastDocPerGroup,+ Sort withinGroupSort,+ int withinGroupOffset,+ int maxDocsPerGroup) {+ if (groupSort == null) {+ throw new IllegalArgumentException("groupSort must not be null");+ }+ if (withinGroupSort == null) {+ throw new IllegalArgumentException("withinGroupSort must not be null");+ }++ if (groupOffset < 0) {+ throw new IllegalArgumentException("groupOffset must be >= 0 (got " + groupOffset + ")");+ }++ if (topNGroups < 1) {+ throw new IllegalArgumentException("topNGroups must be >= 1 (got " + topNGroups + ")");+ }++ if (withinGroupOffset < 0) {+ throw new IllegalArgumentException(+ "withinGroupOffset must be >= 0 (got " + withinGroupOffset + ")");+ }++ if (maxDocsPerGroup < 1) {+ throw new IllegalArgumentException(+ "maxDocsPerGroup must be >= 1 (got " + maxDocsPerGroup + ")");+ }++ this.groupSort = groupSort;+ this.groupOffset = groupOffset;+ this.topNGroups = topNGroups;+ this.needsScores = needsScores;+ this.lastDocPerGroup = lastDocPerGroup;+ this.withinGroupSort = withinGroupSort;+ this.withinGroupOffset = withinGroupOffset;+ this.maxDocsPerGroup = maxDocsPerGroup;+ }++ @Override+ public BlockGroupingCollector newCollector() throws IOException {+ return new BlockGroupingCollector(+ groupSort, groupOffset + topNGroups, needsScores, lastDocPerGroup);+ }++ @SuppressWarnings("unchecked")+ @Override+ public TopGroups<T> reduce(Collection<BlockGroupingCollector> collectors) throws IOException {+ List<TopGroups<T>> shardGroupsList = new ArrayList<>();+ for (BlockGroupingCollector collector : collectors) {+ TopGroups<?> topGroups =+ collector.getTopGroups(withinGroupSort, 0, withinGroupOffset, maxDocsPerGroup);+ if (topGroups != null && topGroups.groups.length > 0) {+ shardGroupsList.add((TopGroups<T>) topGroups);+ }+ }++ return TopGroups.mergeBlockGroups(+ shardGroupsList, groupSort, groupOffset, topNGroups, withinGroupSort);+ }+}diff --git a/lucene/grouping/src/java/org/apache/lucene/search/grouping/GroupingSearch.java b/lucene/grouping/src/java/org/apache/lucene/search/grouping/GroupingSearch.javaindex 91bcbf56da8..630ffde1404 100644--- a/lucene/grouping/src/java/org/apache/lucene/search/grouping/GroupingSearch.java+++ b/lucene/grouping/src/java/org/apache/lucene/search/grouping/GroupingSearch.java@@ -126,7 +126,7 @@ public class GroupingSearch {if (grouper != null) {return groupByFieldOrFunction(searcher, query, groupOffset, groupLimit);} else if (groupEndDocs != null) {- return (TopGroups<T>) groupByDocBlock(searcher, query, groupOffset, groupLimit);+ return groupByDocBlock(searcher, query, groupOffset, groupLimit);} else {throw new IllegalStateException("Either groupField, groupFunction or groupEndDocs must be set."); // This can't happen...@@ -190,21 +190,23 @@ public class GroupingSearch {}}- protected TopGroups<?> groupByDocBlock(+ protected <T> TopGroups<T> groupByDocBlock(IndexSearcher searcher, Query query, int groupOffset, int groupLimit) throws IOException {- int topN = groupOffset + groupLimit;final Query endDocsQuery = searcher.rewrite(this.groupEndDocs);final Weight groupEndDocs =searcher.createWeight(endDocsQuery, ScoreMode.COMPLETE_NO_SCORES, 1);- BlockGroupingCollector c =- new BlockGroupingCollector(+ BlockGroupingCollectorManager<T> bcm =+ new BlockGroupingCollectorManager<>(groupSort,- topN,+ groupOffset,+ groupLimit,groupSort.needsScores() || sortWithinGroup.needsScores(),- groupEndDocs);- searcher.search(query, c);- int topNInsideGroup = groupDocsOffset + groupDocsLimit;- return c.getTopGroups(sortWithinGroup, groupOffset, groupDocsOffset, topNInsideGroup);+ groupEndDocs,+ sortWithinGroup,+ groupDocsOffset,+ groupDocsOffset + groupDocsLimit);++ return searcher.search(query, bcm);}/**diff --git a/lucene/grouping/src/java/org/apache/lucene/search/grouping/TopGroups.java b/lucene/grouping/src/java/org/apache/lucene/search/grouping/TopGroups.javaindex b19453c1a43..860a412d0bd 100644--- a/lucene/grouping/src/java/org/apache/lucene/search/grouping/TopGroups.java+++ b/lucene/grouping/src/java/org/apache/lucene/search/grouping/TopGroups.java@@ -16,7 +16,13 @@*/package org.apache.lucene.search.grouping;+import java.util.ArrayList;+import java.util.Comparator;import java.util.List;+import java.util.NavigableSet;+import java.util.TreeSet;+import org.apache.lucene.search.FieldComparator;+import org.apache.lucene.search.Pruning;import org.apache.lucene.search.ScoreDoc;import org.apache.lucene.search.Sort;import org.apache.lucene.search.SortField;@@ -290,4 +296,151 @@ public class TopGroups<T> {totalMaxScore);}}++ private record MergedBlockGroup(Object[] topValues, int shardIndex, int groupIndex) {}++ private static class GroupComparator implements Comparator<MergedBlockGroup> {+ @SuppressWarnings("rawtypes")+ private final FieldComparator[] comparators;++ private final int[] reversed;++ @SuppressWarnings({"rawtypes"})+ public GroupComparator(Sort groupSort) {+ final SortField[] sortFields = groupSort.getSort();+ comparators = new FieldComparator[sortFields.length];+ reversed = new int[sortFields.length];+ for (int compIDX = 0; compIDX < sortFields.length; compIDX++) {+ final SortField sortField = sortFields[compIDX];+ comparators[compIDX] = sortField.getComparator(1, Pruning.NONE);+ reversed[compIDX] = sortField.getReverse() ? -1 : 1;+ }+ }++ @Override+ @SuppressWarnings({"unchecked"})+ public int compare(MergedBlockGroup group, MergedBlockGroup other) {+ if (group == other) {+ return 0;+ }+ final Object[] groupValues = group.topValues;+ final Object[] otherValues = other.topValues;+ for (int compIDX = 0; compIDX < comparators.length; compIDX++) {+ final int c =+ reversed[compIDX]+ * comparators[compIDX].compareValues(groupValues[compIDX], otherValues[compIDX]);+ if (c != 0) {+ return c;+ }+ }++ assert group.shardIndex != other.shardIndex;+ return group.shardIndex - other.shardIndex;+ }+ }++ /**+ * Merge TopGroups that are partitioned into blocks per shard. This method assumes that within+ * each shard, the groups are sorted according to the groupSort.+ *+ * @param shardGroups list of TopGroups, one per shard.+ * @param groupSort The {@link Sort} used to sort the groups. The top sorted document within each+ * group according to groupSort, determines how that group sorts against other groups. This+ * must be non-null, ie, if you want to groupSort by relevance use Sort.RELEVANCE.+ * @param groupOffset Which group to start from.+ * @param topNGroups How many top groups to keep.+ * @param docSort The sort to use within each group+ * @return TopGroups instance or null if there are no groups.+ */+ @SuppressWarnings("unchecked")+ public static <T> TopGroups<T> mergeBlockGroups(+ List<TopGroups<T>> shardGroups,+ Sort groupSort,+ int groupOffset,+ int topNGroups,+ Sort docSort) {+ if (shardGroups.isEmpty()) {+ return new TopGroups<>(+ groupSort.getSort(),+ docSort.getSort(),+ 0,+ 0,+ (GroupDocs<T>[]) new GroupDocs<?>[0],+ Float.NaN);+ }++ Integer totalGroupCount = null;+ int totalHitCount = 0;+ int totalGroupedHitCount = 0;+ for (TopGroups<T> sg : shardGroups) {+ totalHitCount += sg.totalHitCount;+ if (sg.totalGroupCount != null) {+ if (totalGroupCount == null) {+ totalGroupCount = 0;+ }+ totalGroupCount += sg.totalGroupCount;+ }+ }++ // k-way merge+ GroupComparator groupComp = new GroupComparator(groupSort);+ NavigableSet<MergedBlockGroup> queue = new TreeSet<>(groupComp);++ float totalMaxScore = Float.NaN;+ final boolean groupSortByRelevance = groupSort.equals(Sort.RELEVANCE);+ // init queue+ for (int idx = 0; idx < shardGroups.size(); idx++) {+ TopGroups<T> topGroups = shardGroups.get(idx);+ if (topGroups.groups.length == 0) {+ continue;+ }+ if (!groupSortByRelevance) {+ totalMaxScore = nonNANmax(totalMaxScore, topGroups.maxScore);+ }+ GroupDocs<T> firstGroupDocs = topGroups.groups[0];+ queue.add(new MergedBlockGroup(firstGroupDocs.groupSortValues(), idx, 0));+ }++ if (groupSortByRelevance && !queue.isEmpty()) {+ totalMaxScore = shardGroups.get(queue.first().shardIndex).maxScore;+ }++ final List<GroupDocs<T>> groupDocsList = new ArrayList<>();+ int count = 0;+ while (!queue.isEmpty()) {+ final MergedBlockGroup mergedBlockGroup = queue.pollFirst();+ TopGroups<T> shardGroup = shardGroups.get(mergedBlockGroup.shardIndex);++ int currentGroupIndex = mergedBlockGroup.groupIndex;+ GroupDocs<T> currentGroupDocs = shardGroup.groups[currentGroupIndex];+ if (count++ >= groupOffset) {+ groupDocsList.add(currentGroupDocs);+ totalGroupedHitCount += (int) currentGroupDocs.totalHits().value();+ if (groupDocsList.size() == topNGroups) {+ break;+ }+ }++ int nextGroupIndex = currentGroupIndex + 1;+ if (nextGroupIndex < shardGroup.groups.length) {+ GroupDocs<T> nextGroupDocs = shardGroup.groups[nextGroupIndex];+ queue.add(+ new MergedBlockGroup(+ nextGroupDocs.groupSortValues(), mergedBlockGroup.shardIndex, nextGroupIndex));+ }+ }++ @SuppressWarnings({"unchecked"})+ GroupDocs<T>[] groupDocs = (GroupDocs<T>[]) groupDocsList.toArray(GroupDocs[]::new);++ return new TopGroups<>(+ new TopGroups<>(+ groupSort.getSort(),+ docSort.getSort(),+ totalHitCount,+ totalGroupedHitCount,+ groupDocs,+ totalMaxScore),+ totalGroupCount);+ }}diff --git a/lucene/grouping/src/test/org/apache/lucene/search/grouping/AbstractGroupingTestCase.java b/lucene/grouping/src/test/org/apache/lucene/search/grouping/AbstractGroupingTestCase.javaindex a66154d7a08..5242debdf83 100644--- a/lucene/grouping/src/test/org/apache/lucene/search/grouping/AbstractGroupingTestCase.java+++ b/lucene/grouping/src/test/org/apache/lucene/search/grouping/AbstractGroupingTestCase.java@@ -69,7 +69,14 @@ public abstract class AbstractGroupingTestCase extends LuceneTestCase {IndexSearcher getIndexSearcher() throws IOException {if (searcher == null) {- searcher = new IndexSearcher(this.writer.getReader());+ // BlockGroupingCollectorManager does not support INTRA_SEGMENT concurrency (requires more+ // work).+ searcher =+ newSearcher(+ writer.getReader(),+ random().nextBoolean(),+ random().nextBoolean(),+ Concurrency.INTER_SEGMENT);}return searcher;}diff --git a/lucene/grouping/src/test/org/apache/lucene/search/grouping/TestBlockGrouping.java b/lucene/grouping/src/test/org/apache/lucene/search/grouping/TestBlockGrouping.javaindex 18c02422f84..5d68937e137 100644--- a/lucene/grouping/src/test/org/apache/lucene/search/grouping/TestBlockGrouping.java+++ b/lucene/grouping/src/test/org/apache/lucene/search/grouping/TestBlockGrouping.java@@ -36,6 +36,7 @@ import org.apache.lucene.search.Sort;import org.apache.lucene.search.SortField;import org.apache.lucene.search.TermQuery;import org.apache.lucene.search.TopDocs;+import org.apache.lucene.search.TotalHits;import org.apache.lucene.tests.index.RandomIndexWriter;import org.apache.lucene.util.BytesRef;@@ -58,7 +59,6 @@ public class TestBlockGrouping extends AbstractGroupingTestCase {// score of the top document from the same query with no groupingTopDocs topDoc = searcher.search(topLevel, 1);assertEquals(topDoc.scoreDocs[0].score, tg.groups[0].scoreDocs()[0].score, 0);- assertEquals(topDoc.scoreDocs[0].doc, tg.groups[0].scoreDocs()[0].doc);for (int i = 0; i < tg.groups.length; i++) {String bookName =@@ -77,6 +77,32 @@ public class TestBlockGrouping extends AbstractGroupingTestCase {shard.close();}+ public void testGroupOffset() throws IOException {+ Shard shard = new Shard();+ indexRandomDocs(shard.writer);+ IndexSearcher searcher = shard.getIndexSearcher();++ Query blockEndQuery = new TermQuery(new Term("blockEnd", "true"));+ GroupingSearch grouper = new GroupingSearch(blockEndQuery);+ grouper.setGroupDocsLimit(10);++ Query topLevel = new TermQuery(new Term("text", "grandmother"));++ int topN = 10;+ int offset = random().nextInt(1, topN);+ TopGroups<?> all = grouper.search(searcher, topLevel, 0, topN);+ TopGroups<?> offsetGroups = grouper.search(searcher, topLevel, offset, topN - offset);++ assertNotNull(offsetGroups);+ assertEquals(all.groups.length - offset, offsetGroups.groups.length);++ for (int i = 0; i < offsetGroups.groups.length; i++) {+ assertScoreDocsEquals(all.groups[i + offset].scoreDocs(), offsetGroups.groups[i].scoreDocs());+ }++ shard.close();+ }+public void testTopLevelSort() throws IOException {Shard shard = new Shard();@@ -165,6 +191,37 @@ public class TestBlockGrouping extends AbstractGroupingTestCase {shard.close();}+ @SuppressWarnings({"unchecked", "rawtypes"})+ public void testMergeBlockGroupsWithEmptyGroups() {+ SortField[] groupSort = Sort.RELEVANCE.getSort();+ SortField[] withinGroupSort = Sort.RELEVANCE.getSort();++ GroupDocs<BytesRef> group =+ new GroupDocs<>(+ 1.0f,+ 1.0f,+ new TotalHits(1, TotalHits.Relation.EQUAL_TO),+ new ScoreDoc[] {new ScoreDoc(0, 1.0f)},+ new BytesRef("group1"),+ new Object[] {1.0f});+ TopGroups<BytesRef> shardWithGroups =+ new TopGroups<>(+ new TopGroups<>(groupSort, withinGroupSort, 1, 1, new GroupDocs[] {group}, 1.0f), 1);++ TopGroups<BytesRef> shardWithNoGroups =+ new TopGroups<>(+ new TopGroups<>(groupSort, withinGroupSort, 0, 0, new GroupDocs[0], Float.NaN), 0);++ TopGroups<BytesRef> merged =+ TopGroups.mergeBlockGroups(+ List.of(shardWithGroups, shardWithNoGroups), Sort.RELEVANCE, 0, 5, Sort.RELEVANCE);++ assertNotNull(merged);+ assertEquals(1, merged.totalHitCount);+ assertEquals(1, merged.groups.length);+ assertEquals(new BytesRef("group1"), merged.groups[0].groupValue());+ }+private static void indexRandomDocs(RandomIndexWriter writer) throws IOException {int bookCount = atLeast(20);for (int i = 0; i < bookCount; i++) {diff --git a/lucene/grouping/src/test/org/apache/lucene/search/grouping/TestGroupingSearch.java b/lucene/grouping/src/test/org/apache/lucene/search/grouping/TestGroupingSearch.javaindex 308b7d2c070..07de8a18d7d 100644--- a/lucene/grouping/src/test/org/apache/lucene/search/grouping/TestGroupingSearch.java+++ b/lucene/grouping/src/test/org/apache/lucene/search/grouping/TestGroupingSearch.java@@ -36,11 +36,10 @@ import org.apache.lucene.search.similarities.BM25Similarity;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.util.LuceneTestCase;import org.apache.lucene.util.BytesRef;import org.apache.lucene.util.mutable.MutableValueStr;-public class TestGroupingSearch extends LuceneTestCase {+public class TestGroupingSearch extends AbstractGroupingTestCase {// Tests some very basic usages...public void testBasic() throws Exception {@@ -50,12 +49,9 @@ public class TestGroupingSearch extends LuceneTestCase {FieldType customType = new FieldType();customType.setStored(true);- Directory dir = newDirectory();- RandomIndexWriter w =- new RandomIndexWriter(- random(),- dir,- newIndexWriterConfig(new MockAnalyzer(random())).setMergePolicy(newLogMergePolicy()));+ Shard shard = new Shard();+ RandomIndexWriter w = shard.writer;+boolean canUseIDV = true;List<Document> documents = new ArrayList<>();// 0@@ -115,7 +111,7 @@ public class TestGroupingSearch extends LuceneTestCase {w.addDocument(doc);- IndexSearcher indexSearcher = newSearcher(w.getReader());+ IndexSearcher indexSearcher = shard.getIndexSearcher();indexSearcher.setSimilarity(new BM25Similarity());w.close();@@ -169,8 +165,7 @@ public class TestGroupingSearch extends LuceneTestCase {assertEquals(4, groups.totalGroupCount.longValue());assertEquals(4, groups.groups.length);- indexSearcher.getIndexReader().close();- dir.close();+ shard.close();}private void addGroupField(Document doc, String groupField, String value, boolean canUseIDV) {