Apache Lucene open-source search software
Introduce TermGroupFacetCollectorManager for concurrent grouped faceting (#16292)
Luca Cavannad148795b182f
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txtindex 87d4071990e..740576fc23f 100644--- a/lucene/CHANGES.txt+++ b/lucene/CHANGES.txt@@ -480,6 +480,10 @@ Improvements* GITHUB#16091: Replace deprecated IndexSearcher#search(Query, Collector) usage with CollectorManagerin JoinUtil#createJoinQuery for the GlobalOrdinalsCollector case. (Luca Cavanna)+* GITHUB#16292: Introduce TermGroupFacetCollectorManager to enable concurrent search with grouped+ faceting, removing usages of the deprecated IndexSearcher#search(Query, Collector).+ (Luca Cavanna)+Optimizations---------------------diff --git a/lucene/grouping/src/java/org/apache/lucene/search/grouping/GroupFacetCollector.java b/lucene/grouping/src/java/org/apache/lucene/search/grouping/GroupFacetCollector.javaindex c2f613f3631..fcad0a70193 100644--- a/lucene/grouping/src/java/org/apache/lucene/search/grouping/GroupFacetCollector.java+++ b/lucene/grouping/src/java/org/apache/lucene/search/grouping/GroupFacetCollector.java@@ -33,7 +33,11 @@ import org.apache.lucene.util.PriorityQueue;* Base class for computing grouped facets.** @lucene.experimental+ * @deprecated Use {@code TermGroupFacetCollectorManager} instead, which supports concurrent search.+ * {@code GroupedFacetResult} and {@code GroupedFacetResult.FacetEntry} are now top-level+ * classes.*/+@Deprecatedpublic abstract class GroupFacetCollector extends SimpleCollector {protected final String groupField;@@ -64,7 +68,13 @@ public abstract class GroupFacetCollector extends SimpleCollector {* </code> then the facets are sorted lexicographically in ascending order.* @return grouped facet results* @throws IOException If I/O related errors occur during merging segment grouped facet counts.+ * @deprecated Use {@link TermGroupFacetCollectorManager} instead. The {@code size}, {@code+ * minCount}, and {@code orderByCount} parameters are now passed to its constructor, and+ * merging happens automatically inside {@link+ * org.apache.lucene.search.IndexSearcher#search(org.apache.lucene.search.Query,+ * org.apache.lucene.search.CollectorManager)}.*/+ @Deprecatedpublic GroupedFacetResult mergeSegmentResults(int size, int minCount, boolean orderByCount)throws IOException {int totalCount = 0;diff --git a/lucene/grouping/src/java/org/apache/lucene/search/grouping/GroupedFacetResult.java b/lucene/grouping/src/java/org/apache/lucene/search/grouping/GroupedFacetResult.javanew file mode 100644index 00000000000..5e59f6d80a8--- /dev/null+++ b/lucene/grouping/src/java/org/apache/lucene/search/grouping/GroupedFacetResult.java@@ -0,0 +1,134 @@+/*+ * 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.util.ArrayList;+import java.util.Collections;+import java.util.List;+import java.util.NavigableSet;+import java.util.TreeSet;+import org.apache.lucene.util.BytesRef;++/**+ * The grouped facet result. Containing grouped facet entries, total count and total missing count.+ *+ * @lucene.experimental+ */+public class GroupedFacetResult {++ private final int maxSize;+ private final NavigableSet<FacetEntry> facetEntries;+ private final int totalMissingCount;+ private final int totalCount;++ private int currentMin;++ GroupedFacetResult(+ int size, int minCount, boolean orderByCount, int totalCount, int totalMissingCount) {+ this.facetEntries =+ new TreeSet<>(+ orderByCount+ ? (a, b) -> {+ int cmp = b.count - a.count; // Highest count first!+ if (cmp != 0) {+ return cmp;+ }+ return a.value.compareTo(b.value);+ }+ : (a, b) -> a.value.compareTo(b.value));+ this.totalMissingCount = totalMissingCount;+ this.totalCount = totalCount;+ maxSize = size;+ currentMin = minCount;+ }++ void addFacetCount(BytesRef facetValue, int count) {+ if (count < currentMin) {+ return;+ }++ FacetEntry facetEntry = new FacetEntry(facetValue, count);+ if (facetEntries.size() == maxSize) {+ if (facetEntries.higher(facetEntry) == null) {+ return;+ }+ facetEntries.pollLast();+ }+ facetEntries.add(facetEntry);++ if (facetEntries.size() == maxSize) {+ currentMin = facetEntries.last().count;+ }+ }++ /**+ * Returns a list of facet entries to be rendered based on the specified offset and limit. The+ * facet entries are retrieved from the facet entries collected during merging.+ *+ * @param offset The offset in the collected facet entries during merging+ * @param limit The number of facets to return starting from the offset.+ * @return a list of facet entries to be rendered based on the specified offset and limit+ */+ public List<FacetEntry> getFacetEntries(int offset, int limit) {+ if (offset >= facetEntries.size()) {+ return Collections.emptyList();+ }++ List<FacetEntry> entries = new ArrayList<>(Math.min(limit, facetEntries.size() - offset));++ int skipped = 0;+ int included = 0;+ for (FacetEntry facetEntry : facetEntries) {+ if (skipped < offset) {+ skipped++;+ continue;+ }+ if (included++ >= limit) {+ break;+ }+ entries.add(facetEntry);+ }+ return entries;+ }++ /**+ * Returns the sum of all facet entries counts.+ *+ * @return the sum of all facet entries counts+ */+ public int getTotalCount() {+ return totalCount;+ }++ /**+ * Returns the number of groups that didn't have a facet value.+ *+ * @return the number of groups that didn't have a facet value+ */+ public int getTotalMissingCount() {+ return totalMissingCount;+ }++ /** Represents a facet entry with a value and a count. */+ public record FacetEntry(BytesRef value, int count) {++ @Override+ public String toString() {+ return "FacetEntry{" + "value=" + value.utf8ToString() + ", count=" + count + '}';+ }+ }+}diff --git a/lucene/grouping/src/java/org/apache/lucene/search/grouping/TermGroupFacetCollector.java b/lucene/grouping/src/java/org/apache/lucene/search/grouping/TermGroupFacetCollector.javaindex 33052db4390..6a4831b59c0 100644--- a/lucene/grouping/src/java/org/apache/lucene/search/grouping/TermGroupFacetCollector.java+++ b/lucene/grouping/src/java/org/apache/lucene/search/grouping/TermGroupFacetCollector.java@@ -34,7 +34,9 @@ import org.apache.lucene.util.UnicodeUtil;* indexed terms from DocValues.** @lucene.experimental+ * @deprecated Use {@code TermGroupFacetCollectorManager} instead, which supports concurrent search.*/+@Deprecatedpublic abstract class TermGroupFacetCollector extends GroupFacetCollector {final List<GroupedFacetHit> groupedFacetHits;@@ -54,7 +56,9 @@ public abstract class TermGroupFacetCollector extends GroupFacetCollector {* which should roughly match the total number of expected unique groups. Be aware that the* heap usage is 4 bytes * initialSize.* @return <code>TermGroupFacetCollector</code> implementation+ * @deprecated Use {@code TermGroupFacetCollectorManager} instead.*/+ @Deprecatedpublic static TermGroupFacetCollector createTermGroupFacetCollector(String groupField,String facetField,diff --git a/lucene/grouping/src/java/org/apache/lucene/search/grouping/TermGroupFacetCollectorManager.java b/lucene/grouping/src/java/org/apache/lucene/search/grouping/TermGroupFacetCollectorManager.javanew file mode 100644index 00000000000..b74c6aea631--- /dev/null+++ b/lucene/grouping/src/java/org/apache/lucene/search/grouping/TermGroupFacetCollectorManager.java@@ -0,0 +1,376 @@+/*+ * 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.Collection;+import java.util.HashMap;+import java.util.HashSet;+import java.util.Map;+import java.util.Set;+import java.util.TreeSet;+import org.apache.lucene.index.DocValues;+import org.apache.lucene.index.LeafReaderContext;+import org.apache.lucene.index.SortedDocValues;+import org.apache.lucene.index.SortedSetDocValues;+import org.apache.lucene.index.TermsEnum;+import org.apache.lucene.internal.hppc.LongHashSet;+import org.apache.lucene.search.Collector;+import org.apache.lucene.search.CollectorManager;+import org.apache.lucene.search.LeafCollector;+import org.apache.lucene.search.Scorable;+import org.apache.lucene.search.ScoreMode;+import org.apache.lucene.util.BytesRef;+import org.apache.lucene.util.BytesRefBuilder;+import org.apache.lucene.util.UnicodeUtil;++/**+ * A {@link CollectorManager} for computing grouped facet counts based on term DocValues.+ *+ * <p>For each facet value, the result counts the number of distinct group values that have at least+ * one document with that facet value. Groups spanning multiple search slices are counted exactly+ * once (cross-slice deduplication is handled in {@link #reduce}).+ *+ * <p>When {@code minCount} is {@code 0}, zero-count facet terms are included in the result. Those+ * terms must be copied to {@link BytesRef} at {@link LeafCollector#finish()} time because {@link+ * #reduce} no longer has access to per-segment DocValues. On a high-cardinality facet field this+ * can use substantially more memory than when {@code minCount > 0}, which only materializes terms+ * that were actually collected.+ *+ * @lucene.experimental+ */+public class TermGroupFacetCollectorManager+ implements CollectorManager<TermGroupFacetCollectorManager.FacetCollector, GroupedFacetResult> {++ private final String groupField;+ private final String facetField;+ private final boolean facetFieldMultivalued;+ private final BytesRef facetPrefix;+ private final int size;+ private final int minCount;+ private final boolean orderByCount;++ /**+ * Creates a new TermGroupFacetCollectorManager.+ *+ * @param groupField the group field+ * @param facetField the facet field+ * @param facetFieldMultivalued whether the facet field has multiple values per document+ * @param facetPrefix only include facet entries with this prefix; may be null+ * @param size the maximum number of facet entries to include in the result (offset + limit)+ * @param minCount minimum count for a facet entry to be included. {@code 0} includes zero-count+ * terms and materializes every in-range facet term (see class javadoc)+ * @param orderByCount whether to sort facet entries by count descending (vs. lexicographic)+ */+ public TermGroupFacetCollectorManager(+ String groupField,+ String facetField,+ boolean facetFieldMultivalued,+ BytesRef facetPrefix,+ int size,+ int minCount,+ boolean orderByCount) {+ this.groupField = groupField;+ this.facetField = facetField;+ this.facetFieldMultivalued = facetFieldMultivalued;+ this.facetPrefix = facetPrefix;+ this.size = size;+ this.minCount = minCount;+ this.orderByCount = orderByCount;+ }++ @Override+ public FacetCollector newCollector() {+ return new FacetCollector(+ groupField, facetField, facetFieldMultivalued, facetPrefix, minCount == 0);+ }++ @Override+ public GroupedFacetResult reduce(Collection<FacetCollector> collectors) throws IOException {+ // Globally deduplicate (group, facet) pairs across all per-slice collectors.+ Set<FacetCollector.GroupFacetPair> globalPairs = new HashSet<>();+ for (FacetCollector collector : collectors) {+ globalPairs.addAll(collector.groupFacetPairs);+ }++ Map<BytesRef, Integer> facetCounts = new HashMap<>();+ int totalCount = 0;+ int missingCount = 0;+ for (FacetCollector.GroupFacetPair pair : globalPairs) {+ if (pair.facetValue() == null) {+ missingCount++;+ } else {+ totalCount++;+ facetCounts.merge(pair.facetValue(), 1, Integer::sum);+ }+ }++ // Terms must be presented to addFacetCount in ascending byte order: GroupedFacetResult's+ // internal currentMin optimization assumes sorted input (as mergeSegmentResults guarantees+ // via its priority queue). TreeSet gives us that order for free.+ Set<BytesRef> sortedTerms = new TreeSet<>(facetCounts.keySet());+ if (minCount == 0) {+ // Union in-range terms from all collectors so that zero-count terms are included.+ for (FacetCollector collector : collectors) {+ sortedTerms.addAll(collector.allFacetTermsInRange);+ }+ }++ GroupedFacetResult result =+ new GroupedFacetResult(size, minCount, orderByCount, totalCount, missingCount);+ for (BytesRef term : sortedTerms) {+ result.addFacetCount(term, facetCounts.getOrDefault(term, 0));+ }+ return result;+ }++ /**+ * Per-slice collector. During collection, (groupOrd, facetOrd) pairs are tracked as packed longs+ * to avoid {@link BytesRef} allocations in the hot path. Ordinals are translated to term values+ * once per segment at {@code finish()} time. Cross-slice deduplication is performed by {@link+ * TermGroupFacetCollectorManager#reduce}.+ */+ static class FacetCollector implements Collector {++ private final String groupField;+ private final String facetField;+ private final boolean facetFieldMultivalued;+ private final BytesRef facetPrefix;+ private final boolean needAllFacetTerms;++ // Accumulated across all segments processed by this collector's slice.+ final Set<GroupFacetPair> groupFacetPairs = new HashSet<>();+ // Populated only when needAllFacetTerms=true (minCount==0), for zero-count term support.+ final Set<BytesRef> allFacetTermsInRange = new HashSet<>();++ FacetCollector(+ String groupField,+ String facetField,+ boolean facetFieldMultivalued,+ BytesRef facetPrefix,+ boolean needAllFacetTerms) {+ this.groupField = groupField;+ this.facetField = facetField;+ this.facetFieldMultivalued = facetFieldMultivalued;+ this.facetPrefix = facetPrefix;+ this.needAllFacetTerms = needAllFacetTerms;+ }++ @Override+ public LeafCollector getLeafCollector(LeafReaderContext context) throws IOException {+ return facetFieldMultivalued ? new MVLeafCollector(context) : new SVLeafCollector(context);+ }++ @Override+ public ScoreMode scoreMode() {+ return ScoreMode.COMPLETE_NO_SCORES;+ }++ // Packs (groupOrd, facetOrd) into a single long. Adding 1 to each maps the missing sentinel+ // (-1) to 0, making the encoding unambiguous for non-negative ordinal values.+ private static long encodePair(int groupOrd, int facetOrd) {+ return (((long) groupOrd + 1) << 32) | ((long) facetOrd + 1);+ }++ // Single-valued facet field implementation.+ private class SVLeafCollector implements LeafCollector {++ private final SortedDocValues groupDV;+ private final SortedDocValues facetDV;+ private final int startFacetOrd; // -1 when no prefix, to allow missing facet value through+ private final int endFacetOrd;+ private final LongHashSet segmentPairs = new LongHashSet();++ SVLeafCollector(LeafReaderContext context) throws IOException {+ groupDV = DocValues.getSorted(context.reader(), groupField);+ facetDV = DocValues.getSorted(context.reader(), facetField);+ int sf, ef;+ if (facetPrefix != null) {+ sf = facetDV.lookupTerm(facetPrefix);+ if (sf < 0) {+ sf = -sf - 1;+ }+ BytesRefBuilder end = new BytesRefBuilder();+ end.append(facetPrefix);+ end.append(UnicodeUtil.BIG_TERM);+ ef = facetDV.lookupTerm(end.get());+ assert ef < 0;+ ef = -ef - 1;+ } else {+ sf = -1;+ ef = facetDV.getValueCount();+ }+ startFacetOrd = sf;+ endFacetOrd = ef;+ }++ @Override+ public void setScorer(Scorable scorer) {}++ @Override+ public void collect(int doc) throws IOException {+ if (doc > facetDV.docID()) {+ facetDV.advance(doc);+ }+ int facetOrd = doc == facetDV.docID() ? facetDV.ordValue() : -1;+ if (facetOrd < startFacetOrd || facetOrd >= endFacetOrd) {+ return;+ }+ if (doc > groupDV.docID()) {+ groupDV.advance(doc);+ }+ int groupOrd = doc == groupDV.docID() ? groupDV.ordValue() : -1;+ segmentPairs.add(encodePair(groupOrd, facetOrd));+ }++ @Override+ public void finish() throws IOException {+ for (var cursor : segmentPairs) {+ int groupOrd = (int) (cursor.value >>> 32) - 1;+ int facetOrd = (int) (cursor.value & 0xFFFFFFFFL) - 1;+ BytesRef groupValue =+ groupOrd < 0 ? null : BytesRef.deepCopyOf(groupDV.lookupOrd(groupOrd));+ BytesRef facetValue =+ facetOrd < 0 ? null : BytesRef.deepCopyOf(facetDV.lookupOrd(facetOrd));+ groupFacetPairs.add(new GroupFacetPair(groupValue, facetValue));+ }+ segmentPairs.clear();+ if (needAllFacetTerms) {+ int start = startFacetOrd < 0 ? 0 : startFacetOrd;+ if (start < endFacetOrd) {+ TermsEnum tenum = facetDV.termsEnum();+ tenum.seekExact(start);+ for (int i = start; i < endFacetOrd; i++) {+ BytesRef term = tenum.term();+ if (!allFacetTermsInRange.contains(term)) {+ allFacetTermsInRange.add(BytesRef.deepCopyOf(term));+ }+ if (i + 1 < endFacetOrd) {+ tenum.next();+ }+ }+ }+ }+ }+ }++ // Multi-valued facet field implementation.+ private class MVLeafCollector implements LeafCollector {++ private final SortedDocValues groupDV;+ private final SortedSetDocValues facetDV;+ private final int facetFieldNumTerms;+ private final int startFacetOrd;+ private final int endFacetOrd;+ private final LongHashSet segmentPairs = new LongHashSet();++ MVLeafCollector(LeafReaderContext context) throws IOException {+ groupDV = DocValues.getSorted(context.reader(), groupField);+ facetDV = DocValues.getSortedSet(context.reader(), facetField);+ facetFieldNumTerms = (int) facetDV.getValueCount();+ int sf, ef;+ if (facetPrefix != null) {+ if (facetFieldNumTerms == 0) {+ sf = 0;+ ef = 0;+ } else {+ TermsEnum tenum = facetDV.termsEnum();+ TermsEnum.SeekStatus status = tenum.seekCeil(facetPrefix);+ if (status == TermsEnum.SeekStatus.END) {+ sf = 0;+ ef = 0;+ } else {+ sf = (int) tenum.ord();+ BytesRefBuilder end = new BytesRefBuilder();+ end.append(facetPrefix);+ end.append(UnicodeUtil.BIG_TERM);+ status = tenum.seekCeil(end.get());+ ef = (status == TermsEnum.SeekStatus.END) ? facetFieldNumTerms : (int) tenum.ord();+ }+ }+ } else {+ sf = 0;+ ef = facetFieldNumTerms;+ }+ startFacetOrd = sf;+ endFacetOrd = ef;+ }++ @Override+ public void setScorer(Scorable scorer) {}++ @Override+ public void collect(int doc) throws IOException {+ if (doc > facetDV.docID()) {+ facetDV.advance(doc);+ }+ boolean hasFacetDocValues = doc == facetDV.docID();+ if (hasFacetDocValues) {+ int groupOrd = Integer.MIN_VALUE; // lazily fetched on first in-range facet ord+ for (int i = 0; i < facetDV.docValueCount(); i++) {+ int facetOrd = (int) facetDV.nextOrd();+ if (facetOrd >= startFacetOrd && facetOrd < endFacetOrd) {+ if (groupOrd == Integer.MIN_VALUE) {+ if (doc > groupDV.docID()) {+ groupDV.advance(doc);+ }+ groupOrd = doc == groupDV.docID() ? groupDV.ordValue() : -1;+ }+ segmentPairs.add(encodePair(groupOrd, facetOrd));+ }+ }+ } else if (facetPrefix == null) {+ // No facet values at all and no prefix: count as missing (facetOrd = -1).+ if (doc > groupDV.docID()) {+ groupDV.advance(doc);+ }+ int groupOrd = doc == groupDV.docID() ? groupDV.ordValue() : -1;+ segmentPairs.add(encodePair(groupOrd, -1));+ }+ }++ @Override+ public void finish() throws IOException {+ for (var cursor : segmentPairs) {+ int groupOrd = (int) (cursor.value >>> 32) - 1;+ int facetOrd = (int) (cursor.value & 0xFFFFFFFFL) - 1;+ BytesRef groupValue =+ groupOrd < 0 ? null : BytesRef.deepCopyOf(groupDV.lookupOrd(groupOrd));+ BytesRef facetValue =+ facetOrd < 0 ? null : BytesRef.deepCopyOf(facetDV.lookupOrd((long) facetOrd));+ groupFacetPairs.add(new GroupFacetPair(groupValue, facetValue));+ }+ segmentPairs.clear();+ if (needAllFacetTerms && startFacetOrd < endFacetOrd) {+ TermsEnum tenum = facetDV.termsEnum();+ tenum.seekExact(startFacetOrd);+ for (int i = startFacetOrd; i < endFacetOrd; i++) {+ BytesRef term = tenum.term();+ if (!allFacetTermsInRange.contains(term)) {+ allFacetTermsInRange.add(BytesRef.deepCopyOf(term));+ }+ if (i + 1 < endFacetOrd) {+ tenum.next();+ }+ }+ }+ }+ }++ record GroupFacetPair(BytesRef groupValue, BytesRef facetValue) {}+ }+}diff --git a/lucene/grouping/src/java/org/apache/lucene/search/grouping/package-info.java b/lucene/grouping/src/java/org/apache/lucene/search/grouping/package-info.javaindex 0e5e9f30a4a..f8ebe3368f9 100644--- a/lucene/grouping/src/java/org/apache/lucene/search/grouping/package-info.java+++ b/lucene/grouping/src/java/org/apache/lucene/search/grouping/package-info.java@@ -176,5 +176,21 @@* int maxDoc = indexSearcher.getIndexReader().maxDoc();* Bits groupHeadsBitSet = result.retrieveGroupHeads(maxDoc);* </code></pre>+ *+ * <p>Grouped faceting is handled by {@link+ * org.apache.lucene.search.grouping.TermGroupFacetCollectorManager}. For each facet value it counts+ * how many distinct groups have at least one matching document with that value. The manager+ * supports concurrent collection; groups that span multiple search slices are counted once.+ *+ * <pre><code class="language-java">+ * TermGroupFacetCollectorManager manager =+ * new TermGroupFacetCollectorManager(+ * "author", "category", false, null, offset + limit, minCount, orderByCount);+ * GroupedFacetResult facetResult =+ * indexSearcher.search(new TermQuery(new Term("content", searchTerm)), manager);+ * int totalCount = facetResult.getTotalCount();+ * int missingCount = facetResult.getTotalMissingCount();+ * List<GroupedFacetResult.FacetEntry> entries = facetResult.getFacetEntries(offset, limit);+ * </code></pre>*/package org.apache.lucene.search.grouping;diff --git a/lucene/grouping/src/test/org/apache/lucene/search/grouping/TestTermGroupFacetCollectorManager.java b/lucene/grouping/src/test/org/apache/lucene/search/grouping/TestTermGroupFacetCollectorManager.javanew file mode 100644index 00000000000..00ce9612a3b--- /dev/null+++ b/lucene/grouping/src/test/org/apache/lucene/search/grouping/TestTermGroupFacetCollectorManager.java@@ -0,0 +1,855 @@+/*+ * 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.Collections;+import java.util.HashMap;+import java.util.HashSet;+import java.util.List;+import java.util.Locale;+import java.util.Map;+import java.util.NavigableSet;+import java.util.Random;+import java.util.Set;+import java.util.TreeSet;+import org.apache.lucene.document.Document;+import org.apache.lucene.document.Field;+import org.apache.lucene.document.FieldType;+import org.apache.lucene.document.SortedDocValuesField;+import org.apache.lucene.document.SortedSetDocValuesField;+import org.apache.lucene.document.StringField;+import org.apache.lucene.index.DirectoryReader;+import org.apache.lucene.index.NoMergePolicy;+import org.apache.lucene.index.Term;+import org.apache.lucene.search.IndexSearcher;+import org.apache.lucene.search.MatchAllDocsQuery;+import org.apache.lucene.search.TermQuery;+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.TestUtil;+import org.apache.lucene.util.BytesRef;++/** Tests {@link TermGroupFacetCollectorManager}. */+public class TestTermGroupFacetCollectorManager extends AbstractGroupingTestCase {++ public void testSimple() throws Exception {+ final String groupField = "hotel";+ FieldType customType = new FieldType();+ customType.setStored(true);++ Directory dir = newDirectory();+ RandomIndexWriter w =+ new RandomIndexWriter(+ random(),+ dir,+ newIndexWriterConfig(new MockAnalyzer(random())).setMergePolicy(newLogMergePolicy()));+ boolean useDv = true;++ // 0+ Document doc = new Document();+ addField(doc, groupField, "a", useDv);+ addField(doc, "airport", "ams", useDv);+ addField(doc, "duration", "5", useDv);+ w.addDocument(doc);++ // 1+ doc = new Document();+ addField(doc, groupField, "a", useDv);+ addField(doc, "airport", "dus", useDv);+ addField(doc, "duration", "10", useDv);+ w.addDocument(doc);++ // 2+ doc = new Document();+ addField(doc, groupField, "b", useDv);+ addField(doc, "airport", "ams", useDv);+ addField(doc, "duration", "10", useDv);+ w.addDocument(doc);+ w.commit(); // To ensure a second segment++ // 3+ doc = new Document();+ addField(doc, groupField, "b", useDv);+ addField(doc, "airport", "ams", useDv);+ addField(doc, "duration", "5", useDv);+ w.addDocument(doc);++ // 4+ doc = new Document();+ addField(doc, groupField, "b", useDv);+ addField(doc, "airport", "ams", useDv);+ addField(doc, "duration", "5", useDv);+ w.addDocument(doc);++ IndexSearcher indexSearcher = newSearcher(w.getReader());++ List<GroupedFacetResult.FacetEntry> entries;+ GroupedFacetResult airportResult;++ for (int limit : new int[] {2, 10, 100, Integer.MAX_VALUE}) {+ // any of these limits is plenty for the data we have++ int maxOffset = 5;+ airportResult =+ indexSearcher.search(+ MatchAllDocsQuery.INSTANCE,+ createRandomCollectorManager(+ useDv ? "hotel_dv" : "hotel",+ useDv ? "airport_dv" : "airport",+ null,+ false,+ Integer.MAX_VALUE == limit ? limit : maxOffset + limit,+ 0,+ false));++ assertEquals(3, airportResult.getTotalCount());+ assertEquals(0, airportResult.getTotalMissingCount());++ entries = airportResult.getFacetEntries(maxOffset, limit);+ assertEquals(0, entries.size());++ entries = airportResult.getFacetEntries(0, limit);+ assertEquals(2, entries.size());+ assertEquals("ams", entries.get(0).value().utf8ToString());+ assertEquals(2, entries.get(0).count());+ assertEquals("dus", entries.get(1).value().utf8ToString());+ assertEquals(1, entries.get(1).count());++ entries = airportResult.getFacetEntries(1, limit);+ assertEquals(1, entries.size());+ assertEquals("dus", entries.get(0).value().utf8ToString());+ assertEquals(1, entries.get(0).count());+ }++ GroupedFacetResult durationResult =+ indexSearcher.search(+ MatchAllDocsQuery.INSTANCE,+ createRandomCollectorManager(+ useDv ? "hotel_dv" : "hotel",+ useDv ? "duration_dv" : "duration",+ null,+ false,+ 10,+ 0,+ false));+ assertEquals(4, durationResult.getTotalCount());+ assertEquals(0, durationResult.getTotalMissingCount());++ entries = durationResult.getFacetEntries(0, 10);+ assertEquals(2, entries.size());+ assertEquals("10", entries.get(0).value().utf8ToString());+ assertEquals(2, entries.get(0).count());+ assertEquals("5", entries.get(1).value().utf8ToString());+ assertEquals(2, entries.get(1).count());++ // 5+ doc = new Document();+ addField(doc, groupField, "b", useDv);+ // missing airport+ if (useDv) {+ addField(doc, "airport", "", useDv);+ }+ addField(doc, "duration", "5", useDv);+ w.addDocument(doc);++ // 6+ doc = new Document();+ addField(doc, groupField, "b", useDv);+ addField(doc, "airport", "bru", useDv);+ addField(doc, "duration", "10", useDv);+ w.addDocument(doc);++ // 7+ doc = new Document();+ addField(doc, groupField, "b", useDv);+ addField(doc, "airport", "bru", useDv);+ addField(doc, "duration", "15", useDv);+ w.addDocument(doc);++ // 8+ doc = new Document();+ addField(doc, groupField, "a", useDv);+ addField(doc, "airport", "bru", useDv);+ addField(doc, "duration", "10", useDv);+ w.addDocument(doc);++ indexSearcher.getIndexReader().close();+ indexSearcher = newSearcher(w.getReader());+ airportResult =+ indexSearcher.search(+ MatchAllDocsQuery.INSTANCE,+ createRandomCollectorManager(+ useDv ? "hotel_dv" : "hotel",+ useDv ? "airport_dv" : "airport",+ null,+ !useDv,+ 3,+ 0,+ true));+ entries = airportResult.getFacetEntries(1, 2);+ assertEquals(2, entries.size());+ if (useDv) {+ assertEquals(6, airportResult.getTotalCount());+ assertEquals(0, airportResult.getTotalMissingCount());+ assertEquals("bru", entries.get(0).value().utf8ToString());+ assertEquals(2, entries.get(0).count());+ assertEquals("", entries.get(1).value().utf8ToString());+ assertEquals(1, entries.get(1).count());+ } else {+ assertEquals(5, airportResult.getTotalCount());+ assertEquals(1, airportResult.getTotalMissingCount());+ assertEquals("bru", entries.get(0).value().utf8ToString());+ assertEquals(2, entries.get(0).count());+ assertEquals("dus", entries.get(1).value().utf8ToString());+ assertEquals(1, entries.get(1).count());+ }++ durationResult =+ indexSearcher.search(+ MatchAllDocsQuery.INSTANCE,+ createRandomCollectorManager(+ useDv ? "hotel_dv" : "hotel",+ useDv ? "duration_dv" : "duration",+ null,+ false,+ 10,+ 2,+ true));+ assertEquals(5, durationResult.getTotalCount());+ assertEquals(0, durationResult.getTotalMissingCount());++ entries = durationResult.getFacetEntries(1, 1);+ assertEquals(1, entries.size());+ assertEquals("5", entries.get(0).value().utf8ToString());+ assertEquals(2, entries.get(0).count());++ // 9+ doc = new Document();+ addField(doc, groupField, "c", useDv);+ addField(doc, "airport", "bru", useDv);+ addField(doc, "duration", "15", useDv);+ w.addDocument(doc);++ // 10+ doc = new Document();+ addField(doc, groupField, "c", useDv);+ addField(doc, "airport", "dus", useDv);+ addField(doc, "duration", "10", useDv);+ w.addDocument(doc);++ indexSearcher.getIndexReader().close();+ indexSearcher = newSearcher(w.getReader());+ airportResult =+ indexSearcher.search(+ MatchAllDocsQuery.INSTANCE,+ createRandomCollectorManager(+ useDv ? "hotel_dv" : "hotel",+ useDv ? "airport_dv" : "airport",+ null,+ false,+ 10,+ 0,+ false));+ entries = airportResult.getFacetEntries(0, 10);+ if (useDv) {+ assertEquals(8, airportResult.getTotalCount());+ assertEquals(0, airportResult.getTotalMissingCount());+ assertEquals(4, entries.size());+ assertEquals("", entries.get(0).value().utf8ToString());+ assertEquals(1, entries.get(0).count());+ assertEquals("ams", entries.get(1).value().utf8ToString());+ assertEquals(2, entries.get(1).count());+ assertEquals("bru", entries.get(2).value().utf8ToString());+ assertEquals(3, entries.get(2).count());+ assertEquals("dus", entries.get(3).value().utf8ToString());+ assertEquals(2, entries.get(3).count());+ } else {+ assertEquals(7, airportResult.getTotalCount());+ assertEquals(1, airportResult.getTotalMissingCount());+ assertEquals(3, entries.size());+ assertEquals("ams", entries.get(0).value().utf8ToString());+ assertEquals(2, entries.get(0).count());+ assertEquals("bru", entries.get(1).value().utf8ToString());+ assertEquals(3, entries.get(1).count());+ assertEquals("dus", entries.get(2).value().utf8ToString());+ assertEquals(2, entries.get(2).count());+ }++ durationResult =+ indexSearcher.search(+ MatchAllDocsQuery.INSTANCE,+ createRandomCollectorManager(+ useDv ? "hotel_dv" : "hotel",+ useDv ? "duration_dv" : "duration",+ "1",+ false,+ 10,+ 0,+ true));+ assertEquals(5, durationResult.getTotalCount());+ assertEquals(0, durationResult.getTotalMissingCount());++ entries = durationResult.getFacetEntries(0, 10);+ assertEquals(2, entries.size());+ assertEquals("10", entries.get(0).value().utf8ToString());+ assertEquals(3, entries.get(0).count());+ assertEquals("15", entries.get(1).value().utf8ToString());+ assertEquals(2, entries.get(1).count());++ w.close();+ indexSearcher.getIndexReader().close();+ dir.close();+ }++ public void testMVGroupedFacetingWithDeletes() throws Exception {+ final String groupField = "hotel";+ FieldType customType = new FieldType();+ customType.setStored(true);++ Directory dir = newDirectory();+ RandomIndexWriter w =+ new RandomIndexWriter(+ random(),+ dir,+ newIndexWriterConfig(new MockAnalyzer(random()))+ .setMergePolicy(NoMergePolicy.INSTANCE));+ boolean useDv = true;++ // Cannot assert this since we use NoMergePolicy:+ w.setDoRandomForceMergeAssert(false);++ // 0+ Document doc = new Document();+ doc.add(new StringField("x", "x", Field.Store.NO));+ w.addDocument(doc);++ // 1+ doc = new Document();+ addField(doc, groupField, "a", useDv);+ doc.add(new SortedSetDocValuesField("airport", new BytesRef("ams")));+ w.addDocument(doc);++ w.commit();+ w.deleteDocuments(new TermQuery(new Term("airport", "ams")));++ // 2+ doc = new Document();+ addField(doc, groupField, "a", useDv);+ doc.add(new SortedSetDocValuesField("airport", new BytesRef("ams")));+ w.addDocument(doc);++ // 3+ doc = new Document();+ addField(doc, groupField, "a", useDv);+ doc.add(new SortedSetDocValuesField("airport", new BytesRef("dus")));+ w.addDocument(doc);++ // 4+ doc = new Document();+ addField(doc, groupField, "b", useDv);+ doc.add(new SortedSetDocValuesField("airport", new BytesRef("ams")));+ w.addDocument(doc);++ // 5+ doc = new Document();+ addField(doc, groupField, "b", useDv);+ doc.add(new SortedSetDocValuesField("airport", new BytesRef("ams")));+ w.addDocument(doc);++ // 6+ doc = new Document();+ addField(doc, groupField, "b", useDv);+ doc.add(new SortedSetDocValuesField("airport", new BytesRef("ams")));+ w.addDocument(doc);+ w.commit();++ // 7+ doc = new Document();+ doc.add(new StringField("x", "x", Field.Store.NO));+ w.addDocument(doc);+ w.commit();++ w.close();+ IndexSearcher indexSearcher = newSearcher(DirectoryReader.open(dir));+ GroupedFacetResult airportResult =+ indexSearcher.search(+ MatchAllDocsQuery.INSTANCE,+ createRandomCollectorManager(groupField + "_dv", "airport", null, true, 10, 0, false));+ assertEquals(3, airportResult.getTotalCount());+ assertEquals(1, airportResult.getTotalMissingCount());++ List<GroupedFacetResult.FacetEntry> entries = airportResult.getFacetEntries(0, 10);+ assertEquals(2, entries.size());+ assertEquals("ams", entries.get(0).value().utf8ToString());+ assertEquals(2, entries.get(0).count());+ assertEquals("dus", entries.get(1).value().utf8ToString());+ assertEquals(1, entries.get(1).count());++ indexSearcher.getIndexReader().close();+ dir.close();+ }++ private void addField(Document doc, String field, String value, boolean canUseIDV) {+ assert canUseIDV;+ doc.add(new SortedDocValuesField(field + "_dv", new BytesRef(value)));+ }++ public void testRandom() throws Exception {+ Random random = random();+ int numberOfRuns = atLeast(1);+ for (int indexIter = 0; indexIter < numberOfRuns; indexIter++) {+ boolean multipleFacetsPerDocument = random.nextBoolean();+ IndexContext context = createIndexContext(multipleFacetsPerDocument);+ final IndexSearcher searcher = newSearcher(context.indexReader);++ if (VERBOSE) {+ System.out.println("TEST: searcher=" + searcher);+ }++ for (int searchIter = 0; searchIter < 100; searchIter++) {+ if (VERBOSE) {+ System.out.println("TEST: searchIter=" + searchIter);+ }+ String searchTerm = context.contentStrings[random.nextInt(context.contentStrings.length)];+ int limit = random.nextInt(context.facetValues.size());+ int offset = random.nextInt(context.facetValues.size() - limit);+ int size = offset + limit;+ int minCount =+ random.nextBoolean() ? 0 : random.nextInt(1 + context.facetWithMostGroups / 10);+ boolean orderByCount = random.nextBoolean();+ String randomStr =+ getFromSet(context.facetValues, random.nextInt(context.facetValues.size()));+ final String facetPrefix;+ if (randomStr == null) {+ facetPrefix = null;+ } else {+ int codePointLen = randomStr.codePointCount(0, randomStr.length());+ int randomLen = random.nextInt(codePointLen);+ if (codePointLen == randomLen - 1) {+ facetPrefix = null;+ } else {+ int end = randomStr.offsetByCodePoints(0, randomLen);+ facetPrefix = random.nextBoolean() ? null : randomStr.substring(end);+ }+ }++ ExpectedFacetResult expectedFacetResult =+ createExpectedFacetResult(+ searchTerm, context, offset, limit, minCount, orderByCount, facetPrefix);+ GroupedFacetResult actualFacetResult =+ searcher.search(+ new TermQuery(new Term("content", searchTerm)),+ createRandomCollectorManager(+ "group",+ "facet",+ facetPrefix,+ multipleFacetsPerDocument,+ size,+ minCount,+ orderByCount));++ List<GroupedFacetResult.FacetEntry> expectedFacetEntries =+ expectedFacetResult.facetEntries();+ List<GroupedFacetResult.FacetEntry> actualFacetEntries =+ actualFacetResult.getFacetEntries(offset, limit);++ if (VERBOSE) {+ System.out.println("Collector: TermGroupFacetCollectorManager");+ System.out.println("Num group: " + context.numGroups);+ System.out.println("Num doc: " + context.numDocs);+ System.out.println("Index iter: " + indexIter);+ System.out.println("multipleFacetsPerDocument: " + multipleFacetsPerDocument);+ System.out.println("Search iter: " + searchIter);++ System.out.println("Search term: " + searchTerm);+ System.out.println("Min count: " + minCount);+ System.out.println("Facet offset: " + offset);+ System.out.println("Facet limit: " + limit);+ System.out.println("Facet prefix: " + facetPrefix);+ System.out.println("Order by count: " + orderByCount);++ System.out.println("\n=== Expected: \n");+ System.out.println("Total count " + expectedFacetResult.totalCount());+ System.out.println("Total missing count " + expectedFacetResult.totalMissingCount());+ int counter = 0;+ for (GroupedFacetResult.FacetEntry expectedFacetEntry : expectedFacetEntries) {+ System.out.printf(+ Locale.ROOT,+ "%d. Expected facet value %s with count %d%n",+ counter++,+ expectedFacetEntry.value().utf8ToString(),+ expectedFacetEntry.count());+ }++ System.out.println("\n=== Actual: \n");+ System.out.println("Total count " + actualFacetResult.getTotalCount());+ System.out.println("Total missing count " + actualFacetResult.getTotalMissingCount());+ counter = 0;+ for (GroupedFacetResult.FacetEntry actualFacetEntry : actualFacetEntries) {+ System.out.printf(+ Locale.ROOT,+ "%d. Actual facet value %s with count %d%n",+ counter++,+ actualFacetEntry.value().utf8ToString(),+ actualFacetEntry.count());+ }+ System.out.println(+ "\n===================================================================================");+ }++ assertEquals(expectedFacetResult.totalCount(), actualFacetResult.getTotalCount());+ assertEquals(+ expectedFacetResult.totalMissingCount(), actualFacetResult.getTotalMissingCount());+ assertEquals(expectedFacetEntries.size(), actualFacetEntries.size());+ for (int i = 0; i < expectedFacetEntries.size(); i++) {+ GroupedFacetResult.FacetEntry expectedFacetEntry = expectedFacetEntries.get(i);+ GroupedFacetResult.FacetEntry actualFacetEntry = actualFacetEntries.get(i);+ assertEquals(+ "i="+ + i+ + ": "+ + expectedFacetEntry.value().utf8ToString()+ + " != "+ + actualFacetEntry.value().utf8ToString(),+ expectedFacetEntry.value(),+ actualFacetEntry.value());+ assertEquals(+ "i=" + i + ": " + expectedFacetEntry.count() + " != " + actualFacetEntry.count(),+ expectedFacetEntry.count(),+ actualFacetEntry.count());+ }+ }++ context.indexReader.close();+ context.dir.close();+ }+ }++ private IndexContext createIndexContext(boolean multipleFacetValuesPerDocument)+ throws IOException {+ final Random random = random();+ final int numDocs = TestUtil.nextInt(random, 138, 1145) * RANDOM_MULTIPLIER;+ final int numGroups = TestUtil.nextInt(random, 1, numDocs / 4);+ final int numFacets = TestUtil.nextInt(random, 1, numDocs / 6);++ if (VERBOSE) {+ System.out.println("TEST: numDocs=" + numDocs + " numGroups=" + numGroups);+ }++ final List<String> groups = new ArrayList<>();+ for (int i = 0; i < numGroups; i++) {+ groups.add(generateRandomNonEmptyString());+ }+ final List<String> facetValues = new ArrayList<>();+ for (int i = 0; i < numFacets; i++) {+ facetValues.add(generateRandomNonEmptyString());+ }+ final String[] contentBrs = new String[TestUtil.nextInt(random, 2, 20)];+ if (VERBOSE) {+ System.out.println("TEST: create fake content");+ }+ for (int contentIDX = 0; contentIDX < contentBrs.length; contentIDX++) {+ contentBrs[contentIDX] = generateRandomNonEmptyString();+ if (VERBOSE) {+ System.out.println(" content=" + contentBrs[contentIDX]);+ }+ }++ Directory dir = newDirectory();+ RandomIndexWriter writer =+ new RandomIndexWriter(random, dir, newIndexWriterConfig(new MockAnalyzer(random)));+ Document doc = new Document();+ Document docNoGroup = new Document();+ Document docNoFacet = new Document();+ Document docNoGroupNoFacet = new Document();+ Field group = newStringField("group", "", Field.Store.NO);+ Field groupDc = new SortedDocValuesField("group", new BytesRef());+ doc.add(groupDc);+ docNoFacet.add(groupDc);+ doc.add(group);+ docNoFacet.add(group);+ Field[] facetFields;+ if (multipleFacetValuesPerDocument == false) {+ facetFields = new Field[2];+ facetFields[0] = newStringField("facet", "", Field.Store.NO);+ doc.add(facetFields[0]);+ docNoGroup.add(facetFields[0]);+ facetFields[1] = new SortedDocValuesField("facet", new BytesRef());+ doc.add(facetFields[1]);+ docNoGroup.add(facetFields[1]);+ } else {+ facetFields =+ multipleFacetValuesPerDocument ? new Field[2 + random.nextInt(6)] : new Field[1];+ for (int i = 0; i < facetFields.length; i++) {+ facetFields[i] = new SortedSetDocValuesField("facet", new BytesRef());+ doc.add(facetFields[i]);+ docNoGroup.add(facetFields[i]);+ }+ }+ Field content = newStringField("content", "", Field.Store.NO);+ doc.add(content);+ docNoGroup.add(content);+ docNoFacet.add(content);+ docNoGroupNoFacet.add(content);++ NavigableSet<String> uniqueFacetValues =+ new TreeSet<>(+ (a, b) -> {+ if (a == b) {+ return 0;+ } else if (a == null) {+ return -1;+ } else if (b == null) {+ return 1;+ } else {+ return a.compareTo(b);+ }+ });+ Map<String, Map<String, Set<String>>> searchTermToFacetToGroups = new HashMap<>();+ int facetWithMostGroups = 0;+ for (int i = 0; i < numDocs; i++) {+ final String groupValue;+ if (random.nextInt(24) == 17) {+ // So we test the "doc doesn't have the group'd+ // field" case:+ groupValue = "";+ } else {+ groupValue = groups.get(random.nextInt(groups.size()));+ }++ String contentStr = contentBrs[random.nextInt(contentBrs.length)];+ if (!searchTermToFacetToGroups.containsKey(contentStr)) {+ searchTermToFacetToGroups.put(contentStr, new HashMap<>());+ }+ Map<String, Set<String>> facetToGroups = searchTermToFacetToGroups.get(contentStr);++ List<String> facetVals = new ArrayList<>();+ if (multipleFacetValuesPerDocument == false) {+ String facetValue = facetValues.get(random.nextInt(facetValues.size()));+ uniqueFacetValues.add(facetValue);+ if (!facetToGroups.containsKey(facetValue)) {+ facetToGroups.put(facetValue, new HashSet<>());+ }+ Set<String> groupsInFacet = facetToGroups.get(facetValue);+ groupsInFacet.add(groupValue);+ if (groupsInFacet.size() > facetWithMostGroups) {+ facetWithMostGroups = groupsInFacet.size();+ }+ facetFields[0].setStringValue(facetValue);+ facetFields[1].setBytesValue(new BytesRef(facetValue));+ facetVals.add(facetValue);+ } else {+ for (Field facetField : facetFields) {+ String facetValue = facetValues.get(random.nextInt(facetValues.size()));+ uniqueFacetValues.add(facetValue);+ if (!facetToGroups.containsKey(facetValue)) {+ facetToGroups.put(facetValue, new HashSet<>());+ }+ Set<String> groupsInFacet = facetToGroups.get(facetValue);+ groupsInFacet.add(groupValue);+ if (groupsInFacet.size() > facetWithMostGroups) {+ facetWithMostGroups = groupsInFacet.size();+ }+ facetField.setBytesValue(new BytesRef(facetValue));+ facetVals.add(facetValue);+ }+ }++ if (VERBOSE) {+ System.out.println(+ " doc content="+ + contentStr+ + " group="+ + (groupValue == null ? "null" : groupValue)+ + " facetVals="+ + facetVals);+ }++ if (groupValue != null) {+ groupDc.setBytesValue(new BytesRef(groupValue));+ group.setStringValue(groupValue);+ } else {+ // TODO: not true+ // DV cannot have missing values:+ groupDc.setBytesValue(new BytesRef());+ }+ content.setStringValue(contentStr);+ if (groupValue == null && facetVals.isEmpty()) {+ writer.addDocument(docNoGroupNoFacet);+ } else if (facetVals.isEmpty()) {+ writer.addDocument(docNoFacet);+ } else if (groupValue == null) {+ writer.addDocument(docNoGroup);+ } else {+ writer.addDocument(doc);+ }+ }++ DirectoryReader reader = writer.getReader();+ writer.close();++ return new IndexContext(+ searchTermToFacetToGroups,+ reader,+ numDocs,+ dir,+ facetWithMostGroups,+ numGroups,+ contentBrs,+ uniqueFacetValues);+ }++ private ExpectedFacetResult createExpectedFacetResult(+ String searchTerm,+ IndexContext context,+ int offset,+ int limit,+ int minCount,+ final boolean orderByCount,+ String facetPrefix) {+ Map<String, Set<String>> facetGroups = context.searchTermToFacetGroups.get(searchTerm);+ if (facetGroups == null) {+ facetGroups = new HashMap<>();+ }++ int totalCount = 0;+ int totalMissCount = 0;+ Set<String> facetValues;+ if (facetPrefix != null) {+ facetValues = new HashSet<>();+ for (String facetValue : context.facetValues) {+ if (facetValue != null && facetValue.startsWith(facetPrefix)) {+ facetValues.add(facetValue);+ }+ }+ } else {+ facetValues = context.facetValues;+ }++ List<GroupedFacetResult.FacetEntry> entries = new ArrayList<>(facetGroups.size());+ // also includes facets with count 0+ for (String facetValue : facetValues) {+ if (facetValue == null) {+ continue;+ }++ Set<String> groups = facetGroups.get(facetValue);+ int count = groups != null ? groups.size() : 0;+ if (count >= minCount) {+ entries.add(new GroupedFacetResult.FacetEntry(new BytesRef(facetValue), count));+ }+ totalCount += count;+ }++ // Only include null count when no facet prefix is specified+ if (facetPrefix == null) {+ Set<String> groups = facetGroups.get(null);+ if (groups != null) {+ totalMissCount = groups.size();+ }+ }++ entries.sort(+ (a, b) -> {+ if (orderByCount) {+ int cmp = b.count() - a.count();+ if (cmp != 0) {+ return cmp;+ }+ }+ return a.value().compareTo(b.value());+ });++ int endOffset = offset + limit;+ List<GroupedFacetResult.FacetEntry> entriesResult;+ if (offset >= entries.size()) {+ entriesResult = Collections.emptyList();+ } else if (endOffset >= entries.size()) {+ entriesResult = entries.subList(offset, entries.size());+ } else {+ entriesResult = entries.subList(offset, endOffset);+ }+ return new ExpectedFacetResult(totalCount, totalMissCount, entriesResult);+ }++ private TermGroupFacetCollectorManager createRandomCollectorManager(+ String groupField,+ String facetField,+ String facetPrefix,+ boolean multipleFacetsPerDocument,+ int size,+ int minCount,+ boolean orderByCount) {+ BytesRef facetPrefixBR = facetPrefix == null ? null : new BytesRef(facetPrefix);+ return new TermGroupFacetCollectorManager(+ groupField,+ facetField,+ multipleFacetsPerDocument,+ facetPrefixBR,+ size,+ minCount,+ orderByCount);+ }++ private String getFromSet(Set<String> set, int index) {+ int currentIndex = 0;+ for (String bytesRef : set) {+ if (currentIndex++ == index) {+ return bytesRef;+ }+ }++ return null;+ }++ private static class IndexContext {++ final int numDocs;+ final DirectoryReader indexReader;+ final Map<String, Map<String, Set<String>>> searchTermToFacetGroups;+ final NavigableSet<String> facetValues;+ final Directory dir;+ final int facetWithMostGroups;+ final int numGroups;+ final String[] contentStrings;++ public IndexContext(+ Map<String, Map<String, Set<String>>> searchTermToFacetGroups,+ DirectoryReader r,+ int numDocs,+ Directory dir,+ int facetWithMostGroups,+ int numGroups,+ String[] contentStrings,+ NavigableSet<String> facetValues) {+ this.searchTermToFacetGroups = searchTermToFacetGroups;+ this.indexReader = r;+ this.numDocs = numDocs;+ this.dir = dir;+ this.facetWithMostGroups = facetWithMostGroups;+ this.numGroups = numGroups;+ this.contentStrings = contentStrings;+ this.facetValues = facetValues;+ }+ }++ private record ExpectedFacetResult(+ int totalCount, int totalMissingCount, List<GroupedFacetResult.FacetEntry> facetEntries) {}+}