You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@solr.apache.org by ds...@apache.org on 2026/08/02 20:55:16 UTC

(solr) branch branch_10x updated (a649775654a -> 783f3bc3930)

This is an automated email from the ASF dual-hosted git repository.

dsmiley pushed a change to branch branch_10x
in repository https://gitbox.apache.org/repos/asf/solr.git


    from a649775654a Tidy up java code in o.a.s.jersey package (#4658)
     new e61da9178be SolrRequest.getPath setPath documentation (#4665)
     new 2f62b8085d8 SOLR-18318: Fix NPE in GetNodeSystemInfo when nodes param is set (#4661)
     new 9b610b9a91d SOLR-18099: CollapseQParser extensibility (#4112)
     new 5747b366992 SOLR-18313: Prep for Lucene 11: use newer Lucene API forms (#4651)
     new aa862c4533f Avoid forwarding unrelated request parameters to Calcite from the /sql handler (#4607)
     new 1864907dd5e SOLR-18313: drop the changelog entry (#4682)
     new 14830a71a41 Extract CLIUtils.solrUrlFromConnection() from normalizeSolrUrl(CommandLine) (#4683)
     new 6125fb2d412 Tidy up java code in o.a.s.i.csv package (#4681)
     new f9882fc0650 Tidy up java code in o.a.s.common package (#4669)
     new ddba8752b8e SolrRequest.setPath fix; allow null (#4686)
     new 81e57446ce6 build: centralize maven repo declarations (#4677)
     new 9ad63cc534c Simplify SolrRequest path usage: prefer ctor not setPath (#4689)
     new 783f3bc3930 SOLR-18183: Permit LockType.NONE for ephemeral directories (#4660)

The 13 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 build-tools/build-infra/build.gradle               |    4 +-
 .../build-infra/declare-repositories.gradle        |   42 +
 build-tools/build-infra/settings.gradle            |    4 +
 build-tools/missing-doclet/build.gradle            |    4 +-
 build-tools/missing-doclet/settings.gradle         |    4 +
 .../PR#4677-buildCentralizeRepoDeclaration.yml     |    8 +
 changelog/unreleased/Yashgoswami-SOLR-18318.yml    |   10 +
 changelog/unreleased/calcite-sql-params.yml        |    7 +
 gradle/documentation/markdown.gradle               |   26 +-
 gradle/globals.gradle                              |   13 +-
 gradle/testing/randomization.gradle                |    6 +-
 gradle/validation/git-status.gradle                |   15 +-
 gradle/validation/jar-checks.gradle                |    4 +-
 gradle/validation/rat-sources.gradle               |    4 +-
 settings.gradle                                    |    5 +-
 .../solr/client/api/model/NodeSystemResponse.java  |    6 +-
 .../src/java/org/apache/solr/cli/CLIUtils.java     |   50 +-
 .../apache/solr/cloud/overseer/SliceMutator.java   |    4 +-
 .../solr/core/ByteBuffersDirectoryFactory.java     |    9 +-
 .../org/apache/solr/core/RAMDirectoryFactory.java  |    9 +-
 .../org/apache/solr/internal/csv/CSVParser.java    |   19 +-
 .../org/apache/solr/internal/csv/CSVPrinter.java   |   38 -
 .../org/apache/solr/internal/csv/CSVStrategy.java  |    8 +-
 .../org/apache/solr/internal/csv/CSVUtils.java     |   36 +-
 .../solr/internal/csv/ExtendedBufferedReader.java  |   20 +-
 .../java/org/apache/solr/logging/LogWatcher.java   |    4 +-
 .../org/apache/solr/logging/jul/JulWatcher.java    |    2 +-
 .../apache/solr/logging/log4j2/Log4j2Watcher.java  |    2 +-
 .../apache/solr/parser/SolrQueryParserBase.java    |    5 +-
 .../java/org/apache/solr/schema/EnumFieldType.java |   12 +-
 .../src/java/org/apache/solr/schema/FieldType.java |   37 +-
 .../src/java/org/apache/solr/search/BitDocSet.java |    3 +-
 .../solr/search/CollapsingQParserPlugin.java       | 4141 +++++++++-----------
 .../src/java/org/apache/solr/util/DynamicMap.java  |    3 +
 .../org/apache/solr/util/IntFloatDynamicMap.java   |   19 +-
 .../org/apache/solr/util/IntIntDynamicMap.java     |   19 +-
 .../org/apache/solr/util/IntLongDynamicMap.java    |   19 +-
 .../solr/configsets/zipfs/conf/solrconfig.xml      |    2 +-
 .../apache/solr/cloud/BasicDistributedZkTest.java  |    7 +-
 .../apache/solr/cloud/MultiThreadedOCPTest.java    |    8 +-
 .../org/apache/solr/cloud/SSLMigrationTest.java    |    8 +-
 .../TestCloudPhrasesIdentificationComponent.java   |    6 +-
 .../solr/cloud/TestGracefulJettyShutdown.java      |    3 +-
 .../solr/cloud/api/collections/ShardSplitTest.java |    8 +-
 .../TestRequestStatusCollectionAPI.java            |    8 +-
 .../solr/core/ByteBuffersDirectoryFactoryTest.java |    6 +
 .../apache/solr/core/RAMDirectoryFactoryTest.java  |    6 +
 .../admin/api/GetNodeSystemInfoSolrCloudTest.java} |   29 +-
 .../org/apache/solr/response/JSONWriterTest.java   |    3 +-
 .../solr/response/TestErrorResponseStackTrace.java |    4 +-
 .../apache/solr/schema/TestCloudManagedSchema.java |    7 +-
 .../solr/search/TestCollapseQParserPlugin.java     |   16 +-
 .../search/TestRandomCollapseQParserPlugin.java    |    5 +-
 .../org/apache/solr/search/TestSmileRequest.java   |    4 -
 .../apache/solr/update/UuidAtomicUpdateTest.java   |    3 +-
 .../update/processor/AtomicUpdateJavabinTest.java  |    3 +-
 solr/docker/build.gradle                           |    8 +-
 .../solr/ltr/TestLTRReRankCutoffOnSolrCloud.java   |    9 +-
 .../org/apache/solr/handler/sql/SQLHandler.java    |   45 +-
 .../apache/solr/handler/sql/TestSQLHandler.java    |   67 +
 .../configuration-guide/pages/solr-properties.adoc |    2 +
 .../TermComponentRefGuideExamplesTest.java         |    3 +-
 .../pages/collapse-and-expand-results.adoc         |   17 +-
 .../client/solrj/io/stream/JSONTupleStream.java    |   11 +-
 .../solr/client/solrj/io/stream/SolrStream.java    |   23 +-
 .../client/solrj/io/graph/GraphExpressionTest.java |    3 +-
 .../solr/common/cloud/SecurityNodeWatcher.java     |    6 +-
 .../org/apache/solr/client/solrj/SolrRequest.java  |   16 +-
 .../solr/client/solrj/request/UpdateRequest.java   |    7 +-
 .../src/java/org/apache/solr/common/Callable.java  |   21 -
 .../solr/common/ConditionalKeyMapWriter.java       |    5 -
 .../apache/solr/common/ConditionalMapWriter.java   |   84 -
 .../apache/solr/common/LinkedHashMapWriter.java    |   11 -
 .../src/java/org/apache/solr/common/MapWriter.java |    4 -
 .../org/apache/solr/common/NavigableObject.java    |    9 -
 .../org/apache/solr/common/SolrDocumentList.java   |    2 +-
 .../java/org/apache/solr/common/SolrException.java |   44 +-
 .../apache/solr/common/ToleratedUpdateError.java   |    6 +-
 .../java/org/apache/solr/common/cloud/Aliases.java |    2 +-
 .../solr/common/cloud/CompositeIdRouter.java       |    6 +-
 .../apache/solr/common/cloud/HashBasedRouter.java  |    6 +-
 .../apache/solr/common/cloud/PerReplicaStates.java |    6 +-
 .../org/apache/solr/common/cloud/RoutingRule.java  |    2 +-
 .../java/org/apache/solr/common/cloud/Slice.java   |    2 +-
 .../apache/solr/common/params/AnalysisParams.java  |   14 +-
 .../apache/solr/common/params/CommonParams.java    |    4 -
 .../apache/solr/common/params/ConfigSetParams.java |   10 +-
 .../solr/common/params/CursorMarkParams.java       |    6 +-
 .../apache/solr/common/params/DisMaxParams.java    |   31 +-
 .../org/apache/solr/common/params/EventParams.java |    6 +-
 .../apache/solr/common/params/ExpandParams.java    |   14 +-
 .../org/apache/solr/common/params/FacetParams.java |  118 +-
 .../org/apache/solr/common/params/GroupParams.java |   32 +-
 .../apache/solr/common/params/HighlightParams.java |  117 +-
 .../solr/common/params/MoreLikeThisParams.java     |   39 +-
 .../apache/solr/common/params/SimpleParams.java    |   24 +-
 .../org/apache/solr/common/params/SolrParams.java  |   20 -
 .../apache/solr/common/params/SpatialParams.java   |   12 +-
 .../apache/solr/common/params/SpellingParams.java  |   46 +-
 .../org/apache/solr/common/params/StatsParams.java |    8 +-
 .../solr/common/params/TermVectorParams.java       |   20 +-
 .../org/apache/solr/common/params/TermsParams.java |   30 +-
 .../apache/solr/common/params/UpdateParams.java    |   34 +-
 .../common/util/ByteArrayUtf8CharSequence.java     |   12 +-
 .../org/apache/solr/common/util/ByteUtils.java     |   19 +-
 .../apache/solr/common/util/CommandOperation.java  |   20 +-
 .../solr/common/util/CommonTestInjection.java      |   11 -
 .../apache/solr/common/util/ContentStreamBase.java |    4 -
 .../java/org/apache/solr/common/util/DOMUtil.java  |  119 -
 .../solr/common/util/DataInputInputStream.java     |    3 +-
 .../org/apache/solr/common/util/ExecutorUtil.java  |   18 -
 .../solr/common/util/FastJavaBinDecoder.java       |   14 +-
 .../apache/solr/common/util/FastOutputStream.java  |    4 +-
 .../org/apache/solr/common/util/FastWriter.java    |    2 +-
 .../apache/solr/common/util/GlobPatternUtil.java   |    4 +-
 .../org/apache/solr/common/util/JavaBinCodec.java  |   10 +-
 .../apache/solr/common/util/JsonRecordReader.java  |   29 +-
 .../solr/common/util/JsonSchemaValidator.java      |    1 -
 .../apache/solr/common/util/JsonTextWriter.java    |   76 +-
 .../org/apache/solr/common/util/NamedList.java     |    2 +-
 .../solr/common/util/ObjectReleaseTracker.java     |   11 -
 .../java/org/apache/solr/common/util/PathTrie.java |    2 -
 .../apache/solr/common/util/PropertiesUtil.java    |   19 -
 .../java/org/apache/solr/common/util/Template.java |   61 -
 .../java/org/apache/solr/common/util/URLUtil.java  |    2 +-
 .../java/org/apache/solr/common/util/Utils.java    |   43 -
 .../src/java/org/apache/solr/common/util/XML.java  |   40 +-
 .../apache/solr/client/solrj/SolrExampleTests.java |    3 +-
 .../solr/client/solrj/request/TestCoreAdmin.java   |    6 +-
 .../src/java/org/apache/solr/SolrTestCaseHS.java   |    5 -
 .../solr/cloud/AbstractFullDistribZkTestBase.java  |    1 -
 solr/ui/build.gradle.kts                           |    3 +-
 132 files changed, 2615 insertions(+), 3698 deletions(-)
 create mode 100644 build-tools/build-infra/declare-repositories.gradle
 create mode 100644 changelog/unreleased/PR#4677-buildCentralizeRepoDeclaration.yml
 create mode 100644 changelog/unreleased/Yashgoswami-SOLR-18318.yml
 create mode 100644 changelog/unreleased/calcite-sql-params.yml
 copy solr/core/src/test/org/apache/solr/{cloud/TestExclusionRuleCollectionAccess.java => handler/admin/api/GetNodeSystemInfoSolrCloudTest.java} (56%)
 delete mode 100644 solr/solrj/src/java/org/apache/solr/common/Callable.java
 delete mode 100644 solr/solrj/src/java/org/apache/solr/common/ConditionalMapWriter.java
 delete mode 100644 solr/solrj/src/java/org/apache/solr/common/util/Template.java


(solr) 13/13: SOLR-18183: Permit LockType.NONE for ephemeral directories (#4660)

Posted by ds...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

dsmiley pushed a commit to branch branch_10x
in repository https://gitbox.apache.org/repos/asf/solr.git

commit 783f3bc393055c476d4ceb3995412a3868fcfca6
Author: Surya Shukla <su...@zomato.com>
AuthorDate: Sat Aug 1 22:21:30 2026 +0530

    SOLR-18183: Permit LockType.NONE for ephemeral directories (#4660)
    
    (cherry picked from commit 8fa14f1048f00decc7ade6fede1350a862e97d7e)
---
 .../java/org/apache/solr/core/ByteBuffersDirectoryFactory.java   | 9 ++++++++-
 solr/core/src/java/org/apache/solr/core/RAMDirectoryFactory.java | 9 ++++++++-
 .../src/test-files/solr/configsets/zipfs/conf/solrconfig.xml     | 2 +-
 .../org/apache/solr/core/ByteBuffersDirectoryFactoryTest.java    | 6 ++++++
 .../src/test/org/apache/solr/core/RAMDirectoryFactoryTest.java   | 6 ++++++
 5 files changed, 29 insertions(+), 3 deletions(-)

diff --git a/solr/core/src/java/org/apache/solr/core/ByteBuffersDirectoryFactory.java b/solr/core/src/java/org/apache/solr/core/ByteBuffersDirectoryFactory.java
index aeed5d589f4..aab134a266e 100644
--- a/solr/core/src/java/org/apache/solr/core/ByteBuffersDirectoryFactory.java
+++ b/solr/core/src/java/org/apache/solr/core/ByteBuffersDirectoryFactory.java
@@ -20,6 +20,7 @@ import java.io.IOException;
 import org.apache.lucene.store.ByteBuffersDirectory;
 import org.apache.lucene.store.Directory;
 import org.apache.lucene.store.LockFactory;
+import org.apache.lucene.store.NoLockFactory;
 import org.apache.lucene.store.SingleInstanceLockFactory;
 import org.apache.solr.common.SolrException;
 import org.apache.solr.common.SolrException.ErrorCode;
@@ -29,13 +30,19 @@ public class ByteBuffersDirectoryFactory extends EphemeralDirectoryFactory {
 
   @Override
   protected LockFactory createLockFactory(String rawLockType) throws IOException {
+    if (rawLockType != null
+        && DirectoryFactory.LOCK_TYPE_NONE.equalsIgnoreCase(rawLockType.trim())) {
+      return NoLockFactory.INSTANCE;
+    }
     if (!(rawLockType == null
         || DirectoryFactory.LOCK_TYPE_SINGLE.equalsIgnoreCase(rawLockType.trim()))) {
       throw new SolrException(
           ErrorCode.FORBIDDEN,
           "ByteBuffersDirectory can only be used with the '"
               + DirectoryFactory.LOCK_TYPE_SINGLE
-              + "' lock factory type.");
+              + "' or '"
+              + DirectoryFactory.LOCK_TYPE_NONE
+              + "' lock factory types.");
     }
     return new SingleInstanceLockFactory();
   }
diff --git a/solr/core/src/java/org/apache/solr/core/RAMDirectoryFactory.java b/solr/core/src/java/org/apache/solr/core/RAMDirectoryFactory.java
index 052dc0106f1..9b171806280 100644
--- a/solr/core/src/java/org/apache/solr/core/RAMDirectoryFactory.java
+++ b/solr/core/src/java/org/apache/solr/core/RAMDirectoryFactory.java
@@ -20,6 +20,7 @@ import java.io.IOException;
 import org.apache.lucene.store.ByteBuffersDirectory;
 import org.apache.lucene.store.Directory;
 import org.apache.lucene.store.LockFactory;
+import org.apache.lucene.store.NoLockFactory;
 import org.apache.lucene.store.SingleInstanceLockFactory;
 import org.apache.solr.common.SolrException;
 import org.apache.solr.common.SolrException.ErrorCode;
@@ -29,13 +30,19 @@ public class RAMDirectoryFactory extends EphemeralDirectoryFactory {
 
   @Override
   protected LockFactory createLockFactory(String rawLockType) throws IOException {
+    if (rawLockType != null
+        && DirectoryFactory.LOCK_TYPE_NONE.equalsIgnoreCase(rawLockType.trim())) {
+      return NoLockFactory.INSTANCE;
+    }
     if (!(rawLockType == null
         || DirectoryFactory.LOCK_TYPE_SINGLE.equalsIgnoreCase(rawLockType.trim()))) {
       throw new SolrException(
           ErrorCode.FORBIDDEN,
           "RAMDirectory can only be used with the '"
               + DirectoryFactory.LOCK_TYPE_SINGLE
-              + "' lock factory type.");
+              + "' or '"
+              + DirectoryFactory.LOCK_TYPE_NONE
+              + "' lock factory types.");
     }
     return new SingleInstanceLockFactory();
   }
diff --git a/solr/core/src/test-files/solr/configsets/zipfs/conf/solrconfig.xml b/solr/core/src/test-files/solr/configsets/zipfs/conf/solrconfig.xml
index 1beded14516..b16b37fd10c 100644
--- a/solr/core/src/test-files/solr/configsets/zipfs/conf/solrconfig.xml
+++ b/solr/core/src/test-files/solr/configsets/zipfs/conf/solrconfig.xml
@@ -23,7 +23,7 @@
 
   <directoryFactory class="solr.RAMDirectoryFactory"/>
   <indexConfig>
-    <lockType>single</lockType>
+    <lockType>none</lockType>
   </indexConfig>
 
   <schemaFactory class="ClassicIndexSchemaFactory"/>
diff --git a/solr/core/src/test/org/apache/solr/core/ByteBuffersDirectoryFactoryTest.java b/solr/core/src/test/org/apache/solr/core/ByteBuffersDirectoryFactoryTest.java
index ba3c04ab6df..1c72b2fa48c 100644
--- a/solr/core/src/test/org/apache/solr/core/ByteBuffersDirectoryFactoryTest.java
+++ b/solr/core/src/test/org/apache/solr/core/ByteBuffersDirectoryFactoryTest.java
@@ -20,12 +20,18 @@ import java.io.IOException;
 import org.apache.lucene.store.ByteBuffersDirectory;
 import org.apache.lucene.store.Directory;
 import org.apache.lucene.store.LockFactory;
+import org.apache.lucene.store.NoLockFactory;
 import org.apache.solr.SolrTestCaseJ4;
 import org.apache.solr.core.DirectoryFactory.DirContext;
 
 /** Test-case for ByteBuffersDirectoryFactory */
 public class ByteBuffersDirectoryFactoryTest extends SolrTestCaseJ4 {
 
+  public void testLockTypeNone() throws IOException {
+    ByteBuffersDirectoryFactory factory = new ByteBuffersDirectoryFactory();
+    assertSame(NoLockFactory.INSTANCE, factory.createLockFactory(DirectoryFactory.LOCK_TYPE_NONE));
+  }
+
   public void testOpenReturnsTheSameForSamePath() throws IOException {
     final Directory directory = new ByteBuffersDirectory();
     ByteBuffersDirectoryFactory factory =
diff --git a/solr/core/src/test/org/apache/solr/core/RAMDirectoryFactoryTest.java b/solr/core/src/test/org/apache/solr/core/RAMDirectoryFactoryTest.java
index c0c418f8f82..70543e824e7 100644
--- a/solr/core/src/test/org/apache/solr/core/RAMDirectoryFactoryTest.java
+++ b/solr/core/src/test/org/apache/solr/core/RAMDirectoryFactoryTest.java
@@ -20,6 +20,7 @@ import java.io.IOException;
 import org.apache.lucene.store.ByteBuffersDirectory;
 import org.apache.lucene.store.Directory;
 import org.apache.lucene.store.LockFactory;
+import org.apache.lucene.store.NoLockFactory;
 import org.apache.solr.SolrTestCase;
 import org.apache.solr.core.DirectoryFactory.DirContext;
 
@@ -31,6 +32,11 @@ public class RAMDirectoryFactoryTest extends SolrTestCase {
     dotestOpenSucceedForEmptyDir();
   }
 
+  public void testLockTypeNone() throws IOException {
+    RAMDirectoryFactory factory = new RAMDirectoryFactory();
+    assertSame(NoLockFactory.INSTANCE, factory.createLockFactory(DirectoryFactory.LOCK_TYPE_NONE));
+  }
+
   private void dotestOpenReturnsTheSameForSamePath() throws IOException {
     final Directory directory = new ByteBuffersDirectory();
     RAMDirectoryFactory factory =


(solr) 05/13: Avoid forwarding unrelated request parameters to Calcite from the /sql handler (#4607)

Posted by ds...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

dsmiley pushed a commit to branch branch_10x
in repository https://gitbox.apache.org/repos/asf/solr.git

commit aa862c4533fba8c724f2049b750f53dc59c47022
Author: Jan Høydahl <ja...@apache.org>
AuthorDate: Thu Jul 30 14:15:02 2026 +0200

    Avoid forwarding unrelated request parameters to Calcite from the /sql handler (#4607)
    
    (cherry picked from commit 34eb9e3c998b6835969f12d75379607aea9220a2)
---
 changelog/unreleased/calcite-sql-params.yml        |  7 +++
 .../org/apache/solr/handler/sql/SQLHandler.java    | 45 +++++++++++----
 .../apache/solr/handler/sql/TestSQLHandler.java    | 67 ++++++++++++++++++++++
 .../configuration-guide/pages/solr-properties.adoc |  2 +
 4 files changed, 111 insertions(+), 10 deletions(-)

diff --git a/changelog/unreleased/calcite-sql-params.yml b/changelog/unreleased/calcite-sql-params.yml
new file mode 100644
index 00000000000..a178dbe6488
--- /dev/null
+++ b/changelog/unreleased/calcite-sql-params.yml
@@ -0,0 +1,7 @@
+title: The /sql handler request params forwarded to Calcite is now configurable
+type: changed
+authors:
+  - name: Jan Høydahl
+links:
+  - name: PR#4607
+    url: https://github.com/apache/solr/pull/4607
diff --git a/solr/modules/sql/src/java/org/apache/solr/handler/sql/SQLHandler.java b/solr/modules/sql/src/java/org/apache/solr/handler/sql/SQLHandler.java
index 1f3cfe6b05d..1aa7ace83ef 100644
--- a/solr/modules/sql/src/java/org/apache/solr/handler/sql/SQLHandler.java
+++ b/solr/modules/sql/src/java/org/apache/solr/handler/sql/SQLHandler.java
@@ -22,10 +22,10 @@ import java.sql.ResultSetMetaData;
 import java.sql.SQLException;
 import java.util.ArrayList;
 import java.util.HashMap;
-import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
 import java.util.Properties;
+import java.util.Set;
 import org.apache.calcite.config.Lex;
 import org.apache.solr.client.solrj.io.Tuple;
 import org.apache.solr.client.solrj.io.comp.StreamComparator;
@@ -34,6 +34,7 @@ import org.apache.solr.client.solrj.io.stream.TupleStream;
 import org.apache.solr.common.params.CommonParams;
 import org.apache.solr.common.params.ModifiableSolrParams;
 import org.apache.solr.common.params.SolrParams;
+import org.apache.solr.common.util.EnvUtils;
 import org.apache.solr.core.CoreContainer;
 import org.apache.solr.core.SolrCore;
 import org.apache.solr.handler.RequestHandlerBase;
@@ -52,10 +53,27 @@ public class SQLHandler extends RequestHandlerBase
   private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
 
   private static String defaultZkhost = null;
-  private static String defaultWorkerCollection = null;
 
   static final String sqlNonCloudErrorMsg = "/sql handler only works in Solr Cloud mode";
 
+  /** System property to override the set of request parameters forwarded to Calcite. */
+  static final String ALLOWED_CONNECTION_PARAMS_PROP = "solr.sql.connection.params.allowed";
+
+  /** Calcite configuration parameters forwarded as connection properties. */
+  static final Set<String> DEFAULT_CONNECTION_PARAMS =
+      Set.of(
+          "caseSensitive",
+          "quoting",
+          "quotedCasing",
+          "unquotedCasing",
+          "conformance",
+          "fun",
+          "typeCoercion",
+          "lenientOperatorLookup",
+          "defaultNullCollation",
+          "timeZone",
+          "locale");
+
   private boolean isCloud = false;
 
   @Override
@@ -64,7 +82,6 @@ public class SQLHandler extends RequestHandlerBase
 
     if (coreContainer.isZooKeeperAware()) {
       defaultZkhost = coreContainer.getZkController().getZkServerAddress();
-      defaultWorkerCollection = core.getCoreDescriptor().getCollectionName();
       isCloud = true;
     }
 
@@ -85,8 +102,6 @@ public class SQLHandler extends RequestHandlerBase
     String sql = params.get("stmt");
     // Set defaults for parameters
     params.set("numWorkers", params.getInt("numWorkers", 1));
-    params.set("workerCollection", params.get("workerCollection", defaultWorkerCollection));
-    params.set("workerZkhost", params.get("workerZkhost", defaultZkhost));
     params.set("aggregationMode", params.get("aggregationMode", "facet"));
 
     TupleStream tupleStream = null;
@@ -103,13 +118,18 @@ public class SQLHandler extends RequestHandlerBase
       String url = CalciteSolrDriver.CONNECT_STRING_PREFIX;
 
       Properties properties = new Properties();
-      // Add all query parameters
-      Iterator<String> parameterNamesIterator = params.getParameterNamesIterator();
-      while (parameterNamesIterator.hasNext()) {
-        String param = parameterNamesIterator.next();
-        properties.setProperty(param, params.get(param));
+      // Forward only the configured Calcite configuration parameters
+      for (String param : allowedConnectionParams()) {
+        String value = params.get(param);
+        if (value != null) {
+          properties.setProperty(param, value);
+        }
       }
 
+      // Solr-specific parameters
+      properties.setProperty("aggregationMode", params.get("aggregationMode"));
+      properties.setProperty("numWorkers", params.get("numWorkers"));
+
       // Set these last to ensure that they are set properly
       properties.setProperty("lex", Lex.MYSQL.toString());
       properties.setProperty("zk", defaultZkhost);
@@ -203,6 +223,11 @@ public class SQLHandler extends RequestHandlerBase
     }
   }
 
+  static Set<String> allowedConnectionParams() {
+    List<String> override = EnvUtils.getPropertyAsList(ALLOWED_CONNECTION_PARAMS_PROP);
+    return override != null ? Set.copyOf(override) : DEFAULT_CONNECTION_PARAMS;
+  }
+
   private ModifiableSolrParams adjustParams(SolrParams params) {
     ModifiableSolrParams adjustedParams = new ModifiableSolrParams();
     adjustedParams.add(params);
diff --git a/solr/modules/sql/src/test/org/apache/solr/handler/sql/TestSQLHandler.java b/solr/modules/sql/src/test/org/apache/solr/handler/sql/TestSQLHandler.java
index 94e997998ea..6ababeb539a 100644
--- a/solr/modules/sql/src/test/org/apache/solr/handler/sql/TestSQLHandler.java
+++ b/solr/modules/sql/src/test/org/apache/solr/handler/sql/TestSQLHandler.java
@@ -452,6 +452,73 @@ public class TestSQLHandler extends SolrCloudTestCase {
     tuples = getTuples(sParams, baseUrl);
 
     assertEquals(0, tuples.size());
+
+    // Verify that request parameters not on the allowlist are not forwarded to Calcite.
+    // 'schemaType' is a real Calcite connection property which would crash the request
+    sParams =
+        params(
+            CommonParams.QT,
+            "/sql",
+            "schemaType",
+            "someValue",
+            "stmt",
+            "select id, field_i, str_s from collection1 where text_t='XXXX' order by field_i desc limit 1");
+
+    tuples = getTuples(sParams, baseUrl);
+
+    assertEquals(1, tuples.size());
+    tuple = tuples.get(0);
+    assertEquals(8, tuple.getLong("id").longValue());
+    assertEquals(60, tuple.getLong("field_i").longValue());
+    assertEquals("c", tuple.get("str_s"));
+
+    // Sanity check: with 'schemaType' added to the allowlist it IS forwarded, and the same
+    // request now fails on the invalid value, proving the allowlist controls forwarding
+    System.setProperty(SQLHandler.ALLOWED_CONNECTION_PARAMS_PROP, "schemaType");
+    try {
+      final SolrParams forwardedParams = sParams;
+      IOException e = expectThrows(IOException.class, () -> getTuples(forwardedParams, baseUrl));
+      assertTrue(e.getMessage().contains("not valid"));
+    } finally {
+      System.clearProperty(SQLHandler.ALLOWED_CONNECTION_PARAMS_PROP);
+    }
+  }
+
+  @Test
+  public void testConnectionParamsAllowlistOverride() throws Exception {
+
+    new UpdateRequest()
+        .add("id", "1", "text_t", "XXXX XXXX", "str_s", "a", "field_i", "7")
+        .commit(cluster.getSolrClient(), COLLECTIONORALIAS);
+
+    String baseUrl =
+        cluster.getJettySolrRunners().get(0).getBaseUrl().toString() + "/" + COLLECTIONORALIAS;
+
+    SolrParams sParams =
+        params(
+            CommonParams.QT,
+            "/sql",
+            "caseSensitive",
+            "true",
+            "stmt",
+            "select id, FIELD_I from collection1 limit 1");
+
+    // caseSensitive is forwarded to Calcite by default, making column names case-sensitive,
+    // unlike the default MySQL dialect behavior
+    SolrStream solrStream = new SolrStream(baseUrl, sParams);
+    Tuple tuple = getTuple(new ExceptionStream(solrStream));
+    assertTrue(tuple.EOF);
+    assertTrue(tuple.EXCEPTION);
+    assertTrue(tuple.getException().contains("Column 'FIELD_I' not found"));
+
+    // Restrict the allowlist so that caseSensitive is no longer forwarded and the same query
+    // succeeds with case-insensitive column resolution
+    System.setProperty(SQLHandler.ALLOWED_CONNECTION_PARAMS_PROP, "");
+    try {
+      assertEquals(1, getTuples(sParams, baseUrl).size());
+    } finally {
+      System.clearProperty(SQLHandler.ALLOWED_CONNECTION_PARAMS_PROP);
+    }
   }
 
   @Test
diff --git a/solr/solr-ref-guide/modules/configuration-guide/pages/solr-properties.adoc b/solr/solr-ref-guide/modules/configuration-guide/pages/solr-properties.adoc
index b9ecaddb100..20fbfc09fb3 100644
--- a/solr/solr-ref-guide/modules/configuration-guide/pages/solr-properties.adoc
+++ b/solr/solr-ref-guide/modules/configuration-guide/pages/solr-properties.adoc
@@ -110,6 +110,8 @@ NOTE: Properties marked with "!" indicate inverted meaning between pre Solr 10 a
 
 |solr.solrj.http.jetty.customizer|solr.httpclient.builder.factory||A class loaded to customize HttpJettySolrClient upon creation.
 
+|solr.sql.connection.params.allowed||caseSensitive, quoting, quotedCasing, unquotedCasing, conformance, fun,typeCoercion, lenientOperatorLookup, defaultNullCollation, timeZone, locale|A comma separated list of request parameters to forward to Apache Calcite as connection properties.
+
 |solr.streamingexpressions.facet.tiered.enabled|solr.facet.stream.tiered|true|Controls whether tiered faceting is enabled for streaming expressions.
 
 |solr.streamingexpressions.macros.enabled|StreamingExpressionMacros|false|Controls whether to expand URL parameters inside of the `expr` parameter.


(solr) 08/13: Tidy up java code in o.a.s.i.csv package (#4681)

Posted by ds...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

dsmiley pushed a commit to branch branch_10x
in repository https://gitbox.apache.org/repos/asf/solr.git

commit 6125fb2d412d98614bd3f12d39080a46c759eabc
Author: Eric Pugh <ep...@opensourceconnections.com>
AuthorDate: Fri Jul 31 20:02:38 2026 -0400

    Tidy up java code in o.a.s.i.csv package (#4681)
    
    (cherry picked from commit c9ed84e97864f19cc0f80a80100648855e527752)
---
 .../org/apache/solr/internal/csv/CSVParser.java    | 19 ++++-------
 .../org/apache/solr/internal/csv/CSVPrinter.java   | 38 ----------------------
 .../org/apache/solr/internal/csv/CSVStrategy.java  |  8 ++---
 .../org/apache/solr/internal/csv/CSVUtils.java     | 36 +-------------------
 .../solr/internal/csv/ExtendedBufferedReader.java  | 20 ++++++------
 .../java/org/apache/solr/logging/LogWatcher.java   |  4 +--
 .../org/apache/solr/logging/jul/JulWatcher.java    |  2 +-
 .../apache/solr/logging/log4j2/Log4j2Watcher.java  |  2 +-
 8 files changed, 24 insertions(+), 105 deletions(-)

diff --git a/solr/core/src/java/org/apache/solr/internal/csv/CSVParser.java b/solr/core/src/java/org/apache/solr/internal/csv/CSVParser.java
index a5495a31106..3f22e6aefe5 100644
--- a/solr/core/src/java/org/apache/solr/internal/csv/CSVParser.java
+++ b/solr/core/src/java/org/apache/solr/internal/csv/CSVParser.java
@@ -254,14 +254,14 @@ public class CSVParser {
    * @throws IOException on stream access error
    */
   protected Token nextToken(Token tkn) throws IOException {
-    wsBuf.clear(); // resuse
+    wsBuf.clear(); // reuse
 
     // get the last read char (required for empty line detection)
     int lastChar = in.readAgain();
 
     //  read the next char and set eol
-    /* note: unfortunately isEndOfLine may consumes a character silently.
-     *       this has no effect outside of the method. so a simple workaround
+    /* note: unfortunately isEndOfLine may consume a character silently.
+     *       this has no effect outside the method. so a simple workaround
      *       is to call 'readAgain' on the stream...
      *       uh: might using objects instead of base-types (jdk1.5 autoboxing!)
      */
@@ -286,7 +286,7 @@ public class CSVParser {
       }
     }
 
-    // did we reached eof during the last iteration already ? TT_EOF
+    // did we reach eof during the last iteration already ? TT_EOF
     if (isEndOfFile(lastChar) || (lastChar != strategy.getDelimiter() && isEndOfFile(c))) {
       tkn.type = TT_EOF;
       return tkn;
@@ -302,7 +302,7 @@ public class CSVParser {
       }
       // ok, start of token reached: comment, encapsulated, or token
       if (c == strategy.getCommentStart()) {
-        // ignore everything till end of line and continue (incr linecount)
+        // ignore everything till end of line and continue (increment line count)
         in.readLine();
         tkn = nextToken(tkn.reset());
       } else if (c == strategy.getDelimiter()) {
@@ -464,7 +464,7 @@ public class CSVParser {
    *
    * @param c current char which is discarded because it's the "\\" of "\\uXXXX"
    * @return the decoded character
-   * @throws IOException on wrong unicode escape sequence or read error
+   * @throws IOException on wrong Unicode escape sequence or read error
    */
   protected int unicodeEscapeLexer(int c) throws IOException {
     int ret = 0;
@@ -482,12 +482,7 @@ public class CSVParser {
       ret = Integer.parseInt(code.toString(), 16);
     } catch (NumberFormatException e) {
       throw new IOException(
-          "(line "
-              + getLineNumber()
-              + ") Wrong unicode escape sequence found '"
-              + code.toString()
-              + "'"
-              + e.toString());
+          "(line " + getLineNumber() + ") Wrong unicode escape sequence found '" + code + "'" + e);
     }
     return ret;
   }
diff --git a/solr/core/src/java/org/apache/solr/internal/csv/CSVPrinter.java b/solr/core/src/java/org/apache/solr/internal/csv/CSVPrinter.java
index e759236a5c2..9e8c543a1ef 100644
--- a/solr/core/src/java/org/apache/solr/internal/csv/CSVPrinter.java
+++ b/solr/core/src/java/org/apache/solr/internal/csv/CSVPrinter.java
@@ -73,44 +73,6 @@ public class CSVPrinter {
     println();
   }
 
-  /**
-   * Put a comment among the comma separated values. Comments will always begin on a new line and
-   * occupy a least one full line. The character specified to star comments and a space will be
-   * inserted at the beginning of each new line in the comment.
-   *
-   * @param comment the comment to output
-   */
-  @SuppressWarnings({"fallthrough"})
-  public void printlnComment(String comment) throws IOException {
-    if (this.strategy.isCommentingDisabled()) {
-      return;
-    }
-    if (!newLine) {
-      println();
-    }
-    out.write(this.strategy.getCommentStart());
-    out.write(' ');
-    for (int i = 0; i < comment.length(); i++) {
-      char c = comment.charAt(i);
-      switch (c) {
-        case '\r':
-          if (i + 1 < comment.length() && comment.charAt(i + 1) == '\n') {
-            i++;
-          }
-        // break intentionally excluded.
-        case '\n':
-          println();
-          out.write(this.strategy.getCommentStart());
-          out.write(' ');
-          break;
-        default:
-          out.write(c);
-          break;
-      }
-    }
-    println();
-  }
-
   public void print(char[] value, int offset, int len, boolean checkForEscape) throws IOException {
     if (!checkForEscape) {
       printSep();
diff --git a/solr/core/src/java/org/apache/solr/internal/csv/CSVStrategy.java b/solr/core/src/java/org/apache/solr/internal/csv/CSVStrategy.java
index 98f2d6cbb58..c647bc6240c 100644
--- a/solr/core/src/java/org/apache/solr/internal/csv/CSVStrategy.java
+++ b/solr/core/src/java/org/apache/solr/internal/csv/CSVStrategy.java
@@ -102,8 +102,8 @@ public class CSVStrategy implements Cloneable, Serializable {
    * @param escape a Char used for escaping
    * @param ignoreTrailingWhitespaces TRUE when trailing whitespaces should be ignored
    * @param ignoreLeadingWhitespaces TRUE when leading whitespaces should be ignored
-   * @param interpretUnicodeEscapes TRUE when unicode escapes should be interpreted
-   * @param ignoreEmptyLines TRUE when the parser should skip emtpy lines
+   * @param interpretUnicodeEscapes TRUE when Unicode escapes should be interpreted
+   * @param ignoreEmptyLines TRUE when the parser should skip empty lines
    * @param printerNewline The string to use when printing a newline
    */
   public CSVStrategy(
@@ -139,10 +139,6 @@ public class CSVStrategy implements Cloneable, Serializable {
     return this.commentStart;
   }
 
-  public boolean isCommentingDisabled() {
-    return this.commentStart == COMMENTS_DISABLED;
-  }
-
   public char getEscape() {
     return this.escape;
   }
diff --git a/solr/core/src/java/org/apache/solr/internal/csv/CSVUtils.java b/solr/core/src/java/org/apache/solr/internal/csv/CSVUtils.java
index 8bb0ad3703a..76c7922bc9b 100644
--- a/solr/core/src/java/org/apache/solr/internal/csv/CSVUtils.java
+++ b/solr/core/src/java/org/apache/solr/internal/csv/CSVUtils.java
@@ -18,7 +18,6 @@ package org.apache.solr.internal.csv;
 
 import java.io.IOException;
 import java.io.StringReader;
-import java.io.StringWriter;
 
 /** Utility methods for dealing with CSV files */
 public class CSVUtils {
@@ -33,39 +32,6 @@ public class CSVUtils {
    */
   public CSVUtils() {}
 
-  /**
-   * Converts an array of string values into a single CSV line. All <code>null</code> values are
-   * converted to the string <code>"null"</code>, all strings equal to <code>"null"</code> will
-   * additionally get quotes around.
-   *
-   * @param values the value array
-   * @return the CSV string, will be an empty string if the length of the value array is 0
-   */
-  public static String printLine(String[] values, CSVStrategy strategy) {
-    // set up a CSVUtils
-    StringWriter stringWriter = new StringWriter();
-    CSVPrinter csvPrinter = new CSVPrinter(stringWriter, strategy);
-
-    // check for null values an "null" as strings and convert them
-    // into the strings "null" and "\"null\""
-    for (int i = 0; i < values.length; i++) {
-      if (values[i] == null) {
-        values[i] = "null";
-      } else if (values[i].equals("null")) {
-        values[i] = "\"null\"";
-      }
-    }
-
-    // convert to CSV
-    try {
-      csvPrinter.println(values);
-    } catch (IOException e) {
-      // should not happen with StringWriter
-    }
-    // as the resulting string has \r\n at the end, we will trim that away
-    return stringWriter.toString().trim();
-  }
-
   // ======================================================
   //  static parsers
   // ======================================================
@@ -105,7 +71,7 @@ public class CSVUtils {
       throw new IllegalArgumentException("Null argument not allowed.");
     }
     // uh,jh: make sure that parseLine("").length == 0
-    if (s.length() == 0) {
+    if (s.isEmpty()) {
       return EMPTY_STRING_ARRAY;
     }
     return (new CSVParser(new StringReader(s))).getLine();
diff --git a/solr/core/src/java/org/apache/solr/internal/csv/ExtendedBufferedReader.java b/solr/core/src/java/org/apache/solr/internal/csv/ExtendedBufferedReader.java
index fb7621490ea..fa9266256b9 100644
--- a/solr/core/src/java/org/apache/solr/internal/csv/ExtendedBufferedReader.java
+++ b/solr/core/src/java/org/apache/solr/internal/csv/ExtendedBufferedReader.java
@@ -23,11 +23,11 @@ import java.io.Reader;
 /**
  * ExtendedBufferedReader
  *
- * <p>A special reader decorater which supports more sophisticated access to the underlying reader
+ * <p>A special reader decorator which supports more sophisticated access to the underlying reader
  * object.
  *
  * <p>In particular the reader supports a look-ahead option, which allows you to see the next char
- * returned by next(). Furthermore the skip-method supports skipping until (but excluding) a given
+ * returned by next(). Furthermore, the skip-method supports skipping until (but excluding) a given
  * char. Similar functionality is supported by the reader as well.
  */
 class ExtendedBufferedReader extends BufferedReader {
@@ -98,7 +98,7 @@ class ExtendedBufferedReader extends BufferedReader {
   }
 
   /**
-   * Non-blocking reading of len chars into buffer buf starting at bufferposition off.
+   * Non-blocking reading of len chars into buffer buf starting at buffer position off.
    *
    * <p>performs an iterative read on the underlying stream as long as the following conditions
    * hold: - less than len chars have been read - end of stream has not been reached - next read is
@@ -215,7 +215,7 @@ class ExtendedBufferedReader extends BufferedReader {
    *
    * <p>ATTENTION: invalidates the line-counter !!!!!
    *
-   * @return nof skiped chars
+   * @return nof skipped chars
    */
   @Override
   public long skip(long n) throws IllegalArgumentException, IOException {
@@ -235,14 +235,14 @@ class ExtendedBufferedReader extends BufferedReader {
     }
 
     // skip and reread the lookahead-char
-    long skiped = 0;
+    long skipped = 0;
     if (n > 1) {
-      skiped = super.skip(n - 1);
+      skipped = super.skip(n - 1);
     }
     lookaheadChar = super.read();
-    // fixme uh: we should check the skiped sequence for line-terminations...
+    // fixme uh: we should check the skipped sequence for line-terminations...
     lineCounter = Integer.MIN_VALUE;
-    return skiped + 1;
+    return skipped + 1;
   }
 
   /**
@@ -269,7 +269,7 @@ class ExtendedBufferedReader extends BufferedReader {
   /**
    * Returns the next char in the stream without consuming it.
    *
-   * <p>Remember the next char read by read(..) will always be identical to lookAhead().
+   * <p>Remember the next char read by read() will always be identical to lookAhead().
    *
    * @return the next char (without consuming it) or END_OF_STREAM
    */
@@ -295,7 +295,7 @@ class ExtendedBufferedReader extends BufferedReader {
 
   @Override
   public boolean markSupported() {
-    /* note uh: marking is not supported, cause we cannot
+    /* note uh: marking is not supported, because we cannot
      *          see into the future...
      */
     return false;
diff --git a/solr/core/src/java/org/apache/solr/logging/LogWatcher.java b/solr/core/src/java/org/apache/solr/logging/LogWatcher.java
index 30f4f6e2755..c4cd3d763d1 100644
--- a/solr/core/src/java/org/apache/solr/logging/LogWatcher.java
+++ b/solr/core/src/java/org/apache/solr/logging/LogWatcher.java
@@ -68,9 +68,9 @@ public abstract class LogWatcher<E> {
 
   public abstract String getThreshold();
 
-  public void add(E event, long timstamp) {
+  public void add(E event, long timestamp) {
     history.add(unmodifiable(toSolrDocument(event)));
-    last = timstamp;
+    last = timestamp;
   }
 
   /**
diff --git a/solr/core/src/java/org/apache/solr/logging/jul/JulWatcher.java b/solr/core/src/java/org/apache/solr/logging/jul/JulWatcher.java
index 271e1358fd1..9cb3acc0b0c 100644
--- a/solr/core/src/java/org/apache/solr/logging/jul/JulWatcher.java
+++ b/solr/core/src/java/org/apache/solr/logging/jul/JulWatcher.java
@@ -150,7 +150,7 @@ public class JulWatcher extends LogWatcher<LogRecord> {
     doc.setField("time", new Date(event.getMillis()));
     doc.setField("level", event.getLevel().toString());
     doc.setField("logger", event.getLoggerName());
-    doc.setField("message", event.getMessage().toString());
+    doc.setField("message", event.getMessage());
     Throwable t = event.getThrown();
     if (t != null) {
       StringWriter trace = new StringWriter();
diff --git a/solr/core/src/java/org/apache/solr/logging/log4j2/Log4j2Watcher.java b/solr/core/src/java/org/apache/solr/logging/log4j2/Log4j2Watcher.java
index 9e266baa5ad..f8c2391085f 100644
--- a/solr/core/src/java/org/apache/solr/logging/log4j2/Log4j2Watcher.java
+++ b/solr/core/src/java/org/apache/solr/logging/log4j2/Log4j2Watcher.java
@@ -183,7 +183,7 @@ public class Log4j2Watcher extends LogWatcher<LogEvent> {
     LoggerConfig rootConfig = ctx.getConfiguration().getRootLogger();
     Map<String, LoggerInfo> map = new HashMap<>(ctx.getLoggers().size());
 
-    // First add the ROOT loger with the ROOT level
+    // First add the ROOT logger with the ROOT level
     map.put(
         LoggerInfo.ROOT_NAME,
         new Log4j2Info(


(solr) 01/13: SolrRequest.getPath setPath documentation (#4665)

Posted by ds...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

dsmiley pushed a commit to branch branch_10x
in repository https://gitbox.apache.org/repos/asf/solr.git

commit e61da9178be3c610b3cff865524beccf452e20fc
Author: David Smiley <ds...@apache.org>
AuthorDate: Wed Jul 29 00:26:53 2026 -0400

    SolrRequest.getPath setPath documentation (#4665)
    
    And path enforcement
    
    (cherry picked from commit 6c793d5534160d882882f2833496ae25c1f9016b)
---
 .../solrj/src/java/org/apache/solr/client/solrj/SolrRequest.java | 9 +++++++++
 1 file changed, 9 insertions(+)

diff --git a/solr/solrj/src/java/org/apache/solr/client/solrj/SolrRequest.java b/solr/solrj/src/java/org/apache/solr/client/solrj/SolrRequest.java
index 0f2b21b7f85..7574bd38967 100644
--- a/solr/solrj/src/java/org/apache/solr/client/solrj/SolrRequest.java
+++ b/solr/solrj/src/java/org/apache/solr/client/solrj/SolrRequest.java
@@ -172,11 +172,20 @@ public abstract class SolrRequest<T> implements Serializable {
     this.method = method;
   }
 
+  /**
+   * The URI path to a "request handler", such as "/select". Must start with a "/". For
+   * collection/core requests, this is appended to the core/collection path; otherwise it's a node
+   * level request and thus is relative to the solr root.
+   */
   public String getPath() {
     return path;
   }
 
   public void setPath(String path) {
+    if (path == null || !path.startsWith("/")) {
+      throw new IllegalArgumentException("Must start with a '/': " + path);
+    }
+
     this.path = path;
   }
 


(solr) 02/13: SOLR-18318: Fix NPE in GetNodeSystemInfo when nodes param is set (#4661)

Posted by ds...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

dsmiley pushed a commit to branch branch_10x
in repository https://gitbox.apache.org/repos/asf/solr.git

commit 2f62b8085d8752c8d65f03027dee378fe4d55067
Author: Yash Goswami <yg...@outlook.com>
AuthorDate: Wed Jul 29 21:19:50 2026 +0530

    SOLR-18318: Fix NPE in GetNodeSystemInfo when nodes param is set (#4661)
    
    (cherry picked from commit 84098343b6eccd6347941393e239a656ffa68a03)
---
 changelog/unreleased/Yashgoswami-SOLR-18318.yml    | 10 +++++
 .../solr/client/api/model/NodeSystemResponse.java  |  6 +--
 .../admin/api/GetNodeSystemInfoSolrCloudTest.java  | 48 ++++++++++++++++++++++
 3 files changed, 61 insertions(+), 3 deletions(-)

diff --git a/changelog/unreleased/Yashgoswami-SOLR-18318.yml b/changelog/unreleased/Yashgoswami-SOLR-18318.yml
new file mode 100644
index 00000000000..030b8c9e6ba
--- /dev/null
+++ b/changelog/unreleased/Yashgoswami-SOLR-18318.yml
@@ -0,0 +1,10 @@
+# See https://github.com/apache/solr/blob/main/dev-docs/changelog.adoc
+
+title: >
+  Fix NullPointerException in GetNodeSystemInfo when the nodes parameter is provided in SolrCloud mode
+type: fixed
+authors:
+  - name: Yash Goswami
+links:
+  - name: SOLR-18318
+    url: https://issues.apache.org/jira/browse/SOLR-18318
diff --git a/solr/api/src/java/org/apache/solr/client/api/model/NodeSystemResponse.java b/solr/api/src/java/org/apache/solr/client/api/model/NodeSystemResponse.java
index 1971e323dcd..f513ca46b0d 100644
--- a/solr/api/src/java/org/apache/solr/client/api/model/NodeSystemResponse.java
+++ b/solr/api/src/java/org/apache/solr/client/api/model/NodeSystemResponse.java
@@ -20,6 +20,7 @@ import com.fasterxml.jackson.annotation.JsonAnyGetter;
 import com.fasterxml.jackson.annotation.JsonAnySetter;
 import com.fasterxml.jackson.annotation.JsonProperty;
 import java.util.Date;
+import java.util.LinkedHashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
@@ -27,9 +28,8 @@ import java.util.Set;
 /** Response from /node/system */
 public class NodeSystemResponse extends SolrJerseyResponse {
 
-  // TODO The typing here is kindof wonky - can I tighten 'Object' here to be NodeSystemResponse or
-  // will Jackson choke on that?
-  public Map<String, Object> remoteNodeData;
+  // Object, not NodeSystemResponse, since @JsonAnySetter below also feeds this map raw values.
+  public Map<String, Object> remoteNodeData = new LinkedHashMap<>();
 
   @JsonAnyGetter
   public Map<String, Object> remoteNodeData() {
diff --git a/solr/core/src/test/org/apache/solr/handler/admin/api/GetNodeSystemInfoSolrCloudTest.java b/solr/core/src/test/org/apache/solr/handler/admin/api/GetNodeSystemInfoSolrCloudTest.java
new file mode 100644
index 00000000000..12a6b7e9c06
--- /dev/null
+++ b/solr/core/src/test/org/apache/solr/handler/admin/api/GetNodeSystemInfoSolrCloudTest.java
@@ -0,0 +1,48 @@
+/*
+ * 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.solr.handler.admin.api;
+
+import org.apache.solr.client.solrj.request.CollectionAdminRequest;
+import org.apache.solr.client.solrj.request.SystemApi;
+import org.apache.solr.cloud.SolrCloudTestCase;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+public class GetNodeSystemInfoSolrCloudTest extends SolrCloudTestCase {
+
+  @BeforeClass
+  public static void setupCluster() throws Exception {
+    configureCluster(1).addConfig("conf", configset("cloud-minimal")).configure();
+    CollectionAdminRequest.createCollection(DEFAULT_TEST_COLLECTION_NAME, "conf", 1, 1)
+        .process(cluster.getSolrClient());
+  }
+
+  @Test
+  public void testGetNodeInfoWithNodesParam() throws Exception {
+    String nodeName =
+        cluster.getJettySolrRunners().get(0).getCoreContainer().getZkController().getNodeName();
+
+    final var req = new SystemApi.GetNodeSystemInfo();
+    req.setNodes(nodeName);
+
+    final var infoRsp = req.process(cluster.getSolrClient());
+
+    assertEquals(0, infoRsp.responseHeader.status);
+    assertNotNull(infoRsp.remoteNodeData);
+    assertTrue(infoRsp.remoteNodeData.containsKey(nodeName));
+  }
+}


(solr) 09/13: Tidy up java code in o.a.s.common package (#4669)

Posted by ds...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

dsmiley pushed a commit to branch branch_10x
in repository https://gitbox.apache.org/repos/asf/solr.git

commit f9882fc0650dc10475105cec7fa9583473847a76
Author: Eric Pugh <ep...@opensourceconnections.com>
AuthorDate: Fri Jul 31 20:03:07 2026 -0400

    Tidy up java code in o.a.s.common package (#4669)
    
    (cherry picked from commit bb52661e60749aa92588ab772d02febe585af4a1)
---
 .../apache/solr/cloud/overseer/SliceMutator.java   |   4 +-
 .../org/apache/solr/response/JSONWriterTest.java   |   3 +-
 .../solr/common/cloud/SecurityNodeWatcher.java     |   6 +-
 .../src/java/org/apache/solr/common/Callable.java  |  21 ----
 .../solr/common/ConditionalKeyMapWriter.java       |   5 -
 .../apache/solr/common/ConditionalMapWriter.java   |  84 ---------------
 .../apache/solr/common/LinkedHashMapWriter.java    |  11 --
 .../src/java/org/apache/solr/common/MapWriter.java |   4 -
 .../org/apache/solr/common/NavigableObject.java    |   9 --
 .../org/apache/solr/common/SolrDocumentList.java   |   2 +-
 .../java/org/apache/solr/common/SolrException.java |  44 +-------
 .../apache/solr/common/ToleratedUpdateError.java   |   6 +-
 .../java/org/apache/solr/common/cloud/Aliases.java |   2 +-
 .../solr/common/cloud/CompositeIdRouter.java       |   6 +-
 .../apache/solr/common/cloud/HashBasedRouter.java  |   6 +-
 .../apache/solr/common/cloud/PerReplicaStates.java |   6 +-
 .../org/apache/solr/common/cloud/RoutingRule.java  |   2 +-
 .../java/org/apache/solr/common/cloud/Slice.java   |   2 +-
 .../apache/solr/common/params/AnalysisParams.java  |  14 +--
 .../apache/solr/common/params/CommonParams.java    |   4 -
 .../apache/solr/common/params/ConfigSetParams.java |  10 +-
 .../solr/common/params/CursorMarkParams.java       |   6 +-
 .../apache/solr/common/params/DisMaxParams.java    |  31 +++---
 .../org/apache/solr/common/params/EventParams.java |   6 +-
 .../apache/solr/common/params/ExpandParams.java    |  14 +--
 .../org/apache/solr/common/params/FacetParams.java | 118 ++++++++++----------
 .../org/apache/solr/common/params/GroupParams.java |  32 +++---
 .../apache/solr/common/params/HighlightParams.java | 117 ++++++++++----------
 .../solr/common/params/MoreLikeThisParams.java     |  39 ++++---
 .../apache/solr/common/params/SimpleParams.java    |  24 ++---
 .../org/apache/solr/common/params/SolrParams.java  |  20 ----
 .../apache/solr/common/params/SpatialParams.java   |  12 +--
 .../apache/solr/common/params/SpellingParams.java  |  46 ++++----
 .../org/apache/solr/common/params/StatsParams.java |   8 +-
 .../solr/common/params/TermVectorParams.java       |  20 ++--
 .../org/apache/solr/common/params/TermsParams.java |  30 +++---
 .../apache/solr/common/params/UpdateParams.java    |  34 +++---
 .../common/util/ByteArrayUtf8CharSequence.java     |  12 +--
 .../org/apache/solr/common/util/ByteUtils.java     |  19 ++--
 .../apache/solr/common/util/CommandOperation.java  |  20 +---
 .../solr/common/util/CommonTestInjection.java      |  11 --
 .../apache/solr/common/util/ContentStreamBase.java |   4 -
 .../java/org/apache/solr/common/util/DOMUtil.java  | 119 ---------------------
 .../solr/common/util/DataInputInputStream.java     |   3 +-
 .../org/apache/solr/common/util/ExecutorUtil.java  |  18 ----
 .../solr/common/util/FastJavaBinDecoder.java       |  14 +--
 .../apache/solr/common/util/FastOutputStream.java  |   4 +-
 .../org/apache/solr/common/util/FastWriter.java    |   2 +-
 .../apache/solr/common/util/GlobPatternUtil.java   |   4 +-
 .../org/apache/solr/common/util/JavaBinCodec.java  |  10 +-
 .../apache/solr/common/util/JsonRecordReader.java  |  29 ++---
 .../solr/common/util/JsonSchemaValidator.java      |   1 -
 .../apache/solr/common/util/JsonTextWriter.java    |  76 ++-----------
 .../org/apache/solr/common/util/NamedList.java     |   2 +-
 .../solr/common/util/ObjectReleaseTracker.java     |  11 --
 .../java/org/apache/solr/common/util/PathTrie.java |   2 -
 .../apache/solr/common/util/PropertiesUtil.java    |  19 ----
 .../java/org/apache/solr/common/util/Template.java |  61 -----------
 .../java/org/apache/solr/common/util/URLUtil.java  |   2 +-
 .../java/org/apache/solr/common/util/Utils.java    |  43 --------
 .../src/java/org/apache/solr/common/util/XML.java  |  40 +------
 61 files changed, 346 insertions(+), 988 deletions(-)

diff --git a/solr/core/src/java/org/apache/solr/cloud/overseer/SliceMutator.java b/solr/core/src/java/org/apache/solr/cloud/overseer/SliceMutator.java
index 9b72410a114..b8e5b304d3d 100644
--- a/solr/core/src/java/org/apache/solr/cloud/overseer/SliceMutator.java
+++ b/solr/core/src/java/org/apache/solr/cloud/overseer/SliceMutator.java
@@ -250,14 +250,14 @@ public class SliceMutator {
       map.put("routeRanges", range);
       map.put("targetCollection", targetCollection);
       map.put("expireAt", expireAt);
-      RoutingRule rule = new RoutingRule(routeKey, map);
+      RoutingRule rule = new RoutingRule(map);
       routingRules.put(routeKey, rule);
     } else {
       // add this range
       Map<String, Object> map = r.shallowCopy();
       map.put("routeRanges", map.get("routeRanges") + "," + range);
       map.put("expireAt", expireAt);
-      routingRules.put(routeKey, new RoutingRule(routeKey, map));
+      routingRules.put(routeKey, new RoutingRule(map));
     }
 
     Map<String, Object> props = slice.shallowCopy();
diff --git a/solr/core/src/test/org/apache/solr/response/JSONWriterTest.java b/solr/core/src/test/org/apache/solr/response/JSONWriterTest.java
index ad318de1650..2bfc740a977 100644
--- a/solr/core/src/test/org/apache/solr/response/JSONWriterTest.java
+++ b/solr/core/src/test/org/apache/solr/response/JSONWriterTest.java
@@ -187,10 +187,9 @@ public class JSONWriterTest extends SolrTestCaseJ4 {
   @Test
   public void testArrntvWriterOverridesAllWrites() {
     // List rather than Set because two not-overridden methods could share name but not signature
-    final List<String> methodsExpectedNotOverridden = new ArrayList<>(14);
+    final List<String> methodsExpectedNotOverridden = new ArrayList<>();
     methodsExpectedNotOverridden.add("writeResponse");
     methodsExpectedNotOverridden.add("writeKey");
-    methodsExpectedNotOverridden.add("writeNamedListAsMapMangled");
     methodsExpectedNotOverridden.add("writeNamedListAsMapWithDups");
     methodsExpectedNotOverridden.add("writeNamedListAsArrMap");
     methodsExpectedNotOverridden.add("writeNamedListAsArrArr");
diff --git a/solr/solrj-zookeeper/src/java/org/apache/solr/common/cloud/SecurityNodeWatcher.java b/solr/solrj-zookeeper/src/java/org/apache/solr/common/cloud/SecurityNodeWatcher.java
index 376a9c140c5..0a90b3db6a5 100644
--- a/solr/solrj-zookeeper/src/java/org/apache/solr/common/cloud/SecurityNodeWatcher.java
+++ b/solr/solrj-zookeeper/src/java/org/apache/solr/common/cloud/SecurityNodeWatcher.java
@@ -19,7 +19,7 @@ package org.apache.solr.common.cloud;
 import java.lang.invoke.MethodHandles;
 import java.nio.charset.StandardCharsets;
 import java.util.Map;
-import org.apache.solr.common.Callable;
+import java.util.function.Consumer;
 import org.apache.solr.common.SolrException;
 import org.apache.solr.common.util.Utils;
 import org.apache.zookeeper.KeeperException;
@@ -35,7 +35,7 @@ class SecurityNodeWatcher implements Watcher {
   private final ZkStateReader zkStateReader;
   private ZkStateReader.ConfigData securityData;
 
-  private final Callable<SolrZkClient.NodeData> callback;
+  private final Consumer<SolrZkClient.NodeData> callback;
 
   @SuppressWarnings("unchecked")
   public SecurityNodeWatcher(ZkStateReader zkStateReader, Runnable securityNodeListener) {
@@ -74,7 +74,7 @@ class SecurityNodeWatcher implements Watcher {
           data = zkStateReader.getZkClient().getNode(ZkStateReader.SOLR_SECURITY_CONF_PATH, this);
         }
         try {
-          callback.call(data);
+          callback.accept(data);
         } catch (Exception e) {
           log.error("Error running collections node listener", e);
         }
diff --git a/solr/solrj/src/java/org/apache/solr/common/Callable.java b/solr/solrj/src/java/org/apache/solr/common/Callable.java
deleted file mode 100644
index 8e43ac8e391..00000000000
--- a/solr/solrj/src/java/org/apache/solr/common/Callable.java
+++ /dev/null
@@ -1,21 +0,0 @@
-/*
- * 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.solr.common;
-
-public interface Callable<T> {
-  public void call(T data); // data depends on the context
-}
diff --git a/solr/solrj/src/java/org/apache/solr/common/ConditionalKeyMapWriter.java b/solr/solrj/src/java/org/apache/solr/common/ConditionalKeyMapWriter.java
index c8833413015..09770931aac 100644
--- a/solr/solrj/src/java/org/apache/solr/common/ConditionalKeyMapWriter.java
+++ b/solr/solrj/src/java/org/apache/solr/common/ConditionalKeyMapWriter.java
@@ -18,7 +18,6 @@
 package org.apache.solr.common;
 
 import java.io.IOException;
-import java.util.Set;
 import java.util.function.Predicate;
 
 public class ConditionalKeyMapWriter implements MapWriter {
@@ -80,8 +79,4 @@ public class ConditionalKeyMapWriter implements MapWriter {
   public void writeMap(EntryWriter ew) throws IOException {
     if (delegate != null) delegate.writeMap(new EntryWriterWrapper(ew, predicate));
   }
-
-  public static Predicate<CharSequence> dedupeKeyPredicate(Set<CharSequence> keys) {
-    return (k) -> keys.add(k);
-  }
 }
diff --git a/solr/solrj/src/java/org/apache/solr/common/ConditionalMapWriter.java b/solr/solrj/src/java/org/apache/solr/common/ConditionalMapWriter.java
deleted file mode 100644
index 54785685cda..00000000000
--- a/solr/solrj/src/java/org/apache/solr/common/ConditionalMapWriter.java
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * 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.solr.common;
-
-import java.io.IOException;
-import java.util.Set;
-import java.util.function.BiPredicate;
-
-public class ConditionalMapWriter implements MapWriter {
-  private final MapWriter delegate;
-  private final BiPredicate<CharSequence, Object> predicate;
-
-  public ConditionalMapWriter(MapWriter delegate, BiPredicate<CharSequence, Object> predicate) {
-    this.delegate = delegate;
-    this.predicate = predicate;
-  }
-
-  public static class EntryWriterWrapper implements EntryWriter {
-    private final EntryWriter delegate;
-    private final BiPredicate<CharSequence, Object> predicate;
-
-    public EntryWriterWrapper(EntryWriter delegate, BiPredicate<CharSequence, Object> predicate) {
-      this.delegate = delegate;
-      this.predicate = predicate;
-    }
-
-    @Override
-    public EntryWriter put(CharSequence k, Object v) throws IOException {
-      if (predicate.test(k, v)) delegate.put(k, v);
-      return this;
-    }
-
-    @Override
-    public EntryWriter put(CharSequence k, int v) throws IOException {
-      return put(k, Integer.valueOf(v));
-    }
-
-    @Override
-    public EntryWriter put(CharSequence k, long v) throws IOException {
-      return put(k, Long.valueOf(v));
-    }
-
-    @Override
-    public EntryWriter put(CharSequence k, float v) throws IOException {
-      return put(k, Float.valueOf(v));
-    }
-
-    @Override
-    public EntryWriter put(CharSequence k, double v) throws IOException {
-      return put(k, Double.valueOf(v));
-    }
-
-    @Override
-    public EntryWriter put(CharSequence k, boolean v) throws IOException {
-      return put(k, Boolean.valueOf(v));
-    }
-  }
-
-  @Override
-  public void writeMap(EntryWriter ew) throws IOException {
-    if (delegate != null) delegate.writeMap(new EntryWriterWrapper(ew, predicate));
-  }
-
-  public static BiPredicate<CharSequence, Object> dedupeKeyPredicate(Set<CharSequence> keys) {
-    return (k, v) -> keys.add(k);
-  }
-
-  public static final BiPredicate<CharSequence, Object> NON_NULL_VAL = (s, o) -> o != null;
-}
diff --git a/solr/solrj/src/java/org/apache/solr/common/LinkedHashMapWriter.java b/solr/solrj/src/java/org/apache/solr/common/LinkedHashMapWriter.java
index 57edf04c5b9..418f05d4254 100644
--- a/solr/solrj/src/java/org/apache/solr/common/LinkedHashMapWriter.java
+++ b/solr/solrj/src/java/org/apache/solr/common/LinkedHashMapWriter.java
@@ -20,24 +20,13 @@ package org.apache.solr.common;
 import java.io.IOException;
 import java.util.LinkedHashMap;
 import java.util.List;
-import java.util.Map;
-import org.apache.solr.common.util.SuppressForbidden;
 
 public class LinkedHashMapWriter<V> extends LinkedHashMap<String, V> implements MapWriter {
 
-  @SuppressForbidden(reason = "extends LinkedHashMap")
-  public LinkedHashMapWriter(int initialCapacity) {
-    super(initialCapacity);
-  }
-
   public LinkedHashMapWriter() {
     super();
   }
 
-  public LinkedHashMapWriter(Map<? extends String, ? extends V> m) {
-    super(m);
-  }
-
   @Override
   public void writeMap(EntryWriter ew) throws IOException {
     forEach(ew.getBiConsumer());
diff --git a/solr/solrj/src/java/org/apache/solr/common/MapWriter.java b/solr/solrj/src/java/org/apache/solr/common/MapWriter.java
index d98d66f3bde..d9ab56867ce 100644
--- a/solr/solrj/src/java/org/apache/solr/common/MapWriter.java
+++ b/solr/solrj/src/java/org/apache/solr/common/MapWriter.java
@@ -18,7 +18,6 @@
 package org.apache.solr.common;
 
 import java.io.IOException;
-import java.util.Map;
 import java.util.function.BiConsumer;
 import java.util.function.BiPredicate;
 import java.util.function.Supplier;
@@ -145,7 +144,4 @@ public interface MapWriter extends NavigableObject, JSONWriter.Writable {
       return this::putNoEx;
     }
   }
-
-  @Deprecated // use SimpleOrderedMap.of()
-  MapWriter EMPTY = new MapWriterMap(Map.of());
 }
diff --git a/solr/solrj/src/java/org/apache/solr/common/NavigableObject.java b/solr/solrj/src/java/org/apache/solr/common/NavigableObject.java
index 8b0004b4127..226dc3a90ab 100644
--- a/solr/solrj/src/java/org/apache/solr/common/NavigableObject.java
+++ b/solr/solrj/src/java/org/apache/solr/common/NavigableObject.java
@@ -61,15 +61,6 @@ public interface NavigableObject {
     Utils.forEachMapEntry(this, path, fun);
   }
 
-  /**
-   * Iterate through the entries of a navigable Object at a certain path
-   *
-   * @param path the json path
-   */
-  default void _forEachEntry(List<String> path, @SuppressWarnings({"rawtypes"}) BiConsumer fun) {
-    Utils.forEachMapEntry(this, path, fun);
-  }
-
   /** Iterate through each entry in this object */
   default void _forEachEntry(@SuppressWarnings({"rawtypes"}) BiConsumer fun) {
     Utils.forEachMapEntry(this, fun);
diff --git a/solr/solrj/src/java/org/apache/solr/common/SolrDocumentList.java b/solr/solrj/src/java/org/apache/solr/common/SolrDocumentList.java
index cbc7f8dd2b5..9b9c427979d 100644
--- a/solr/solrj/src/java/org/apache/solr/common/SolrDocumentList.java
+++ b/solr/solrj/src/java/org/apache/solr/common/SolrDocumentList.java
@@ -86,7 +86,7 @@ public class SolrDocumentList extends ArrayList<SolrDocument> implements MapWrit
     return "{numFound="
         + numFound
         + ",numFoundExact="
-        + String.valueOf(numFoundExact)
+        + numFoundExact
         + ",start="
         + start
         + (maxScore != null ? ",maxScore=" + maxScore : "")
diff --git a/solr/solrj/src/java/org/apache/solr/common/SolrException.java b/solr/solrj/src/java/org/apache/solr/common/SolrException.java
index 66a5a4b4fb2..b8eceee17af 100644
--- a/solr/solrj/src/java/org/apache/solr/common/SolrException.java
+++ b/solr/solrj/src/java/org/apache/solr/common/SolrException.java
@@ -23,14 +23,10 @@ import java.util.List;
 import java.util.Map;
 import org.apache.solr.common.util.NamedList;
 import org.apache.solr.common.util.SimpleOrderedMap;
-import org.slf4j.Logger;
-import org.slf4j.MDC;
 
 /** */
 public class SolrException extends RuntimeException {
 
-  private final Map<String, String> mdcContext;
-
   /**
    * This list of valid HTTP Status error codes that Solr may return when there is a "Server Side"
    * error.
@@ -52,7 +48,7 @@ public class SolrException extends RuntimeException {
     UNKNOWN(0);
     public final int code;
 
-    private ErrorCode(int c) {
+    ErrorCode(int c) {
       code = c;
     }
 
@@ -62,24 +58,21 @@ public class SolrException extends RuntimeException {
       }
       return UNKNOWN;
     }
-  };
+  }
 
   public SolrException(ErrorCode code, String msg) {
     super(msg);
     this.code = code.code;
-    this.mdcContext = MDC.getCopyOfContextMap();
   }
 
   public SolrException(ErrorCode code, String msg, Throwable th) {
     super(msg, th);
     this.code = code.code;
-    this.mdcContext = MDC.getCopyOfContextMap();
   }
 
   public SolrException(ErrorCode code, Throwable th) {
     super(th);
     this.code = code.code;
-    this.mdcContext = MDC.getCopyOfContextMap();
   }
 
   /**
@@ -90,10 +83,9 @@ public class SolrException extends RuntimeException {
   protected SolrException(int code, String msg, Throwable th) {
     super(msg, th);
     this.code = code;
-    this.mdcContext = MDC.getCopyOfContextMap();
   }
 
-  int code = 0;
+  int code;
   protected NamedList<String> metadata;
   protected List<Map<String, Object>> details;
 
@@ -180,34 +172,4 @@ public class SolrException extends RuntimeException {
 
     return new SolrException(ErrorCode.SERVER_ERROR, e.getMessage(), e);
   }
-
-  public void logInfoWithMdc(Logger logger, String msg) {
-    Map<String, String> previousMdcContext = MDC.getCopyOfContextMap();
-    MDC.setContextMap(mdcContext);
-    try {
-      logger.info(msg);
-    } finally {
-      MDC.setContextMap(previousMdcContext);
-    }
-  }
-
-  public void logDebugWithMdc(Logger logger, String msg) {
-    Map<String, String> previousMdcContext = MDC.getCopyOfContextMap();
-    MDC.setContextMap(mdcContext);
-    try {
-      logger.debug(msg);
-    } finally {
-      MDC.setContextMap(previousMdcContext);
-    }
-  }
-
-  public void logWarnWithMdc(Logger logger, String msg) {
-    Map<String, String> previousMdcContext = MDC.getCopyOfContextMap();
-    MDC.setContextMap(mdcContext);
-    try {
-      logger.warn(msg);
-    } finally {
-      MDC.setContextMap(previousMdcContext);
-    }
-  }
 }
diff --git a/solr/solrj/src/java/org/apache/solr/common/ToleratedUpdateError.java b/solr/solrj/src/java/org/apache/solr/common/ToleratedUpdateError.java
index 15d03b4792b..02839e35005 100644
--- a/solr/solrj/src/java/org/apache/solr/common/ToleratedUpdateError.java
+++ b/solr/solrj/src/java/org/apache/solr/common/ToleratedUpdateError.java
@@ -160,7 +160,7 @@ public final class ToleratedUpdateError {
    * @see #parseMetadataIfToleratedUpdateError
    */
   public String getMetadataValue() {
-    return message.toString();
+    return message;
   }
 
   /**
@@ -202,10 +202,10 @@ public final class ToleratedUpdateError {
   }
 
   /** Helper class for dealing with SolrException metadata (String) keys */
-  public static enum CmdType {
+  public enum CmdType {
     ADD,
     DELID,
-    DELQ;
+    DELQ
 
     // if we add support for things like commit, parsing/toString/hashCode logic
     // needs to be smarter to account for 'id' being null ... "usesId" should be a prop of enum
diff --git a/solr/solrj/src/java/org/apache/solr/common/cloud/Aliases.java b/solr/solrj/src/java/org/apache/solr/common/cloud/Aliases.java
index f09622c3b01..957d15769e9 100644
--- a/solr/solrj/src/java/org/apache/solr/common/cloud/Aliases.java
+++ b/solr/solrj/src/java/org/apache/solr/common/cloud/Aliases.java
@@ -355,7 +355,7 @@ public class Aliases {
    *
    * @param before previous alias name, must not be null
    * @param after new alias name. If this is null then it's equivalent to calling {@link
-   *     #cloneWithCollectionAlias(String, String)} with the second argument set to null, ie.
+   *     #cloneWithCollectionAlias(String, String)} with the second argument set to null, i.e.
    *     removing an alias.
    * @return new instance with the renamed alias
    * @throws SolrException when either <code>before</code> or <code>after</code> is empty, or the
diff --git a/solr/solrj/src/java/org/apache/solr/common/cloud/CompositeIdRouter.java b/solr/solrj/src/java/org/apache/solr/common/cloud/CompositeIdRouter.java
index fede4e6b453..925cb16ba53 100644
--- a/solr/solrj/src/java/org/apache/solr/common/cloud/CompositeIdRouter.java
+++ b/solr/solrj/src/java/org/apache/solr/common/cloud/CompositeIdRouter.java
@@ -44,12 +44,12 @@ import org.apache.solr.common.util.Hash;
  *
  * <pre>
  * An Example:
- * If the id "contact!0000000KISS is passed 😘
- * Take "contact"" and hash it with murmurhash3_x86_32
+ * If the id "contact!0000000KISS" is passed 😘
+ * Take "contact" and hash it with murmurhash3_x86_32
  * result: -541354036
  * bits: 11011111101110111001011111001100
  *
- * Take 0000000KISS and hash it with murmurhash3_x86_32
+ * Take "0000000KISS" and hash it with murmurhash3_x86_32
  * result: 2099700320
  * bits: 01111101001001101110001001100000
  *
diff --git a/solr/solrj/src/java/org/apache/solr/common/cloud/HashBasedRouter.java b/solr/solrj/src/java/org/apache/solr/common/cloud/HashBasedRouter.java
index 9d38c3e95c4..6d702b61962 100644
--- a/solr/solrj/src/java/org/apache/solr/common/cloud/HashBasedRouter.java
+++ b/solr/solrj/src/java/org/apache/solr/common/cloud/HashBasedRouter.java
@@ -38,7 +38,7 @@ public abstract class HashBasedRouter extends DocRouter {
     if (route != null) {
       hash = sliceHash(route, sdoc, params, collection);
     } else {
-      if (id == null) id = getId(sdoc, params);
+      if (id == null) id = getId(sdoc);
       hash = sliceHash(id, sdoc, params, collection);
     }
     return hashToSlice(hash, collection);
@@ -51,7 +51,7 @@ public abstract class HashBasedRouter extends DocRouter {
       SolrParams params,
       String shardId,
       DocCollection collection) {
-    if (id == null) id = getId(sdoc, params);
+    if (id == null) id = getId(sdoc);
     int hash = sliceHash(id, sdoc, params, collection);
     Range range = collection.getSlice(shardId).getRange();
     return range != null && range.includes(hash);
@@ -62,7 +62,7 @@ public abstract class HashBasedRouter extends DocRouter {
     return Hash.murmurhash3_x86_32(id, 0, id.length(), 0);
   }
 
-  protected String getId(SolrInputDocument sdoc, SolrParams params) {
+  protected String getId(SolrInputDocument sdoc) {
     Object idObj = sdoc.getFieldValue(ID); // blech
     String id = idObj != null ? idObj.toString() : "null"; // should only happen on client side
     return id;
diff --git a/solr/solrj/src/java/org/apache/solr/common/cloud/PerReplicaStates.java b/solr/solrj/src/java/org/apache/solr/common/cloud/PerReplicaStates.java
index e4ed2e0f0e0..0d1c26bb040 100644
--- a/solr/solrj/src/java/org/apache/solr/common/cloud/PerReplicaStates.java
+++ b/solr/solrj/src/java/org/apache/solr/common/cloud/PerReplicaStates.java
@@ -20,7 +20,6 @@ package org.apache.solr.common.cloud;
 import static org.apache.solr.common.params.CommonParams.NAME;
 
 import java.io.IOException;
-import java.lang.invoke.MethodHandles;
 import java.util.ArrayList;
 import java.util.HashSet;
 import java.util.LinkedHashMap;
@@ -35,20 +34,17 @@ import org.apache.solr.common.annotation.JsonProperty;
 import org.apache.solr.common.cloud.Replica.ReplicaStateProps;
 import org.apache.solr.common.util.ReflectMapWriter;
 import org.apache.solr.common.util.StrUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
 
 /**
  * This represents the individual replica states in a collection This is an immutable object. When
  * states are modified, a new instance is constructed
  */
 public class PerReplicaStates implements ReflectMapWriter {
-  private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
   public static final char SEPARATOR = ':';
   // no:of times to retry in case of a CAS failure
   public static final int MAX_RETRIES = 5;
 
-  // znode path where thisis loaded from
+  // znode path where this is loaded from
   @JsonProperty public final String path;
 
   // the child version of that znode
diff --git a/solr/solrj/src/java/org/apache/solr/common/cloud/RoutingRule.java b/solr/solrj/src/java/org/apache/solr/common/cloud/RoutingRule.java
index d4f863a125d..d587236acdf 100644
--- a/solr/solrj/src/java/org/apache/solr/common/cloud/RoutingRule.java
+++ b/solr/solrj/src/java/org/apache/solr/common/cloud/RoutingRule.java
@@ -29,7 +29,7 @@ public class RoutingRule extends ZkNodeProps {
   private final String targetCollectionName;
   private final Long expireAt;
 
-  public RoutingRule(String routeKey, Map<String, Object> propMap) {
+  public RoutingRule(Map<String, Object> propMap) {
     super(propMap);
     this.routeRangesStr = (String) propMap.get("routeRanges");
     String[] rangesArr = this.routeRangesStr.split(",");
diff --git a/solr/solrj/src/java/org/apache/solr/common/cloud/Slice.java b/solr/solrj/src/java/org/apache/solr/common/cloud/Slice.java
index c307a8f9f1c..0de9be921aa 100644
--- a/solr/solrj/src/java/org/apache/solr/common/cloud/Slice.java
+++ b/solr/solrj/src/java/org/apache/solr/common/cloud/Slice.java
@@ -207,7 +207,7 @@ public class Slice extends ZkNodeProps implements Iterable<Replica> {
       for (Map.Entry<String, Object> entry : rules.entrySet()) {
         Object o = entry.getValue();
         if (o instanceof Map map) {
-          RoutingRule rule = new RoutingRule(entry.getKey(), map);
+          RoutingRule rule = new RoutingRule(map);
           routingRules.put(entry.getKey(), rule);
         } else {
           routingRules.put(entry.getKey(), (RoutingRule) o);
diff --git a/solr/solrj/src/java/org/apache/solr/common/params/AnalysisParams.java b/solr/solrj/src/java/org/apache/solr/common/params/AnalysisParams.java
index d50db80de03..c7eeeccd52a 100644
--- a/solr/solrj/src/java/org/apache/solr/common/params/AnalysisParams.java
+++ b/solr/solrj/src/java/org/apache/solr/common/params/AnalysisParams.java
@@ -24,25 +24,25 @@ package org.apache.solr.common.params;
 public interface AnalysisParams {
 
   /** The prefix for all parameters. */
-  static final String PREFIX = "analysis";
+  String PREFIX = "analysis";
 
   /** Holds the query to be analyzed. */
-  static final String QUERY = PREFIX + ".query";
+  String QUERY = PREFIX + ".query";
 
   /**
    * Set to {@code true} to indicate that the index tokens that match query tokens should be marked
    * as "matched".
    */
-  static final String SHOW_MATCH = PREFIX + ".showmatch";
+  String SHOW_MATCH = PREFIX + ".showmatch";
 
   // ===== FieldAnalysisRequestHandler Params =====
 
   /** Holds the value of the field which should be analyzed. */
-  static final String FIELD_NAME = PREFIX + ".fieldname";
+  String FIELD_NAME = PREFIX + ".fieldname";
 
-  /** Holds a comma-separated list of field types that the analysis should be peformed for. */
-  static final String FIELD_TYPE = PREFIX + ".fieldtype";
+  /** Holds a comma-separated list of field types that the analysis should be performed for. */
+  String FIELD_TYPE = PREFIX + ".fieldtype";
 
   /** Holds a comma-separated list of field named that the analysis should be performed for. */
-  static final String FIELD_VALUE = PREFIX + ".fieldvalue";
+  String FIELD_VALUE = PREFIX + ".fieldvalue";
 }
diff --git a/solr/solrj/src/java/org/apache/solr/common/params/CommonParams.java b/solr/solrj/src/java/org/apache/solr/common/params/CommonParams.java
index 2e9e5b89a82..3bed47aac57 100644
--- a/solr/solrj/src/java/org/apache/solr/common/params/CommonParams.java
+++ b/solr/solrj/src/java/org/apache/solr/common/params/CommonParams.java
@@ -92,9 +92,6 @@ public interface CommonParams {
 
   // SOLR-4228 end
 
-  /** stylesheet to apply to XML results */
-  String XSL = "xsl";
-
   /** query and init param for field list */
   String FL = "fl";
 
@@ -313,7 +310,6 @@ public interface CommonParams {
   String JAVABIN_MIME = "application/javabin";
 
   String FILE = "file";
-  String FILES = "files";
 
   String CHILDDOC = "_childDocuments_";
 }
diff --git a/solr/solrj/src/java/org/apache/solr/common/params/ConfigSetParams.java b/solr/solrj/src/java/org/apache/solr/common/params/ConfigSetParams.java
index f7bff105370..18fbfa54238 100644
--- a/solr/solrj/src/java/org/apache/solr/common/params/ConfigSetParams.java
+++ b/solr/solrj/src/java/org/apache/solr/common/params/ConfigSetParams.java
@@ -20,12 +20,12 @@ import java.util.Locale;
 
 /** ConfigSets API related parameters and actions. */
 public interface ConfigSetParams {
-  public static final String ACTION = "action";
-  public static final String OVERWRITE = "overwrite";
-  public static final String CLEANUP = "cleanup";
-  public static final String FILE_PATH = "filePath";
+  String ACTION = "action";
+  String OVERWRITE = "overwrite";
+  String CLEANUP = "cleanup";
+  String FILE_PATH = "filePath";
 
-  public enum ConfigSetAction {
+  enum ConfigSetAction {
     CREATE,
     UPLOAD,
     DELETE,
diff --git a/solr/solrj/src/java/org/apache/solr/common/params/CursorMarkParams.java b/solr/solrj/src/java/org/apache/solr/common/params/CursorMarkParams.java
index d641d3337e5..9c1953f6611 100644
--- a/solr/solrj/src/java/org/apache/solr/common/params/CursorMarkParams.java
+++ b/solr/solrj/src/java/org/apache/solr/common/params/CursorMarkParams.java
@@ -27,18 +27,18 @@ public interface CursorMarkParams {
    * specified must either be {@link #CURSOR_MARK_START} indicating the first page of results, or a
    * value returned by a previous search via the {@link #CURSOR_MARK_NEXT} key.
    */
-  public static final String CURSOR_MARK_PARAM = "cursorMark";
+  String CURSOR_MARK_PARAM = "cursorMark";
 
   /**
    * Key used in Solr response to inform the client what the "next" {@link #CURSOR_MARK_PARAM} value
    * should be to continue pagination
    */
-  public static final String CURSOR_MARK_NEXT = "nextCursorMark";
+  String CURSOR_MARK_NEXT = "nextCursorMark";
 
   /**
    * Special value for {@link #CURSOR_MARK_PARAM} indicating that cursor functionality should be
    * used, and a new cursor value should be computed after the last result, but that currently the
    * "first page" of results is being requested
    */
-  public static final String CURSOR_MARK_START = "*";
+  String CURSOR_MARK_START = "*";
 }
diff --git a/solr/solrj/src/java/org/apache/solr/common/params/DisMaxParams.java b/solr/solrj/src/java/org/apache/solr/common/params/DisMaxParams.java
index 3168b1d60b9..e9615c78cf9 100644
--- a/solr/solrj/src/java/org/apache/solr/common/params/DisMaxParams.java
+++ b/solr/solrj/src/java/org/apache/solr/common/params/DisMaxParams.java
@@ -23,50 +23,47 @@ package org.apache.solr.common.params;
 public interface DisMaxParams {
 
   /** query and init param for tiebreaker value */
-  public static String TIE = "tie";
+  String TIE = "tie";
 
   /** query and init param for query fields */
-  public static String QF = "qf";
+  String QF = "qf";
 
   /** query and init param for phrase boost fields */
-  public static String PF = "pf";
+  String PF = "pf";
 
   /** query and init param for bigram phrase boost fields */
-  public static String PF2 = "pf2";
+  String PF2 = "pf2";
 
   /** query and init param for trigram phrase boost fields */
-  public static String PF3 = "pf3";
+  String PF3 = "pf3";
 
   /** query and init param for MinShouldMatch specification */
-  public static String MM = "mm";
+  String MM = "mm";
 
   /** If set to true, will try to reduce MM if tokens are removed from some clauses but not all */
-  public static String MM_AUTORELAX = "mm.autoRelax";
+  String MM_AUTORELAX = "mm.autoRelax";
 
   /** query and init param for Phrase Slop value in phrase boost query (in pf fields) */
-  public static String PS = "ps";
+  String PS = "ps";
 
   /** default phrase slop for bigram phrases (pf2) */
-  public static String PS2 = "ps2";
+  String PS2 = "ps2";
 
   /** default phrase slop for bigram phrases (pf3) */
-  public static String PS3 = "ps3";
+  String PS3 = "ps3";
 
   /**
    * query and init param for phrase Slop value in phrases explicitly included in the user's query
    * string ( in qf fields)
    */
-  public static String QS = "qs";
+  String QS = "qs";
 
   /** query and init param for boosting query */
-  public static String BQ = "bq";
+  String BQ = "bq";
 
   /** query and init param for boosting functions */
-  public static String BF = "bf";
+  String BF = "bf";
 
   /** Alternate query (expressed in Solr QuerySyntax) to use if main query (q) is empty */
-  public static String ALTQ = "q.alt";
-
-  /** query and init param for field list */
-  public static String GEN = "gen";
+  String ALTQ = "q.alt";
 }
diff --git a/solr/solrj/src/java/org/apache/solr/common/params/EventParams.java b/solr/solrj/src/java/org/apache/solr/common/params/EventParams.java
index c38b93ef38b..d676901bd59 100644
--- a/solr/solrj/src/java/org/apache/solr/common/params/EventParams.java
+++ b/solr/solrj/src/java/org/apache/solr/common/params/EventParams.java
@@ -19,8 +19,8 @@ package org.apache.solr.common.params;
 /** */
 public interface EventParams {
   /** Event param for things like newSearcher, firstSearcher* */
-  public static final String EVENT = "event";
+  String EVENT = "event";
 
-  public static final String NEW_SEARCHER = "newSearcher";
-  public static final String FIRST_SEARCHER = "firstSearcher";
+  String NEW_SEARCHER = "newSearcher";
+  String FIRST_SEARCHER = "firstSearcher";
 }
diff --git a/solr/solrj/src/java/org/apache/solr/common/params/ExpandParams.java b/solr/solrj/src/java/org/apache/solr/common/params/ExpandParams.java
index 2584f816b31..905d4b68370 100644
--- a/solr/solrj/src/java/org/apache/solr/common/params/ExpandParams.java
+++ b/solr/solrj/src/java/org/apache/solr/common/params/ExpandParams.java
@@ -19,11 +19,11 @@ package org.apache.solr.common.params;
 /** Expand parameters */
 public interface ExpandParams {
 
-  public static final String EXPAND = "expand";
-  public static final String EXPAND_SORT = EXPAND + ".sort";
-  public static final String EXPAND_ROWS = EXPAND + ".rows";
-  public static final String EXPAND_FIELD = EXPAND + ".field";
-  public static final String EXPAND_Q = EXPAND + ".q";
-  public static final String EXPAND_FQ = EXPAND + ".fq";
-  public static final String EXPAND_NULL = EXPAND + ".nullGroup";
+  String EXPAND = "expand";
+  String EXPAND_SORT = EXPAND + ".sort";
+  String EXPAND_ROWS = EXPAND + ".rows";
+  String EXPAND_FIELD = EXPAND + ".field";
+  String EXPAND_Q = EXPAND + ".q";
+  String EXPAND_FQ = EXPAND + ".fq";
+  String EXPAND_NULL = EXPAND + ".nullGroup";
 }
diff --git a/solr/solrj/src/java/org/apache/solr/common/params/FacetParams.java b/solr/solrj/src/java/org/apache/solr/common/params/FacetParams.java
index 53fce3670bd..f52ba0eb33b 100644
--- a/solr/solrj/src/java/org/apache/solr/common/params/FacetParams.java
+++ b/solr/solrj/src/java/org/apache/solr/common/params/FacetParams.java
@@ -24,83 +24,83 @@ import org.apache.solr.common.SolrException;
 public interface FacetParams {
 
   /** Should facet counts be calculated? */
-  public static final String FACET = "facet";
+  String FACET = "facet";
 
   /**
    * Numeric option indicating the maximum number of threads to be used in counting facet field
    * vales
    */
-  public static final String FACET_THREADS = FACET + ".threads";
+  String FACET_THREADS = FACET + ".threads";
 
   /** What method should be used to do the faceting */
-  public static final String FACET_METHOD = FACET + ".method";
+  String FACET_METHOD = FACET + ".method";
 
   /**
    * Value for FACET_METHOD param to indicate that Solr should enumerate over terms in a field to
    * calculate the facet counts.
    */
-  public static final String FACET_METHOD_enum = "enum";
+  String FACET_METHOD_enum = "enum";
 
   /**
    * Value for FACET_METHOD param to indicate that Solr should enumerate over documents and count up
    * terms by consulting an uninverted representation of the field values (such as the FieldCache
    * used for sorting).
    */
-  public static final String FACET_METHOD_fc = "fc";
+  String FACET_METHOD_fc = "fc";
 
   /** Value for FACET_METHOD param, like FACET_METHOD_fc but counts per-segment. */
-  public static final String FACET_METHOD_fcs = "fcs";
+  String FACET_METHOD_fcs = "fcs";
 
   /** Value for FACET_METHOD param to indicate that Solr should use an UnInvertedField */
-  public static final String FACET_METHOD_uif = "uif";
+  String FACET_METHOD_uif = "uif";
 
   /**
    * Any lucene formatted queries the user would like to use for Facet Constraint Counts
    * (multi-value)
    */
-  public static final String FACET_QUERY = FACET + ".query";
+  String FACET_QUERY = FACET + ".query";
 
   /**
    * Any field whose terms the user wants to enumerate over for Facet Constraint Counts
    * (multi-value)
    */
-  public static final String FACET_FIELD = FACET + ".field";
+  String FACET_FIELD = FACET + ".field";
 
   /** The offset into the list of facets. Can be overridden on a per field basis. */
-  public static final String FACET_OFFSET = FACET + ".offset";
+  String FACET_OFFSET = FACET + ".offset";
 
   /**
    * Numeric option indicating the maximum number of facet field counts be included in the response
    * for each field - in descending order of count. Can be overridden on a per field basis.
    */
-  public static final String FACET_LIMIT = FACET + ".limit";
+  String FACET_LIMIT = FACET + ".limit";
 
   /**
    * Numeric option indicating the minimum number of hits before a facet should be included in the
    * response. Can be overridden on a per field basis.
    */
-  public static final String FACET_MINCOUNT = FACET + ".mincount";
+  String FACET_MINCOUNT = FACET + ".mincount";
 
   /**
    * Boolean option indicating whether facet field counts of "0" should be included in the response.
    * Can be overridden on a per field basis.
    */
-  public static final String FACET_ZEROS = FACET + ".zeros";
+  String FACET_ZEROS = FACET + ".zeros";
 
   /**
    * Boolean option indicating whether the response should include a facet field count for all
    * records which have no value for the facet field. Can be overridden on a per field basis.
    */
-  public static final String FACET_MISSING = FACET + ".missing";
+  String FACET_MISSING = FACET + ".missing";
 
-  static final String FACET_OVERREQUEST = FACET + ".overrequest";
+  String FACET_OVERREQUEST = FACET + ".overrequest";
 
   /**
    * The percentage to over-request by when performing initial distributed requests.
    *
    * <p>default value is 1.5
    */
-  public static final String FACET_OVERREQUEST_RATIO = FACET_OVERREQUEST + ".ratio";
+  String FACET_OVERREQUEST_RATIO = FACET_OVERREQUEST + ".ratio";
 
   /**
    * An additional amount to over-request by when performing initial distributed requests. This
@@ -108,81 +108,81 @@ public interface FacetParams {
    *
    * <p>default value is 10
    */
-  public static final String FACET_OVERREQUEST_COUNT = FACET_OVERREQUEST + ".count";
+  String FACET_OVERREQUEST_COUNT = FACET_OVERREQUEST + ".count";
 
   /**
    * Comma separated list of fields to pivot
    *
    * <p>example: author,type (for types by author / types within author)
    */
-  public static final String FACET_PIVOT = FACET + ".pivot";
+  String FACET_PIVOT = FACET + ".pivot";
 
   /**
    * Minimum number of docs that need to match to be included in the sublist
    *
    * <p>default value is 1
    */
-  public static final String FACET_PIVOT_MINCOUNT = FACET_PIVOT + ".mincount";
+  String FACET_PIVOT_MINCOUNT = FACET_PIVOT + ".mincount";
 
   /**
    * String option: "count" causes facets to be sorted by the count, "index" results in index order.
    */
-  public static final String FACET_SORT = FACET + ".sort";
+  String FACET_SORT = FACET + ".sort";
 
-  public static final String FACET_SORT_COUNT = "count";
-  public static final String FACET_SORT_COUNT_LEGACY = "true";
-  public static final String FACET_SORT_INDEX = "index";
-  public static final String FACET_SORT_INDEX_LEGACY = "false";
+  String FACET_SORT_COUNT = "count";
+  String FACET_SORT_COUNT_LEGACY = "true";
+  String FACET_SORT_INDEX = "index";
+  String FACET_SORT_INDEX_LEGACY = "false";
 
   /** Only return constraints of a facet field with the given prefix. */
-  public static final String FACET_PREFIX = FACET + ".prefix";
+  String FACET_PREFIX = FACET + ".prefix";
 
   /** Only return constraints of a facet field containing the given string. */
-  public static final String FACET_CONTAINS = FACET + ".contains";
+  String FACET_CONTAINS = FACET + ".contains";
 
   /** Only return constraints of a facet field containing the given string. */
-  public static final String FACET_MATCHES = FACET + ".matches";
+  String FACET_MATCHES = FACET + ".matches";
 
   /** If using facet contains, ignore case when comparing values. */
-  public static final String FACET_CONTAINS_IGNORE_CASE = FACET_CONTAINS + ".ignoreCase";
+  String FACET_CONTAINS_IGNORE_CASE = FACET_CONTAINS + ".ignoreCase";
 
   /** Only return constraints of a facet field excluding the given string. */
-  public static final String FACET_EXCLUDETERMS = FACET + ".excludeTerms";
+  String FACET_EXCLUDETERMS = FACET + ".excludeTerms";
 
   /**
    * When faceting by enumerating the terms in a field, only use the filterCache for terms with a df
    * &gt;= to this parameter.
    */
-  public static final String FACET_ENUM_CACHE_MINDF = FACET + ".enum.cache.minDf";
+  String FACET_ENUM_CACHE_MINDF = FACET + ".enum.cache.minDf";
 
   /**
    * A boolean parameter that caps the facet counts at 1. With this set, a returned count will only
    * be 0 or 1. For apps that don't need the count, this should be an optimization
    */
-  public static final String FACET_EXISTS = FACET + ".exists";
+  String FACET_EXISTS = FACET + ".exists";
 
   /**
    * Any field whose terms the user wants to enumerate over for Facet Contraint Counts (multi-value)
    */
-  public static final String FACET_DATE = FACET + ".date";
+  String FACET_DATE = FACET + ".date";
 
   /**
    * Date string indicating the starting point for a date facet range. Can be overridden on a per
    * field basis.
    */
-  public static final String FACET_DATE_START = FACET_DATE + ".start";
+  String FACET_DATE_START = FACET_DATE + ".start";
 
   /**
    * Date string indicating the ending point for a date facet range. Can be overridden on a per
    * field basis.
    */
-  public static final String FACET_DATE_END = FACET_DATE + ".end";
+  String FACET_DATE_END = FACET_DATE + ".end";
 
   /**
    * Date Math string indicating the interval of sub-ranges for a date facet range. Can be
    * overridden on a per field basis.
    */
-  public static final String FACET_DATE_GAP = FACET_DATE + ".gap";
+  String FACET_DATE_GAP = FACET_DATE + ".gap";
 
   /**
    * Boolean indicating how counts should be computed if the range between 'start' and 'end' is not
@@ -196,7 +196,7 @@ public interface FacetParams {
    *
    * <p>Can be overridden on a per field basis.
    */
-  public static final String FACET_DATE_HARD_END = FACET_DATE + ".hardend";
+  String FACET_DATE_HARD_END = FACET_DATE + ".hardend";
 
   /**
    * String indicating what "other" ranges should be computed for a date facet range (multi-value).
@@ -205,45 +205,45 @@ public interface FacetParams {
    *
    * @see FacetRangeOther
    */
-  public static final String FACET_DATE_OTHER = FACET_DATE + ".other";
+  String FACET_DATE_OTHER = FACET_DATE + ".other";
 
   /**
    * Multivalued string indicating what rules should be applied to determine when the ranges
    * generated for date faceting should be inclusive or exclusive of their end points.
    *
    * <p>The default value if none are specified is: [lower,upper,edge] <i>(NOTE: This is different
-   * then FACET_RANGE_INCLUDE)</i>
+   * from FACET_RANGE_INCLUDE)</i>
    *
    * <p>Can be overridden on a per field basis.
    *
    * @see FacetRangeInclude
    * @see #FACET_RANGE_INCLUDE
    */
-  public static final String FACET_DATE_INCLUDE = FACET_DATE + ".include";
+  String FACET_DATE_INCLUDE = FACET_DATE + ".include";
 
   /**
    * Any numerical field whose terms the user wants to enumerate over Facet Constraint Counts for
    * selected ranges.
    */
-  public static final String FACET_RANGE = FACET + ".range";
+  String FACET_RANGE = FACET + ".range";
 
   /**
    * Number indicating the starting point for a numerical range facet. Can be overridden on a per
    * field basis.
    */
-  public static final String FACET_RANGE_START = FACET_RANGE + ".start";
+  String FACET_RANGE_START = FACET_RANGE + ".start";
 
   /**
    * Number indicating the ending point for a numerical range facet. Can be overridden on a per
    * field basis.
    */
-  public static final String FACET_RANGE_END = FACET_RANGE + ".end";
+  String FACET_RANGE_END = FACET_RANGE + ".end";
 
   /**
    * Number indicating the interval of sub-ranges for a numerical facet range. Can be overridden on
    * a per field basis.
    */
-  public static final String FACET_RANGE_GAP = FACET_RANGE + ".gap";
+  String FACET_RANGE_GAP = FACET_RANGE + ".gap";
 
   /**
    * Boolean indicating how counts should be computed if the range between 'start' and 'end' is not
@@ -257,13 +257,13 @@ public interface FacetParams {
    *
    * <p>Can be overridden on a per field basis.
    */
-  public static final String FACET_RANGE_HARD_END = FACET_RANGE + ".hardend";
+  String FACET_RANGE_HARD_END = FACET_RANGE + ".hardend";
 
   /**
    * String indicating what "other" ranges should be computed for a numerical range facet
    * (multi-value). Can be overridden on a per field basis.
    */
-  public static final String FACET_RANGE_OTHER = FACET_RANGE + ".other";
+  String FACET_RANGE_OTHER = FACET_RANGE + ".other";
 
   /**
    * Multivalued string indicating what rules should be applied to determine when the ranges
@@ -275,7 +275,7 @@ public interface FacetParams {
    *
    * @see FacetRangeInclude
    */
-  public static final String FACET_RANGE_INCLUDE = FACET_RANGE + ".include";
+  String FACET_RANGE_INCLUDE = FACET_RANGE + ".include";
 
   /**
    * String indicating the method to use to resolve range facets.
@@ -284,23 +284,23 @@ public interface FacetParams {
    *
    * @see FacetRangeMethod
    */
-  public static final String FACET_RANGE_METHOD = FACET_RANGE + ".method";
+  String FACET_RANGE_METHOD = FACET_RANGE + ".method";
 
   /** Any field whose values the user wants to enumerate as explicit intervals of terms. */
-  public static final String FACET_INTERVAL = FACET + ".interval";
+  String FACET_INTERVAL = FACET + ".interval";
 
   /** Set of terms for a single interval to facet on. */
-  public static final String FACET_INTERVAL_SET = FACET_INTERVAL + ".set";
+  String FACET_INTERVAL_SET = FACET_INTERVAL + ".set";
 
   /**
    * A spatial RPT field to generate a 2D "heatmap" (grid of facet counts) on. Just like the other
    * faceting types, this may include a 'key' or local-params to facet multiple times. All
    * parameters with this suffix can be overridden on a per-field basis.
    */
-  public static final String FACET_HEATMAP = "facet.heatmap";
+  String FACET_HEATMAP = "facet.heatmap";
 
   /** The format of the heatmap: either png or ints2D (default). */
-  public static final String FACET_HEATMAP_FORMAT = FACET_HEATMAP + ".format";
+  String FACET_HEATMAP_FORMAT = FACET_HEATMAP + ".format";
 
   /**
    * The region the heatmap should minimally enclose. It defaults to the world if not set. The
@@ -311,12 +311,12 @@ public interface FacetParams {
    * (the first is bottom-left and second is bottom-right, both of which are parsed as points are
    * parsed). OR, any WKT can be provided, and it's bounding box will be taken.
    */
-  public static final String FACET_HEATMAP_GEOM = FACET_HEATMAP + ".geom";
+  String FACET_HEATMAP_GEOM = FACET_HEATMAP + ".geom";
 
   /**
    * Specify the heatmap grid level explicitly, instead of deriving it via distErr or distErrPct.
    */
-  public static final String FACET_HEATMAP_LEVEL = FACET_HEATMAP + ".gridLevel";
+  String FACET_HEATMAP_LEVEL = FACET_HEATMAP + ".gridLevel";
 
   /**
    * Used to determine the heatmap grid level to compute, defaulting to 0.15. It has the same
@@ -324,7 +324,7 @@ public interface FacetParams {
    * fraction (not a %) of the radius of the shape that grid squares must fit into without
    * exceeding. &gt; 0 and &lt;= 0.5. Mutually exclusive with distErr &amp; gridLevel.
    */
-  public static final String FACET_HEATMAP_DIST_ERR_PCT = FACET_HEATMAP + ".distErrPct";
+  String FACET_HEATMAP_DIST_ERR_PCT = FACET_HEATMAP + ".distErrPct";
 
   /**
    * Used to determine the heatmap grid level to compute (optional). It has the same interpretation
@@ -334,13 +334,13 @@ public interface FacetParams {
    * grid levels translate to. This can in turn be used with knowledge of the size of 'bbox' to get
    * a target minimum number of grid cells. Mutually exclusive with distErrPct &amp; gridLevel.
    */
-  public static final String FACET_HEATMAP_DIST_ERR = FACET_HEATMAP + ".distErr";
+  String FACET_HEATMAP_DIST_ERR = FACET_HEATMAP + ".distErr";
 
   /**
    * The maximum number of cells (grid squares) the client is willing to handle. If this limit would
    * be exceeded, we throw an error instead. Defaults to 100k.
    */
-  public static final String FACET_HEATMAP_MAX_CELLS = FACET_HEATMAP + ".maxCells";
+  String FACET_HEATMAP_MAX_CELLS = FACET_HEATMAP + ".maxCells";
 
   /**
    * An enumeration of the legal values for {@link #FACET_RANGE_OTHER} and {@link #FACET_DATE_OTHER}
@@ -357,7 +357,7 @@ public interface FacetParams {
    * @see #FACET_RANGE_OTHER
    * @see #FACET_DATE_OTHER
    */
-  public enum FacetRangeOther {
+  enum FacetRangeOther {
     BEFORE,
     AFTER,
     BETWEEN,
@@ -399,7 +399,7 @@ public interface FacetParams {
    * @see #FACET_DATE_INCLUDE
    * @see #FACET_RANGE_INCLUDE
    */
-  public enum FacetRangeInclude {
+  enum FacetRangeInclude {
     ALL,
     LOWER,
     UPPER,
@@ -454,7 +454,7 @@ public interface FacetParams {
    *
    * @see #FACET_RANGE_METHOD
    */
-  public enum FacetRangeMethod {
+  enum FacetRangeMethod {
     FILTER,
     DV;
 
diff --git a/solr/solrj/src/java/org/apache/solr/common/params/GroupParams.java b/solr/solrj/src/java/org/apache/solr/common/params/GroupParams.java
index 43d5380a7b4..14e1cc49d5f 100644
--- a/solr/solrj/src/java/org/apache/solr/common/params/GroupParams.java
+++ b/solr/solrj/src/java/org/apache/solr/common/params/GroupParams.java
@@ -18,31 +18,31 @@ package org.apache.solr.common.params;
 
 /** Group parameters */
 public interface GroupParams {
-  public static final String GROUP = "group";
+  String GROUP = "group";
 
-  public static final String GROUP_QUERY = GROUP + ".query";
-  public static final String GROUP_FIELD = GROUP + ".field";
-  public static final String GROUP_FUNC = GROUP + ".func";
-  public static final String GROUP_SORT = GROUP + ".sort";
+  String GROUP_QUERY = GROUP + ".query";
+  String GROUP_FIELD = GROUP + ".field";
+  String GROUP_FUNC = GROUP + ".func";
+  String GROUP_SORT = GROUP + ".sort";
 
   /** the limit for the number of documents in each group */
-  public static final String GROUP_LIMIT = GROUP + ".limit";
+  String GROUP_LIMIT = GROUP + ".limit";
 
   /** the offset for the doclist of each group */
-  public static final String GROUP_OFFSET = GROUP + ".offset";
+  String GROUP_OFFSET = GROUP + ".offset";
 
   /** treat the first group result as the main result. true/false */
-  public static final String GROUP_MAIN = GROUP + ".main";
+  String GROUP_MAIN = GROUP + ".main";
 
   /** treat the first group result as the main result. true/false */
-  public static final String GROUP_FORMAT = GROUP + ".format";
+  String GROUP_FORMAT = GROUP + ".format";
 
   /**
    * Whether to cache the first pass search (doc ids and score) for the second pass search. Also
    * defines the maximum size of the group cache relative to maxdoc in a percentage. Values can be a
    * positive integer, from 0 till 100. A value of 0 will disable the group cache. The default is 0.
    */
-  public static final String GROUP_CACHE_PERCENTAGE = GROUP + ".cache.percent";
+  String GROUP_CACHE_PERCENTAGE = GROUP + ".cache.percent";
 
   // Note: Since you can supply multiple fields to group on, but only have a facets for the whole
   // result. It only makes sense to me to support these parameters for the first group.
@@ -51,22 +51,22 @@ public interface GroupParams {
    * UNGROUPED) or on the groups (a.k.a. GROUPED). The docSet will only the most relevant documents
    * per group. It is if you query for everything with group.limit=1
    */
-  public static final String GROUP_TRUNCATE = GROUP + ".truncate";
+  String GROUP_TRUNCATE = GROUP + ".truncate";
 
   /** Whether the group count should be included in the response. */
-  public static final String GROUP_TOTAL_COUNT = GROUP + ".ngroups";
+  String GROUP_TOTAL_COUNT = GROUP + ".ngroups";
 
   /** Whether to compute grouped facets based on the first specified group. */
-  public static final String GROUP_FACET = GROUP + ".facet";
+  String GROUP_FACET = GROUP + ".facet";
 
   /** Retrieve the top search groups (top group values) from the shards being queried. */
-  public static final String GROUP_DISTRIBUTED_FIRST = GROUP + ".distributed.first";
+  String GROUP_DISTRIBUTED_FIRST = GROUP + ".distributed.first";
 
   /**
    * Retrieve the top groups from the shards being queries based on the specified search groups in
    * the {@link #GROUP_DISTRIBUTED_TOPGROUPS_PREFIX} parameters.
    */
-  public static final String GROUP_DISTRIBUTED_SECOND = GROUP + ".distributed.second";
+  String GROUP_DISTRIBUTED_SECOND = GROUP + ".distributed.second";
 
-  public static final String GROUP_DISTRIBUTED_TOPGROUPS_PREFIX = GROUP + ".topgroups.";
+  String GROUP_DISTRIBUTED_TOPGROUPS_PREFIX = GROUP + ".topgroups.";
 }
diff --git a/solr/solrj/src/java/org/apache/solr/common/params/HighlightParams.java b/solr/solrj/src/java/org/apache/solr/common/params/HighlightParams.java
index e0ce04b08f2..42625a605d3 100644
--- a/solr/solrj/src/java/org/apache/solr/common/params/HighlightParams.java
+++ b/solr/solrj/src/java/org/apache/solr/common/params/HighlightParams.java
@@ -21,10 +21,10 @@ package org.apache.solr.common.params;
  */
 public interface HighlightParams {
   // primary
-  public static final String HIGHLIGHT = "hl";
-  public static final String METHOD = HIGHLIGHT + ".method"; // original|fastVector|postings|unified
-  public static final String FIELDS = HIGHLIGHT + ".fl";
-  public static final String SNIPPETS = HIGHLIGHT + ".snippets";
+  String HIGHLIGHT = "hl";
+  String METHOD = HIGHLIGHT + ".method"; // original|fastVector|postings|unified
+  String FIELDS = HIGHLIGHT + ".fl";
+  String SNIPPETS = HIGHLIGHT + ".snippets";
 
   //    KEY:
   // OH = (original) Highlighter   (AKA the standard Highlighter)
@@ -32,71 +32,66 @@ public interface HighlightParams {
   // UH = UnifiedHighlighter (evolved from PostingsHighlighter)
 
   // query interpretation
-  public static final String Q = HIGHLIGHT + ".q"; // all
-  public static final String QPARSER = HIGHLIGHT + ".qparser"; // all
-  public static final String FIELD_MATCH = HIGHLIGHT + ".requireFieldMatch"; // OH, FVH, UH
-  public static final String QUERY_FIELD_PATTERN = HIGHLIGHT + ".queryFieldPattern"; // UH
-  public static final String USE_PHRASE_HIGHLIGHTER =
-      HIGHLIGHT + ".usePhraseHighlighter"; // OH, FVH, UH
-  public static final String HIGHLIGHT_MULTI_TERM = HIGHLIGHT + ".highlightMultiTerm"; // all
+  String Q = HIGHLIGHT + ".q"; // all
+  String QPARSER = HIGHLIGHT + ".qparser"; // all
+  String FIELD_MATCH = HIGHLIGHT + ".requireFieldMatch"; // OH, FVH, UH
+  String QUERY_FIELD_PATTERN = HIGHLIGHT + ".queryFieldPattern"; // UH
+  String USE_PHRASE_HIGHLIGHTER = HIGHLIGHT + ".usePhraseHighlighter"; // OH, FVH, UH
+  String HIGHLIGHT_MULTI_TERM = HIGHLIGHT + ".highlightMultiTerm"; // all
 
   // if no snippets...
-  public static final String DEFAULT_SUMMARY = HIGHLIGHT + ".defaultSummary"; // UH
-  public static final String ALTERNATE_FIELD = HIGHLIGHT + ".alternateField"; // OH, FVH
-  public static final String ALTERNATE_FIELD_LENGTH =
-      HIGHLIGHT + ".maxAlternateFieldLength"; // OH, FVH
-  public static final String HIGHLIGHT_ALTERNATE = HIGHLIGHT + ".highlightAlternate"; // OH, FVH
+  String DEFAULT_SUMMARY = HIGHLIGHT + ".defaultSummary"; // UH
+  String ALTERNATE_FIELD = HIGHLIGHT + ".alternateField"; // OH, FVH
+  String ALTERNATE_FIELD_LENGTH = HIGHLIGHT + ".maxAlternateFieldLength"; // OH, FVH
+  String HIGHLIGHT_ALTERNATE = HIGHLIGHT + ".highlightAlternate"; // OH, FVH
 
   // sizing
-  public static final String FRAGSIZE = HIGHLIGHT + ".fragsize"; // OH, FVH, UH
-  public static final String FRAGSIZEISMINIMUM = HIGHLIGHT + ".fragsizeIsMinimum"; // UH
-  public static final String FRAGALIGNRATIO = HIGHLIGHT + ".fragAlignRatio"; // UH
-  public static final String FRAGMENTER = HIGHLIGHT + ".fragmenter"; // OH
-  public static final String INCREMENT = HIGHLIGHT + ".increment"; // OH
-  public static final String REGEX = "regex"; // OH
-  public static final String SLOP = HIGHLIGHT + "." + REGEX + ".slop"; // OH
-  public static final String PATTERN = HIGHLIGHT + "." + REGEX + ".pattern"; // OH
-  public static final String MAX_RE_CHARS = HIGHLIGHT + "." + REGEX + ".maxAnalyzedChars"; // OH
-  public static final String BOUNDARY_SCANNER = HIGHLIGHT + ".boundaryScanner"; // FVH
-  public static final String BS_MAX_SCAN = HIGHLIGHT + ".bs.maxScan"; // FVH
-  public static final String BS_CHARS = HIGHLIGHT + ".bs.chars"; // FVH
-  public static final String BS_TYPE = HIGHLIGHT + ".bs.type"; // FVH, UH
-  public static final String BS_LANGUAGE = HIGHLIGHT + ".bs.language"; // FVH, UH
-  public static final String BS_COUNTRY = HIGHLIGHT + ".bs.country"; // FVH, UH
-  public static final String BS_VARIANT = HIGHLIGHT + ".bs.variant"; // FVH, UH
-  public static final String BS_SEP = HIGHLIGHT + ".bs.separator"; // UH
+  String FRAGSIZE = HIGHLIGHT + ".fragsize"; // OH, FVH, UH
+  String FRAGSIZEISMINIMUM = HIGHLIGHT + ".fragsizeIsMinimum"; // UH
+  String FRAGALIGNRATIO = HIGHLIGHT + ".fragAlignRatio"; // UH
+  String FRAGMENTER = HIGHLIGHT + ".fragmenter"; // OH
+  String INCREMENT = HIGHLIGHT + ".increment"; // OH
+  String REGEX = "regex"; // OH
+  String SLOP = HIGHLIGHT + "." + REGEX + ".slop"; // OH
+  String PATTERN = HIGHLIGHT + "." + REGEX + ".pattern"; // OH
+  String MAX_RE_CHARS = HIGHLIGHT + "." + REGEX + ".maxAnalyzedChars"; // OH
+  String BOUNDARY_SCANNER = HIGHLIGHT + ".boundaryScanner"; // FVH
+  String BS_MAX_SCAN = HIGHLIGHT + ".bs.maxScan"; // FVH
+  String BS_CHARS = HIGHLIGHT + ".bs.chars"; // FVH
+  String BS_TYPE = HIGHLIGHT + ".bs.type"; // FVH, UH
+  String BS_LANGUAGE = HIGHLIGHT + ".bs.language"; // FVH, UH
+  String BS_COUNTRY = HIGHLIGHT + ".bs.country"; // FVH, UH
+  String BS_VARIANT = HIGHLIGHT + ".bs.variant"; // FVH, UH
+  String BS_SEP = HIGHLIGHT + ".bs.separator"; // UH
 
   // formatting
-  public static final String FORMATTER = HIGHLIGHT + ".formatter"; // OH
-  public static final String ENCODER = HIGHLIGHT + ".encoder"; // all
-  public static final String MERGE_CONTIGUOUS_FRAGMENTS = HIGHLIGHT + ".mergeContiguous"; // OH
-  public static final String SIMPLE = "simple"; // OH
-  public static final String SIMPLE_PRE = HIGHLIGHT + "." + SIMPLE + ".pre"; // OH
-  public static final String SIMPLE_POST = HIGHLIGHT + "." + SIMPLE + ".post"; // OH
-  public static final String FRAGMENTS_BUILDER = HIGHLIGHT + ".fragmentsBuilder"; // FVH
-  public static final String TAG_PRE = HIGHLIGHT + ".tag.pre"; // FVH, UH
-  public static final String TAG_POST = HIGHLIGHT + ".tag.post"; // FVH, UH
-  public static final String TAG_ELLIPSIS = HIGHLIGHT + ".tag.ellipsis"; // FVH, UH
-  public static final String MULTI_VALUED_SEPARATOR =
-      HIGHLIGHT + ".multiValuedSeparatorChar"; // FVH
+  String FORMATTER = HIGHLIGHT + ".formatter"; // OH
+  String ENCODER = HIGHLIGHT + ".encoder"; // all
+  String MERGE_CONTIGUOUS_FRAGMENTS = HIGHLIGHT + ".mergeContiguous"; // OH
+  String SIMPLE = "simple"; // OH
+  String SIMPLE_PRE = HIGHLIGHT + "." + SIMPLE + ".pre"; // OH
+  String SIMPLE_POST = HIGHLIGHT + "." + SIMPLE + ".post"; // OH
+  String FRAGMENTS_BUILDER = HIGHLIGHT + ".fragmentsBuilder"; // FVH
+  String TAG_PRE = HIGHLIGHT + ".tag.pre"; // FVH, UH
+  String TAG_POST = HIGHLIGHT + ".tag.post"; // FVH, UH
+  String TAG_ELLIPSIS = HIGHLIGHT + ".tag.ellipsis"; // FVH, UH
+  String MULTI_VALUED_SEPARATOR = HIGHLIGHT + ".multiValuedSeparatorChar"; // FVH
 
   // ordering
-  public static final String PRESERVE_MULTI = HIGHLIGHT + ".preserveMulti"; // OH
-  public static final String FRAG_LIST_BUILDER = HIGHLIGHT + ".fragListBuilder"; // FVH
-  public static final String SCORE = "score"; // UH
-  public static final String SCORE_K1 = HIGHLIGHT + "." + SCORE + ".k1"; // UH
-  public static final String SCORE_B = HIGHLIGHT + "." + SCORE + ".b"; // UH
-  public static final String SCORE_PIVOT = HIGHLIGHT + "." + SCORE + ".pivot"; // UH
+  String PRESERVE_MULTI = HIGHLIGHT + ".preserveMulti"; // OH
+  String FRAG_LIST_BUILDER = HIGHLIGHT + ".fragListBuilder"; // FVH
+  String SCORE = "score"; // UH
+  String SCORE_K1 = HIGHLIGHT + "." + SCORE + ".k1"; // UH
+  String SCORE_B = HIGHLIGHT + "." + SCORE + ".b"; // UH
+  String SCORE_PIVOT = HIGHLIGHT + "." + SCORE + ".pivot"; // UH
 
   // misc
-  public static final String MAX_CHARS = HIGHLIGHT + ".maxAnalyzedChars"; // all
-  public static final String PAYLOADS = HIGHLIGHT + ".payloads"; // OH
-  public static final String MAX_MULTIVALUED_TO_EXAMINE =
-      HIGHLIGHT + ".maxMultiValuedToExamine"; // OH
-  public static final String MAX_MULTIVALUED_TO_MATCH = HIGHLIGHT + ".maxMultiValuedToMatch"; // OH
-  public static final String PHRASE_LIMIT = HIGHLIGHT + ".phraseLimit"; // FVH
-  public static final String OFFSET_SOURCE = HIGHLIGHT + ".offsetSource"; // UH
-  public static final String CACHE_FIELD_VAL_CHARS_THRESHOLD =
-      HIGHLIGHT + ".cacheFieldValCharsThreshold"; // UH
-  public static final String WEIGHT_MATCHES = HIGHLIGHT + ".weightMatches"; // UH
+  String MAX_CHARS = HIGHLIGHT + ".maxAnalyzedChars"; // all
+  String PAYLOADS = HIGHLIGHT + ".payloads"; // OH
+  String MAX_MULTIVALUED_TO_EXAMINE = HIGHLIGHT + ".maxMultiValuedToExamine"; // OH
+  String MAX_MULTIVALUED_TO_MATCH = HIGHLIGHT + ".maxMultiValuedToMatch"; // OH
+  String PHRASE_LIMIT = HIGHLIGHT + ".phraseLimit"; // FVH
+  String OFFSET_SOURCE = HIGHLIGHT + ".offsetSource"; // UH
+  String CACHE_FIELD_VAL_CHARS_THRESHOLD = HIGHLIGHT + ".cacheFieldValCharsThreshold"; // UH
+  String WEIGHT_MATCHES = HIGHLIGHT + ".weightMatches"; // UH
 }
diff --git a/solr/solrj/src/java/org/apache/solr/common/params/MoreLikeThisParams.java b/solr/solrj/src/java/org/apache/solr/common/params/MoreLikeThisParams.java
index 8c98012e368..72901c28a3f 100644
--- a/solr/solrj/src/java/org/apache/solr/common/params/MoreLikeThisParams.java
+++ b/solr/solrj/src/java/org/apache/solr/common/params/MoreLikeThisParams.java
@@ -20,39 +20,38 @@ import java.util.Locale;
 
 /** Params for {@code MoreLikeThisHandler}. */
 public interface MoreLikeThisParams {
-  public static final String MLT = "mlt";
+  String MLT = "mlt";
 
-  public static final String PREFIX = "mlt.";
+  String PREFIX = "mlt.";
 
-  public static final String SIMILARITY_FIELDS = PREFIX + "fl";
-  public static final String MIN_TERM_FREQ = PREFIX + "mintf";
-  public static final String MAX_DOC_FREQ = PREFIX + "maxdf";
-  public static final String MAX_DOC_FREQ_PCT = PREFIX + "maxdfpct";
-  public static final String MIN_DOC_FREQ = PREFIX + "mindf";
-  public static final String MIN_WORD_LEN = PREFIX + "minwl";
-  public static final String MAX_WORD_LEN = PREFIX + "maxwl";
-  public static final String MAX_QUERY_TERMS = PREFIX + "maxqt";
-  public static final String MAX_NUM_TOKENS_PARSED = PREFIX + "maxntp";
-  public static final String BOOST = PREFIX + "boost"; // boost or not?
-  public static final String QF = PREFIX + "qf"; // boosting applied to mlt fields
+  String SIMILARITY_FIELDS = PREFIX + "fl";
+  String MIN_TERM_FREQ = PREFIX + "mintf";
+  String MAX_DOC_FREQ = PREFIX + "maxdf";
+  String MAX_DOC_FREQ_PCT = PREFIX + "maxdfpct";
+  String MIN_DOC_FREQ = PREFIX + "mindf";
+  String MIN_WORD_LEN = PREFIX + "minwl";
+  String MAX_WORD_LEN = PREFIX + "maxwl";
+  String MAX_QUERY_TERMS = PREFIX + "maxqt";
+  String MAX_NUM_TOKENS_PARSED = PREFIX + "maxntp";
+  String BOOST = PREFIX + "boost"; // boost or not?
+  String QF = PREFIX + "qf"; // boosting applied to mlt fields
 
   // the /mlt request handler uses 'rows'
-  public static final String DOC_COUNT = PREFIX + "count";
+  String DOC_COUNT = PREFIX + "count";
 
   // Do you want to include the original document in the results or not
-  public static final String MATCH_INCLUDE = PREFIX + "match.include";
+  String MATCH_INCLUDE = PREFIX + "match.include";
 
   // If multiple docs are matched in the query, what offset do you want?
-  public static final String MATCH_OFFSET = PREFIX + "match.offset";
+  String MATCH_OFFSET = PREFIX + "match.offset";
 
   // Do you want to include the original document in the results or not
-  public static final String INTERESTING_TERMS =
-      PREFIX + "interestingTerms"; // false,details,(list or true)
+  String INTERESTING_TERMS = PREFIX + "interestingTerms"; // false,details,(list or true)
 
   // the default doc count
-  public static final int DEFAULT_DOC_COUNT = 5;
+  int DEFAULT_DOC_COUNT = 5;
 
-  public enum TermStyle {
+  enum TermStyle {
     NONE,
     LIST,
     DETAILS;
diff --git a/solr/solrj/src/java/org/apache/solr/common/params/SimpleParams.java b/solr/solrj/src/java/org/apache/solr/common/params/SimpleParams.java
index a921d251aca..6d9d5651cbd 100644
--- a/solr/solrj/src/java/org/apache/solr/common/params/SimpleParams.java
+++ b/solr/solrj/src/java/org/apache/solr/common/params/SimpleParams.java
@@ -19,38 +19,38 @@ package org.apache.solr.common.params;
 /** Parameters used by the SimpleQParser. */
 public interface SimpleParams {
   /** Query fields and boosts. */
-  public static String QF = "qf";
+  String QF = "qf";
 
   /** Override the currently enabled/disabled query operators. */
-  public static String QO = "q.operators";
+  String QO = "q.operators";
 
   /** Enables {@code AND} operator (+) */
-  public static final String AND_OPERATOR = "AND";
+  String AND_OPERATOR = "AND";
 
   /** Enables {@code NOT} operator (-) */
-  public static final String NOT_OPERATOR = "NOT";
+  String NOT_OPERATOR = "NOT";
 
   /** Enables {@code OR} operator (|) */
-  public static final String OR_OPERATOR = "OR";
+  String OR_OPERATOR = "OR";
 
   /** Enables {@code PREFIX} operator (*) */
-  public static final String PREFIX_OPERATOR = "PREFIX";
+  String PREFIX_OPERATOR = "PREFIX";
 
   /** Enables {@code PHRASE} operator (") */
-  public static final String PHRASE_OPERATOR = "PHRASE";
+  String PHRASE_OPERATOR = "PHRASE";
 
   /** Enables {@code PRECEDENCE} operators: {@code (} and {@code )} */
-  public static final String PRECEDENCE_OPERATORS = "PRECEDENCE";
+  String PRECEDENCE_OPERATORS = "PRECEDENCE";
 
   /** Enables {@code ESCAPE} operator (\) */
-  public static final String ESCAPE_OPERATOR = "ESCAPE";
+  String ESCAPE_OPERATOR = "ESCAPE";
 
   /** Enables {@code WHITESPACE} operators: ' ' '\n' '\r' '\t' */
-  public static final String WHITESPACE_OPERATOR = "WHITESPACE";
+  String WHITESPACE_OPERATOR = "WHITESPACE";
 
   /** Enables {@code FUZZY} operator (~) */
-  public static final String FUZZY_OPERATOR = "FUZZY";
+  String FUZZY_OPERATOR = "FUZZY";
 
   /** Enables {@code NEAR} operator (~) */
-  public static final String NEAR_OPERATOR = "NEAR";
+  String NEAR_OPERATOR = "NEAR";
 }
diff --git a/solr/solrj/src/java/org/apache/solr/common/params/SolrParams.java b/solr/solrj/src/java/org/apache/solr/common/params/SolrParams.java
index e06cc4cd7cb..0f0e0f59676 100644
--- a/solr/solrj/src/java/org/apache/solr/common/params/SolrParams.java
+++ b/solr/solrj/src/java/org/apache/solr/common/params/SolrParams.java
@@ -193,23 +193,12 @@ public abstract class SolrParams
    * Returns the Boolean value of the field param, or the value for param, or null if neither is
    * set. Use this method only when you want to be explicit about absence of a value (<code>null
    * </code>) vs the default value <code>false</code>.
-   *
-   * @see #getFieldBool(String, String, boolean)
-   * @see #getPrimitiveFieldBool(String, String)
    */
   public Boolean getFieldBool(String field, String param) {
     String val = getFieldParam(field, param);
     return val == null ? null : StrUtils.parseBool(val);
   }
 
-  /**
-   * Returns the boolean value of the field param, or the value for param or the default value of
-   * boolean - <code>false</code>
-   */
-  public boolean getPrimitiveFieldBool(String field, String param) {
-    return getFieldBool(field, param, false);
-  }
-
   /**
    * Returns the boolean value of the field param, or the value for param, or def if neither is set.
    */
@@ -360,7 +349,6 @@ public abstract class SolrParams
    * about absence of a value (<code>null</code>) vs the default value zero (<code>0.0f</code>).
    *
    * @see #getFieldFloat(String, String, float)
-   * @see #getPrimitiveFieldFloat(String, String)
    */
   public Float getFieldFloat(String field, String param) {
     String val = getFieldParam(field, param);
@@ -371,14 +359,6 @@ public abstract class SolrParams
     }
   }
 
-  /**
-   * Returns the float value of the field param or the value for param or the default value for
-   * float - zero (<code>0.0f</code>)
-   */
-  public float getPrimitiveFieldFloat(String field, String param) {
-    return getFieldFloat(field, param, 0.0f);
-  }
-
   /**
    * Returns the float value of the field param, or the value for param, or def if neither is set.
    */
diff --git a/solr/solrj/src/java/org/apache/solr/common/params/SpatialParams.java b/solr/solrj/src/java/org/apache/solr/common/params/SpatialParams.java
index 9fdbe175d61..32980b6014a 100644
--- a/solr/solrj/src/java/org/apache/solr/common/params/SpatialParams.java
+++ b/solr/solrj/src/java/org/apache/solr/common/params/SpatialParams.java
@@ -18,17 +18,17 @@ package org.apache.solr.common.params;
 
 /** */
 public interface SpatialParams {
-  public static final String POINT = "pt";
-  public static final String DISTANCE = "d";
+  String POINT = "pt";
+  String DISTANCE = "d";
   // the field that contains the points we are measuring from "pt"
-  public static final String FIELD = "sfield";
+  String FIELD = "sfield";
 
   /** km - kilometers mi - miles */
-  public static final String UNITS = "units";
+  String UNITS = "units";
 
   /** The distance measure to use. */
-  public static final String MEASURE = "meas";
+  String MEASURE = "meas";
 
   /** The radius of the sphere to use to in calculating spherical distances like Haversine */
-  public static final String SPHERE_RADIUS = "sphere_radius";
+  String SPHERE_RADIUS = "sphere_radius";
 }
diff --git a/solr/solrj/src/java/org/apache/solr/common/params/SpellingParams.java b/solr/solrj/src/java/org/apache/solr/common/params/SpellingParams.java
index db03b003098..aff99191cf6 100644
--- a/solr/solrj/src/java/org/apache/solr/common/params/SpellingParams.java
+++ b/solr/solrj/src/java/org/apache/solr/common/params/SpellingParams.java
@@ -23,13 +23,13 @@ package org.apache.solr.common.params;
  */
 public interface SpellingParams {
 
-  public static final String SPELLCHECK_PREFIX = "spellcheck.";
+  String SPELLCHECK_PREFIX = "spellcheck.";
 
   /**
    * The name of the dictionary to be used for giving the suggestion for a request. The value for
    * this parameter is configured in solrconfig.xml
    */
-  public static final String SPELLCHECK_DICT = SPELLCHECK_PREFIX + "dictionary";
+  String SPELLCHECK_DICT = SPELLCHECK_PREFIX + "dictionary";
 
   /**
    * The count of suggestions to return for each query term not in the index and/or dictionary.
@@ -37,7 +37,7 @@ public interface SpellingParams {
    * <p>If this parameter is absent in the request then only one suggestion is returned. If it is
    * more than one then a maximum of given suggestions are returned for each token in the query.
    */
-  public static final String SPELLCHECK_COUNT = SPELLCHECK_PREFIX + "count";
+  String SPELLCHECK_COUNT = SPELLCHECK_PREFIX + "count";
 
   /**
    * The count of suggestions to return for each query term existing in the index and/or dictionary.
@@ -45,8 +45,7 @@ public interface SpellingParams {
    * <p>If this parameter is absent in the request then no suggestions are generated. This parameter
    * allows for receiving alternative terms to use in context-sensitive spelling corrections.
    */
-  public static final String SPELLCHECK_ALTERNATIVE_TERM_COUNT =
-      SPELLCHECK_PREFIX + "alternativeTermCount";
+  String SPELLCHECK_ALTERNATIVE_TERM_COUNT = SPELLCHECK_PREFIX + "alternativeTermCount";
 
   /**
    * The maximum number of hits the request can return in order to both generate spelling
@@ -65,16 +64,14 @@ public interface SpellingParams {
    * zero is useful for creating "did-you-mean" suggestions for queries that return a low number of
    * hits.
    */
-  public static final String SPELLCHECK_MAX_RESULTS_FOR_SUGGEST =
-      SPELLCHECK_PREFIX + "maxResultsForSuggest";
+  String SPELLCHECK_MAX_RESULTS_FOR_SUGGEST = SPELLCHECK_PREFIX + "maxResultsForSuggest";
 
   /**
    * To be used when {@link SpellingParams#SPELLCHECK_MAX_RESULTS_FOR_SUGGEST} is expressed as a
    * fractional percentage. Specify a filter query whose result count is used to determine the
    * maximum number of documents.
    */
-  public static final String SPELLCHECK_MAX_RESULTS_FOR_SUGGEST_FQ =
-      SPELLCHECK_MAX_RESULTS_FOR_SUGGEST + ".fq";
+  String SPELLCHECK_MAX_RESULTS_FOR_SUGGEST_FQ = SPELLCHECK_MAX_RESULTS_FOR_SUGGEST + ".fq";
 
   /**
    * When this parameter is set to true and the misspelled word exists in the user field, only words
@@ -83,7 +80,7 @@ public interface SpellingParams {
    *
    * <p><b>This is applicable only for dictionaries built from Solr fields.</b>
    */
-  public static final String SPELLCHECK_ONLY_MORE_POPULAR = SPELLCHECK_PREFIX + "onlyMorePopular";
+  String SPELLCHECK_ONLY_MORE_POPULAR = SPELLCHECK_PREFIX + "onlyMorePopular";
 
   /**
    * Whether to use the extended response format, which is more complicated but richer. Returns the
@@ -92,29 +89,29 @@ public interface SpellingParams {
    *
    * <p><b>This is applicable only for dictionaries built from Solr fields.</b>
    */
-  public static final String SPELLCHECK_EXTENDED_RESULTS = SPELLCHECK_PREFIX + "extendedResults";
+  String SPELLCHECK_EXTENDED_RESULTS = SPELLCHECK_PREFIX + "extendedResults";
 
   /**
    * Use the value for this parameter as the query to spell check.
    *
    * <p>This parameter is <b>optional</b>. If absent, then the q parameter is used.
    */
-  public static final String SPELLCHECK_Q = SPELLCHECK_PREFIX + "q";
+  String SPELLCHECK_Q = SPELLCHECK_PREFIX + "q";
 
   /** Whether to build the index or not. Optional and false by default. */
-  public static final String SPELLCHECK_BUILD = SPELLCHECK_PREFIX + "build";
+  String SPELLCHECK_BUILD = SPELLCHECK_PREFIX + "build";
 
   /** Whether to reload the index. Optional and false by default. */
-  public static final String SPELLCHECK_RELOAD = SPELLCHECK_PREFIX + "reload";
+  String SPELLCHECK_RELOAD = SPELLCHECK_PREFIX + "reload";
 
   /** Take the top suggestion for each token and create a new query from it */
-  public static final String SPELLCHECK_COLLATE = SPELLCHECK_PREFIX + "collate";
+  String SPELLCHECK_COLLATE = SPELLCHECK_PREFIX + "collate";
 
   /**
    * The maximum number of collations to return. Default=1. Ignored if "spellcheck.collate" is
    * false.
    */
-  public static final String SPELLCHECK_MAX_COLLATIONS = SPELLCHECK_PREFIX + "maxCollations";
+  String SPELLCHECK_MAX_COLLATIONS = SPELLCHECK_PREFIX + "maxCollations";
 
   /**
    * The maximum number of collations to test by querying against the index. When testing, the
@@ -122,16 +119,14 @@ public interface SpellingParams {
    * set to zero, does not test for hits before returning collations (returned collations may result
    * in zero hits). Default=0. Ignored of "spellcheck.collate" is false.
    */
-  public static final String SPELLCHECK_MAX_COLLATION_TRIES =
-      SPELLCHECK_PREFIX + "maxCollationTries";
+  String SPELLCHECK_MAX_COLLATION_TRIES = SPELLCHECK_PREFIX + "maxCollationTries";
 
   /**
    * The maximum number of word correction combinations to rank and evaluate prior to deciding which
    * collation candidates to test against the index. This is a performance safety-net in cases a
    * user enters a query with many misspelled words. The default is 10,000 combinations.
    */
-  public static final String SPELLCHECK_MAX_COLLATION_EVALUATIONS =
-      SPELLCHECK_PREFIX + "maxCollationEvaluations";
+  String SPELLCHECK_MAX_COLLATION_EVALUATIONS = SPELLCHECK_PREFIX + "maxCollationEvaluations";
 
   /**
    * For use with {@link SpellingParams#SPELLCHECK_MAX_COLLATION_TRIES} and {@link
@@ -146,8 +141,7 @@ public interface SpellingParams {
    * SpellingParams#SPELLCHECK_COLLATE_EXTENDED_RESULTS} is FALSE, this optimization is always
    * performed.
    */
-  public static final String SPELLCHECK_COLLATE_MAX_COLLECT_DOCS =
-      SPELLCHECK_PREFIX + "collateMaxCollectDocs";
+  String SPELLCHECK_COLLATE_MAX_COLLECT_DOCS = SPELLCHECK_PREFIX + "collateMaxCollectDocs";
 
   /**
    * Whether to use the Extended Results Format for collations. Includes "before&gt;after" pairs to
@@ -158,8 +152,7 @@ public interface SpellingParams {
    * <p>Note: that if {@link SpellingParams#SPELLCHECK_COLLATE_MAX_COLLECT_DOCS} is set to a value
    * greater than 0, then the hit counts returned by this will be estimated.
    */
-  public static final String SPELLCHECK_COLLATE_EXTENDED_RESULTS =
-      SPELLCHECK_PREFIX + "collateExtendedResults";
+  String SPELLCHECK_COLLATE_EXTENDED_RESULTS = SPELLCHECK_PREFIX + "collateExtendedResults";
 
   /**
    * For use with {@link SpellingParams#SPELLCHECK_MAX_COLLATION_TRIES}, use this to override any
@@ -167,9 +160,8 @@ public interface SpellingParams {
    * "mm=1" but it is preferred to test collations with "mm=100%", then use
    * "spellcheck.collateParam.mm=100%".
    */
-  public static final String SPELLCHECK_COLLATE_PARAM_OVERRIDE =
-      SPELLCHECK_PREFIX + "collateParam.";
+  String SPELLCHECK_COLLATE_PARAM_OVERRIDE = SPELLCHECK_PREFIX + "collateParam.";
 
   /** Certain spelling implementations may allow for an accuracy setting. */
-  public static final String SPELLCHECK_ACCURACY = SPELLCHECK_PREFIX + "accuracy";
+  String SPELLCHECK_ACCURACY = SPELLCHECK_PREFIX + "accuracy";
 }
diff --git a/solr/solrj/src/java/org/apache/solr/common/params/StatsParams.java b/solr/solrj/src/java/org/apache/solr/common/params/StatsParams.java
index 0c747e9f338..8b1031532f0 100644
--- a/solr/solrj/src/java/org/apache/solr/common/params/StatsParams.java
+++ b/solr/solrj/src/java/org/apache/solr/common/params/StatsParams.java
@@ -18,8 +18,8 @@ package org.apache.solr.common.params;
 
 /** Stats Parameters */
 public interface StatsParams {
-  public static final String STATS = "stats";
-  public static final String STATS_FIELD = STATS + ".field";
-  public static final String STATS_FACET = STATS + ".facet";
-  public static final String STATS_CALC_DISTINCT = STATS + ".calcdistinct";
+  String STATS = "stats";
+  String STATS_FIELD = STATS + ".field";
+  String STATS_FACET = STATS + ".facet";
+  String STATS_CALC_DISTINCT = STATS + ".calcdistinct";
 }
diff --git a/solr/solrj/src/java/org/apache/solr/common/params/TermVectorParams.java b/solr/solrj/src/java/org/apache/solr/common/params/TermVectorParams.java
index a26ba14d970..aacc82b911e 100644
--- a/solr/solrj/src/java/org/apache/solr/common/params/TermVectorParams.java
+++ b/solr/solrj/src/java/org/apache/solr/common/params/TermVectorParams.java
@@ -19,32 +19,32 @@ package org.apache.solr.common.params;
 /** */
 public interface TermVectorParams {
 
-  public static final String TV_PREFIX = "tv.";
+  String TV_PREFIX = "tv.";
 
   /** Return Term Frequency info */
-  public static final String TF = TV_PREFIX + "tf";
+  String TF = TV_PREFIX + "tf";
 
   /** Return Term Vector position information */
-  public static final String POSITIONS = TV_PREFIX + "positions";
+  String POSITIONS = TV_PREFIX + "positions";
 
   /** Return Term Vector payloads information */
-  public static final String PAYLOADS = TV_PREFIX + "payloads";
+  String PAYLOADS = TV_PREFIX + "payloads";
 
   /** Return offset information, if available */
-  public static final String OFFSETS = TV_PREFIX + "offsets";
+  String OFFSETS = TV_PREFIX + "offsets";
 
   /** Return IDF information. May be expensive */
-  public static final String DF = TV_PREFIX + "df";
+  String DF = TV_PREFIX + "df";
 
   /** Return TF-IDF calculation, i.e. (tf / idf). May be expensive. */
-  public static final String TF_IDF = TV_PREFIX + "tf_idf";
+  String TF_IDF = TV_PREFIX + "tf_idf";
 
   /** Return all the options: TF, positions, offsets, idf */
-  public static final String ALL = TV_PREFIX + "all";
+  String ALL = TV_PREFIX + "all";
 
   /** The fields to get term vectors for */
-  public static final String FIELDS = TV_PREFIX + "fl";
+  String FIELDS = TV_PREFIX + "fl";
 
   /** The Doc Ids (Lucene internal ids) of the docs to get the term vectors for */
-  public static final String DOC_IDS = TV_PREFIX + "docIds";
+  String DOC_IDS = TV_PREFIX + "docIds";
 }
diff --git a/solr/solrj/src/java/org/apache/solr/common/params/TermsParams.java b/solr/solrj/src/java/org/apache/solr/common/params/TermsParams.java
index d9dc41d1f4a..ad6f5fbd8a4 100644
--- a/solr/solrj/src/java/org/apache/solr/common/params/TermsParams.java
+++ b/solr/solrj/src/java/org/apache/solr/common/params/TermsParams.java
@@ -23,22 +23,22 @@ import java.util.regex.Pattern;
 /** */
 public interface TermsParams {
   /** The component name. Set to true to turn on the TermsComponent */
-  public static final String TERMS = "terms";
+  String TERMS = "terms";
 
   /** Used for building up the other terms */
-  public static final String TERMS_PREFIX = TERMS + ".";
+  String TERMS_PREFIX = TERMS + ".";
 
   /** Required. Specify the field to look up terms in. */
-  public static final String TERMS_FIELD = TERMS_PREFIX + "fl";
+  String TERMS_FIELD = TERMS_PREFIX + "fl";
 
   /** Optional. The list of terms to be retrieved. */
-  public static final String TERMS_LIST = TERMS_PREFIX + "list";
+  String TERMS_LIST = TERMS_PREFIX + "list";
 
   /** Optional. If true, also returns index-level statistics, such as numDocs. */
-  public static final String TERMS_STATS = TERMS_PREFIX + "stats";
+  String TERMS_STATS = TERMS_PREFIX + "stats";
 
   /** Optional. If true, also returns terms' total term frequency. */
-  public static final String TERMS_TTF = TERMS_PREFIX + "ttf";
+  String TERMS_TTF = TERMS_PREFIX + "ttf";
 
   /**
    * Optional. The lower bound term to start at. The TermEnum will start at the next term after this
@@ -46,36 +46,36 @@ public interface TermsParams {
    *
    * <p>If not specified, the empty string is used
    */
-  public static final String TERMS_LOWER = TERMS_PREFIX + "lower";
+  String TERMS_LOWER = TERMS_PREFIX + "lower";
 
   /**
    * Optional. The term to stop at.
    *
    * @see #TERMS_UPPER_INCLUSIVE
    */
-  public static final String TERMS_UPPER = TERMS_PREFIX + "upper";
+  String TERMS_UPPER = TERMS_PREFIX + "upper";
 
   /** Optional. If true, include the upper bound term in the results. False by default. */
-  public static final String TERMS_UPPER_INCLUSIVE = TERMS_PREFIX + "upper.incl";
+  String TERMS_UPPER_INCLUSIVE = TERMS_PREFIX + "upper.incl";
 
   /**
    * Optional. If true, include the lower bound term in the results, otherwise skip to the next one.
    * True by default.
    */
-  public static final String TERMS_LOWER_INCLUSIVE = TERMS_PREFIX + "lower.incl";
+  String TERMS_LOWER_INCLUSIVE = TERMS_PREFIX + "lower.incl";
 
   /**
    * Optional. The number of results to return. If not specified, looks for {@link
    * org.apache.solr.common.params.CommonParams#ROWS}. If that's not specified, uses {@link
    * org.apache.solr.common.params.CommonParams#ROWS_DEFAULT}.
    */
-  public static final String TERMS_LIMIT = TERMS_PREFIX + "limit";
+  String TERMS_LIMIT = TERMS_PREFIX + "limit";
 
-  public static final String TERMS_PREFIX_STR = TERMS_PREFIX + "prefix";
+  String TERMS_PREFIX_STR = TERMS_PREFIX + "prefix";
 
-  public static final String TERMS_REGEXP_STR = TERMS_PREFIX + "regex";
+  String TERMS_REGEXP_STR = TERMS_PREFIX + "regex";
 
-  public static final String TERMS_REGEXP_FLAG = TERMS_REGEXP_STR + ".flag";
+  String TERMS_REGEXP_FLAG = TERMS_REGEXP_STR + ".flag";
 
   enum TermsRegexpFlag {
     UNIX_LINES(Pattern.UNIX_LINES),
@@ -99,7 +99,7 @@ public interface TermsParams {
   }
 
   /** Optional. The minimum value of docFreq to be returned. 1 by default */
-  public static final String TERMS_MINCOUNT = TERMS_PREFIX + "mincount";
+  String TERMS_MINCOUNT = TERMS_PREFIX + "mincount";
 
   /** Optional. The maximum value of docFreq to be returned. -1 by default means no boundary */
   String TERMS_MAXCOUNT = TERMS_PREFIX + "maxcount";
diff --git a/solr/solrj/src/java/org/apache/solr/common/params/UpdateParams.java b/solr/solrj/src/java/org/apache/solr/common/params/UpdateParams.java
index df6b11f1f3a..8185a9629dc 100644
--- a/solr/solrj/src/java/org/apache/solr/common/params/UpdateParams.java
+++ b/solr/solrj/src/java/org/apache/solr/common/params/UpdateParams.java
@@ -24,59 +24,59 @@ package org.apache.solr.common.params;
 public interface UpdateParams {
 
   /** Open up a new searcher as part of a commit */
-  public static String OPEN_SEARCHER = "openSearcher";
+  String OPEN_SEARCHER = "openSearcher";
 
   /** wait for the searcher to be registered/visible */
-  public static String WAIT_SEARCHER = "waitSearcher";
+  String WAIT_SEARCHER = "waitSearcher";
 
-  public static String SOFT_COMMIT = "softCommit";
+  String SOFT_COMMIT = "softCommit";
 
   /** overwrite indexing fields */
-  public static String OVERWRITE = "overwrite";
+  String OVERWRITE = "overwrite";
 
   /** Commit everything after the command completes */
-  public static String COMMIT = "commit";
+  String COMMIT = "commit";
 
   /** Commit within a certain time period (in ms) */
-  public static String COMMIT_WITHIN = "commitWithin";
+  String COMMIT_WITHIN = "commitWithin";
 
   /** Optimize the index and commit everything after the command completes */
-  public static String OPTIMIZE = "optimize";
+  String OPTIMIZE = "optimize";
 
   /** expert: calls IndexWriter.prepareCommit */
-  public static String PREPARE_COMMIT = "prepareCommit";
+  String PREPARE_COMMIT = "prepareCommit";
 
   /** Fail a commit when the core or collection is in read-only mode */
-  public static String FAIL_ON_READ_ONLY = "failOnReadOnly";
+  String FAIL_ON_READ_ONLY = "failOnReadOnly";
 
   /** Rollback update commands */
-  public static String ROLLBACK = "rollback";
+  String ROLLBACK = "rollback";
 
-  public static String COLLECTION = "collection";
+  String COLLECTION = "collection";
 
   /**
    * Select the update processor chain to use. A RequestHandler may or may not respect this
    * parameter
    */
-  public static final String UPDATE_CHAIN = "update.chain";
+  String UPDATE_CHAIN = "update.chain";
 
   /** Override the content type used for UpdateLoader * */
-  public static final String ASSUME_CONTENT_TYPE = "update.contentType";
+  String ASSUME_CONTENT_TYPE = "update.contentType";
 
   /**
    * If optimizing, set the maximum number of segments left in the index after optimization.
    * Integer.MAX_INT is the default to respect maxMergeSegmentsMB
    */
-  public static final String MAX_OPTIMIZE_SEGMENTS = "maxSegments";
+  String MAX_OPTIMIZE_SEGMENTS = "maxSegments";
 
-  public static final String EXPUNGE_DELETES = "expungeDeletes";
+  String EXPUNGE_DELETES = "expungeDeletes";
 
   /** Return versions of updates? */
-  public static final String VERSIONS = "versions";
+  String VERSIONS = "versions";
 
   /**
    * If set to true, then Solr must fail to process any Atomic Update which can not be done
    * "In-Place" without re-indexing the entire document.
    */
-  public static final String REQUIRE_PARTIAL_DOC_UPDATES_INPLACE = "update.partial.requireInPlace";
+  String REQUIRE_PARTIAL_DOC_UPDATES_INPLACE = "update.partial.requireInPlace";
 }
diff --git a/solr/solrj/src/java/org/apache/solr/common/util/ByteArrayUtf8CharSequence.java b/solr/solrj/src/java/org/apache/solr/common/util/ByteArrayUtf8CharSequence.java
index 052514e75c9..01f4a312358 100644
--- a/solr/solrj/src/java/org/apache/solr/common/util/ByteArrayUtf8CharSequence.java
+++ b/solr/solrj/src/java/org/apache/solr/common/util/ByteArrayUtf8CharSequence.java
@@ -72,14 +72,6 @@ public class ByteArrayUtf8CharSequence implements Utf8CharSequence {
     return buf[offset + idx];
   }
 
-  /**
-   * this is for internal use, to get a cached string value. returns null if there is no cached
-   * String value
-   */
-  public String getStringOrNull() {
-    return utf16;
-  }
-
   @Override
   public int write(int start, byte[] buffer, int pos) {
     return _writeBytes(buf, offset, length, start, buffer, pos);
@@ -203,7 +195,7 @@ public class ByteArrayUtf8CharSequence implements Utf8CharSequence {
       }
     }
     if (needsCopy) {
-      Collection<Object> copy = null;
+      Collection<Object> copy;
       if (vals instanceof Set) {
         copy = CollectionUtil.newHashSet(vals.size());
       } else {
@@ -217,7 +209,7 @@ public class ByteArrayUtf8CharSequence implements Utf8CharSequence {
 
   public static Object convertCharSeq(Object o) {
     if (o == null) return null;
-    if (o instanceof Utf8CharSequence) return ((Utf8CharSequence) o).toString();
+    if (o instanceof Utf8CharSequence) return o.toString();
     if (o instanceof Collection) return convertCharSeq((Collection<?>) o);
     return o;
   }
diff --git a/solr/solrj/src/java/org/apache/solr/common/util/ByteUtils.java b/solr/solrj/src/java/org/apache/solr/common/util/ByteUtils.java
index b7a13dca974..173517baec9 100644
--- a/solr/solrj/src/java/org/apache/solr/common/util/ByteUtils.java
+++ b/solr/solrj/src/java/org/apache/solr/common/util/ByteUtils.java
@@ -75,13 +75,6 @@ public class ByteUtils {
     out.setEnd(out.getEnd() + n);
   }
 
-  /** Convert UTF8 bytes into a String */
-  public static String UTF8toUTF16(byte[] utf8, int offset, int len) {
-    char[] out = new char[len];
-    int n = UTF8toUTF16(utf8, offset, len, out, 0);
-    return new String(out, 0, n);
-  }
-
   /**
    * Writes UTF8 into the byte array, starting at offset. The caller should ensure that there is
    * enough space for the worst-case scenario.
@@ -94,7 +87,7 @@ public class ByteUtils {
 
     int upto = resultOffset;
     for (int i = offset; i < end; i++) {
-      final int code = (int) s.charAt(i);
+      final int code = s.charAt(i);
 
       if (code < 0x80) result[upto++] = (byte) code;
       else if (code < 0x800) {
@@ -108,7 +101,7 @@ public class ByteUtils {
         // surrogate pair
         // confirm valid high surrogate
         if (code < 0xDC00 && (i < end - 1)) {
-          int utf32 = (int) s.charAt(i + 1);
+          int utf32 = s.charAt(i + 1);
           // confirm valid low surrogate and write pair
           if (utf32 >= 0xDC00 && utf32 <= 0xDFFF) {
             utf32 = ((code - 0xD7C0) << 10) + (utf32 & 0x3FF);
@@ -144,7 +137,7 @@ public class ByteUtils {
 
     int upto = 0, totalBytes = 0;
     for (int i = offset; i < end; i++) {
-      final int code = (int) s.charAt(i);
+      final int code = s.charAt(i);
 
       if (upto > scratch.length - 4) {
         // a code point may take up to 4 bytes, and we don't have enough space, so reset
@@ -166,7 +159,7 @@ public class ByteUtils {
         // surrogate pair
         // confirm valid high surrogate
         if (code < 0xDC00 && (i < end - 1)) {
-          int utf32 = (int) s.charAt(i + 1);
+          int utf32 = s.charAt(i + 1);
           // confirm valid low surrogate and write pair
           if (utf32 >= 0xDC00 && utf32 <= 0xDFFF) {
             utf32 = ((code - 0xD7C0) << 10) + (utf32 & 0x3FF);
@@ -202,7 +195,7 @@ public class ByteUtils {
 
     int res = 0;
     for (int i = offset; i < end; i++) {
-      final int code = (int) s.charAt(i);
+      final int code = s.charAt(i);
 
       if (code < 0x80) res++;
       else if (code < 0x800) {
@@ -213,7 +206,7 @@ public class ByteUtils {
         // surrogate pair
         // confirm valid high surrogate
         if (code < 0xDC00 && (i < end - 1)) {
-          int utf32 = (int) s.charAt(i + 1);
+          int utf32 = s.charAt(i + 1);
           // confirm valid low surrogate and write pair
           if (utf32 >= 0xDC00 && utf32 <= 0xDFFF) {
             i++;
diff --git a/solr/solrj/src/java/org/apache/solr/common/util/CommandOperation.java b/solr/solrj/src/java/org/apache/solr/common/util/CommandOperation.java
index 7598e90fcbb..f7c2b560c0a 100644
--- a/solr/solrj/src/java/org/apache/solr/common/util/CommandOperation.java
+++ b/solr/solrj/src/java/org/apache/solr/common/util/CommandOperation.java
@@ -25,7 +25,6 @@ import java.io.Reader;
 import java.nio.charset.StandardCharsets;
 import java.util.ArrayList;
 import java.util.HashMap;
-import java.util.LinkedHashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
@@ -175,19 +174,6 @@ public class CommandOperation {
     errors.add(s);
   }
 
-  /** Get all the values from the metadata for the command without the specified keys */
-  public Map<String, Object> getValuesExcluding(String... keys) {
-    getMapVal(null);
-    if (hasError()) return Map.of(); // just to verify the type is Map
-    @SuppressWarnings("unchecked")
-    LinkedHashMap<String, Object> cp = new LinkedHashMap<>((Map<String, Object>) commandData);
-    if (keys == null) return cp;
-    for (String key : keys) {
-      cp.remove(key);
-    }
-    return cp;
-  }
-
   public List<String> getErrors() {
     return errors;
   }
@@ -258,11 +244,7 @@ public class CommandOperation {
    */
   public static List<CommandOperation> parse(Reader rdr, Set<String> singletonCommands)
       throws IOException {
-    JSONParser parser = new JSONParser(rdr);
-    parser.setFlags(
-        parser.getFlags()
-            | JSONParser.ALLOW_MISSING_COLON_COMMA_BEFORE_OBJECT
-            | JSONParser.OPTIONAL_OUTER_BRACES);
+    JSONParser parser = Utils.getJSONParser(rdr);
 
     ObjectBuilder ob = new ObjectBuilder(parser);
 
diff --git a/solr/solrj/src/java/org/apache/solr/common/util/CommonTestInjection.java b/solr/solrj/src/java/org/apache/solr/common/util/CommonTestInjection.java
index 3acf4d75163..984d15cf6fe 100644
--- a/solr/solrj/src/java/org/apache/solr/common/util/CommonTestInjection.java
+++ b/solr/solrj/src/java/org/apache/solr/common/util/CommonTestInjection.java
@@ -21,7 +21,6 @@ import java.io.Closeable;
 import java.io.IOException;
 import java.lang.invoke.MethodHandles;
 import java.util.HashSet;
-import java.util.Map;
 import java.util.Set;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ConcurrentMap;
@@ -36,23 +35,13 @@ import org.slf4j.LoggerFactory;
 public class CommonTestInjection {
   private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
 
-  private static volatile Map<String, String> additionalSystemProps = null;
   private static volatile Integer delay = null;
   private static final ConcurrentMap<String, Breakpoint> breakpoints = new ConcurrentHashMap<>();
 
   public static void reset() {
-    additionalSystemProps = null;
     delay = null;
   }
 
-  public static void setAdditionalProps(Map<String, String> additionalSystemProps) {
-    CommonTestInjection.additionalSystemProps = additionalSystemProps;
-  }
-
-  public static Map<String, String> injectAdditionalProps() {
-    return additionalSystemProps;
-  }
-
   /**
    * Set test delay (sleep) in unit of milliseconds
    *
diff --git a/solr/solrj/src/java/org/apache/solr/common/util/ContentStreamBase.java b/solr/solrj/src/java/org/apache/solr/common/util/ContentStreamBase.java
index bd87e049b8a..e97e9bf4285 100644
--- a/solr/solrj/src/java/org/apache/solr/common/util/ContentStreamBase.java
+++ b/solr/solrj/src/java/org/apache/solr/common/util/ContentStreamBase.java
@@ -304,10 +304,6 @@ public abstract class ContentStreamBase implements ContentStream {
     return sourceInfo;
   }
 
-  public void setSourceInfo(String sourceInfo) {
-    this.sourceInfo = sourceInfo;
-  }
-
   public static ContentStream create(
       RequestWriter requestWriter, @SuppressWarnings({"rawtypes"}) SolrRequest req)
       throws IOException {
diff --git a/solr/solrj/src/java/org/apache/solr/common/util/DOMUtil.java b/solr/solrj/src/java/org/apache/solr/common/util/DOMUtil.java
index 0a2c93d9aa9..6c561cb80d0 100644
--- a/solr/solrj/src/java/org/apache/solr/common/util/DOMUtil.java
+++ b/solr/solrj/src/java/org/apache/solr/common/util/DOMUtil.java
@@ -20,7 +20,6 @@ import static org.apache.solr.common.params.CommonParams.NAME;
 
 import java.util.ArrayList;
 import java.util.HashMap;
-import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
 import java.util.Properties;
@@ -78,11 +77,6 @@ public class DOMUtil {
     return getAttr(nd.getAttributes(), name);
   }
 
-  public static String getAttrOrDefault(Node nd, String name, String def) {
-    String attr = getAttr(nd.getAttributes(), name);
-    return attr == null ? def : attr;
-  }
-
   public static String getAttr(NamedNodeMap attrs, String name, String missing_err) {
     Node attr = attrs == null ? null : attrs.getNamedItem(name);
     if (attr == null) {
@@ -278,17 +272,6 @@ public class DOMUtil {
     }
   }
 
-  /**
-   * Replaces ${system.property[:default value]} references in all attributes and text nodes of
-   * supplied node. If the system property is not defined and no default value is provided, a
-   * runtime exception is thrown.
-   *
-   * @param node DOM node to walk for substitutions
-   */
-  public static void substituteSystemProperties(Node node) {
-    substituteProperties(node, null);
-  }
-
   /**
    * Replaces ${property[:default value]} references in all attributes and text nodes of supplied
    * node. If the property is not defined, either in the given Properties instance nor in
@@ -321,106 +304,4 @@ public class DOMUtil {
       }
     }
   }
-
-  public static String substituteProperty(String value, Properties coreProperties) {
-    if (value == null || value.indexOf('$') == -1) {
-      return value;
-    }
-
-    List<String> fragments = new ArrayList<>();
-    List<String> propertyRefs = new ArrayList<>();
-    parsePropertyString(value, fragments, propertyRefs);
-
-    StringBuilder sb = new StringBuilder();
-    Iterator<String> i = fragments.iterator();
-    Iterator<String> j = propertyRefs.iterator();
-
-    while (i.hasNext()) {
-      String fragment = i.next();
-      if (fragment == null) {
-        String propertyName = j.next();
-        String defaultValue = null;
-        int colon_index = propertyName.indexOf(':');
-        if (colon_index > -1) {
-          defaultValue = propertyName.substring(colon_index + 1);
-          propertyName = propertyName.substring(0, colon_index);
-        }
-        if (coreProperties != null) {
-          fragment = coreProperties.getProperty(propertyName);
-        }
-        if (fragment == null) {
-          fragment = System.getProperty(propertyName, defaultValue);
-        }
-        if (fragment == null) {
-          throw new SolrException(
-              SolrException.ErrorCode.SERVER_ERROR,
-              "No system property or default value specified for "
-                  + propertyName
-                  + " value:"
-                  + value);
-        }
-      }
-      sb.append(fragment);
-    }
-    return sb.toString();
-  }
-
-  /*
-   * This method borrowed from Ant's PropertyHelper.parsePropertyStringDefault:
-   *   http://svn.apache.org/repos/asf/ant/core/trunk/src/main/org/apache/tools/ant/PropertyHelper.java
-   */
-  private static void parsePropertyString(
-      String value, List<String> fragments, List<String> propertyRefs) {
-    int prev = 0;
-    int pos;
-    // search for the next instance of $ from the 'prev' position
-    while ((pos = value.indexOf('$', prev)) >= 0) {
-
-      // if there was any text before this, add it as a fragment
-      // TODO, this check could be modified to go if pos>prev;
-      // seems like this current version could stick empty strings
-      // into the list
-      if (pos > 0) {
-        fragments.add(value.substring(prev, pos));
-      }
-      // if we are at the end of the string, we tack on a $
-      // then move past it
-      if (pos == (value.length() - 1)) {
-        fragments.add("$");
-        prev = pos + 1;
-      } else if (value.charAt(pos + 1) != '{') {
-        // peek ahead to see if the next char is a property or
-        // not a property: insert the char as a literal
-        /*
-        fragments.addElement(value.substring(pos + 1, pos + 2));
-        prev = pos + 2;
-        */
-        if (value.charAt(pos + 1) == '$') {
-          // backwards compatibility two $ map to one mode
-          fragments.add("$");
-          prev = pos + 2;
-        } else {
-          // new behaviour: $X maps to $X for all values of X!='$'
-          fragments.add(value.substring(pos, pos + 2));
-          prev = pos + 2;
-        }
-
-      } else {
-        // property found, extract its name or bail on a typo
-        int endName = value.indexOf('}', pos);
-        if (endName < 0) {
-          throw new RuntimeException("Syntax error in property: " + value);
-        }
-        String propertyName = value.substring(pos + 2, endName);
-        fragments.add(null);
-        propertyRefs.add(propertyName);
-        prev = endName + 1;
-      }
-    }
-    // no more $ signs found
-    // if there is any tail to the string, append it
-    if (prev < value.length()) {
-      fragments.add(value.substring(prev));
-    }
-  }
 }
diff --git a/solr/solrj/src/java/org/apache/solr/common/util/DataInputInputStream.java b/solr/solrj/src/java/org/apache/solr/common/util/DataInputInputStream.java
index d5724e882dc..c10d699a259 100644
--- a/solr/solrj/src/java/org/apache/solr/common/util/DataInputInputStream.java
+++ b/solr/solrj/src/java/org/apache/solr/common/util/DataInputInputStream.java
@@ -26,7 +26,7 @@ public abstract class DataInputInputStream extends InputStream implements DataIn
   /**
    * If possible, read UTF8 bytes directly from the underlying buffer
    *
-   * @param utf8 the utf8 ubject to read into
+   * @param utf8 the utf8 subject to read into
    * @param len length of the utf8 stream
    * @return whether it is possible to do a direct read or not
    */
@@ -42,5 +42,4 @@ public abstract class DataInputInputStream extends InputStream implements DataIn
   public ByteBuffer readDirectByteBuffer(int sz) {
     return null;
   }
-  ;
 }
diff --git a/solr/solrj/src/java/org/apache/solr/common/util/ExecutorUtil.java b/solr/solrj/src/java/org/apache/solr/common/util/ExecutorUtil.java
index 48ac61f55d8..e4814f7b094 100644
--- a/solr/solrj/src/java/org/apache/solr/common/util/ExecutorUtil.java
+++ b/solr/solrj/src/java/org/apache/solr/common/util/ExecutorUtil.java
@@ -119,24 +119,6 @@ public class ExecutorUtil {
     awaitTermination(pool);
   }
 
-  /**
-   * Shutdown the {@link ExecutorService} and wait forever for the threads to complete. More detail
-   * on the waiting can be found in {@link #awaitTerminationForever(ExecutorService)}.
-   *
-   * <p>This should likely not be used in {@code close()} methods, as we want to time bound when
-   * shutting down. However, sometimes {@link ExecutorService}s are used to submit a list of tasks
-   * and awaiting termination is akin to waiting on the list of {@link Future}s to complete. In that
-   * case, this method should be used as there is no inherent time bound to waiting on those tasks
-   * to complete.
-   *
-   * @param pool The ExecutorService to shut down and wait on
-   */
-  public static void shutdownAndAwaitTerminationForever(ExecutorService pool) {
-    if (pool == null) return;
-    pool.shutdown(); // Disable new tasks from being submitted
-    awaitTerminationForever(pool);
-  }
-
   public static void shutdownNowAndAwaitTermination(ExecutorService pool) {
     if (pool == null) return;
     pool.shutdownNow(); // Disable new tasks from being submitted; interrupt existing tasks
diff --git a/solr/solrj/src/java/org/apache/solr/common/util/FastJavaBinDecoder.java b/solr/solrj/src/java/org/apache/solr/common/util/FastJavaBinDecoder.java
index 37d82822cad..57330fe7b2a 100644
--- a/solr/solrj/src/java/org/apache/solr/common/util/FastJavaBinDecoder.java
+++ b/solr/solrj/src/java/org/apache/solr/common/util/FastJavaBinDecoder.java
@@ -285,7 +285,7 @@ public class FastJavaBinDecoder implements DataEntry.FastDecoder {
 
     void reset() {
       this.doubleVal = 0.0d;
-      this.numericVal = 0l;
+      this.numericVal = 0L;
       this.objVal = null;
       this.ctx = null;
       this.entryListener = null;
@@ -338,7 +338,7 @@ public class FastJavaBinDecoder implements DataEntry.FastDecoder {
 
       @Override
       public Object readObject(StreamCodec codec, EntryImpl entry) {
-        return Byte.valueOf((byte) entry.numericVal);
+        return (byte) entry.numericVal;
       }
     },
     _SHORT(SHORT, LOWER_5_BITS, DataEntry.Type.INT) {
@@ -350,7 +350,7 @@ public class FastJavaBinDecoder implements DataEntry.FastDecoder {
 
       @Override
       public Object readObject(StreamCodec codec, EntryImpl entry) {
-        return Short.valueOf((short) entry.numericVal);
+        return (short) entry.numericVal;
       }
     },
     _DOUBLE(DOUBLE, LOWER_5_BITS, DataEntry.Type.DOUBLE) {
@@ -362,7 +362,7 @@ public class FastJavaBinDecoder implements DataEntry.FastDecoder {
 
       @Override
       public Object readObject(StreamCodec codec, EntryImpl entry) {
-        return Double.valueOf(entry.doubleVal);
+        return entry.doubleVal;
       }
     },
     _INT(INT, LOWER_5_BITS, DataEntry.Type.INT) {
@@ -373,7 +373,7 @@ public class FastJavaBinDecoder implements DataEntry.FastDecoder {
 
       @Override
       public Object readObject(StreamCodec codec, EntryImpl entry) {
-        return Integer.valueOf((int) entry.numericVal);
+        return (int) entry.numericVal;
       }
     }, // signed integer
     _LONG(LONG, LOWER_5_BITS, DataEntry.Type.LONG) {
@@ -384,7 +384,7 @@ public class FastJavaBinDecoder implements DataEntry.FastDecoder {
 
       @Override
       public Object readObject(StreamCodec codec, EntryImpl entry) {
-        return Long.valueOf(entry.numericVal);
+        return entry.numericVal;
       }
     },
     _FLOAT(FLOAT, LOWER_5_BITS, DataEntry.Type.FLOAT) {
@@ -395,7 +395,7 @@ public class FastJavaBinDecoder implements DataEntry.FastDecoder {
 
       @Override
       public Object readObject(StreamCodec codec, EntryImpl entry) {
-        return Float.valueOf((float) entry.doubleVal);
+        return (float) entry.doubleVal;
       }
     },
     _DATE(DATE, LOWER_5_BITS, DataEntry.Type.DATE) {
diff --git a/solr/solrj/src/java/org/apache/solr/common/util/FastOutputStream.java b/solr/solrj/src/java/org/apache/solr/common/util/FastOutputStream.java
index 8c3cdbd394a..dc90d7d5f9a 100644
--- a/solr/solrj/src/java/org/apache/solr/common/util/FastOutputStream.java
+++ b/solr/solrj/src/java/org/apache/solr/common/util/FastOutputStream.java
@@ -52,7 +52,7 @@ public class FastOutputStream extends OutputStream implements DataOutput {
   }
 
   @Override
-  public void write(byte b[]) throws IOException {
+  public void write(byte[] b) throws IOException {
     write(b, 0, b.length);
   }
 
@@ -66,7 +66,7 @@ public class FastOutputStream extends OutputStream implements DataOutput {
   }
 
   @Override
-  public void write(byte arr[], int off, int len) throws IOException {
+  public void write(byte[] arr, int off, int len) throws IOException {
 
     for (; ; ) {
       int space = buf.length - pos;
diff --git a/solr/solrj/src/java/org/apache/solr/common/util/FastWriter.java b/solr/solrj/src/java/org/apache/solr/common/util/FastWriter.java
index 3989d38341a..6d54bda77a3 100644
--- a/solr/solrj/src/java/org/apache/solr/common/util/FastWriter.java
+++ b/solr/solrj/src/java/org/apache/solr/common/util/FastWriter.java
@@ -66,7 +66,7 @@ public class FastWriter extends Writer {
   }
 
   @Override
-  public void write(char arr[], int off, int len) throws IOException {
+  public void write(char[] arr, int off, int len) throws IOException {
     for (; ; ) {
       int space = buf.length - pos;
 
diff --git a/solr/solrj/src/java/org/apache/solr/common/util/GlobPatternUtil.java b/solr/solrj/src/java/org/apache/solr/common/util/GlobPatternUtil.java
index 2c370718701..ac352ccdd3e 100644
--- a/solr/solrj/src/java/org/apache/solr/common/util/GlobPatternUtil.java
+++ b/solr/solrj/src/java/org/apache/solr/common/util/GlobPatternUtil.java
@@ -136,7 +136,7 @@ public class GlobPatternUtil {
     char prevChar = 0;
     for (final char ch : array) {
       if (ch == '?' || ch == '*') {
-        if (buffer.length() != 0) {
+        if (!buffer.isEmpty()) {
           list.add(buffer.toString());
           buffer.setLength(0);
         }
@@ -150,7 +150,7 @@ public class GlobPatternUtil {
       }
       prevChar = ch;
     }
-    if (buffer.length() != 0) {
+    if (!buffer.isEmpty()) {
       list.add(buffer.toString());
     }
 
diff --git a/solr/solrj/src/java/org/apache/solr/common/util/JavaBinCodec.java b/solr/solrj/src/java/org/apache/solr/common/util/JavaBinCodec.java
index f47ff63b980..12f7f4cf4bb 100644
--- a/solr/solrj/src/java/org/apache/solr/common/util/JavaBinCodec.java
+++ b/solr/solrj/src/java/org/apache/solr/common/util/JavaBinCodec.java
@@ -359,7 +359,7 @@ public class JavaBinCodec implements PushWriter {
     throw new RuntimeException("Unknown type " + tagByte);
   }
 
-  @SuppressWarnings({"unchecked", "rawtypes"})
+  @SuppressWarnings({"rawtypes"})
   public boolean writeKnownType(Object val) throws IOException {
     if (writePrimitive(val)) return true;
     if (val instanceof NamedList) {
@@ -1250,16 +1250,16 @@ public class JavaBinCodec implements PushWriter {
     } else if (val instanceof Number) {
 
       if (val instanceof Integer) {
-        writeInt(((Integer) val).intValue());
+        writeInt((Integer) val);
         return true;
       } else if (val instanceof Long) {
-        writeLong(((Long) val).longValue());
+        writeLong((Long) val);
         return true;
       } else if (val instanceof Float) {
-        writeFloat(((Float) val).floatValue());
+        writeFloat((Float) val);
         return true;
       } else if (val instanceof Double) {
-        writeDouble(((Double) val).doubleValue());
+        writeDouble((Double) val);
         return true;
       } else if (val instanceof Byte) {
         daos.writeByte(BYTE);
diff --git a/solr/solrj/src/java/org/apache/solr/common/util/JsonRecordReader.java b/solr/solrj/src/java/org/apache/solr/common/util/JsonRecordReader.java
index 86d3b94c236..5d9ef1b883c 100644
--- a/solr/solrj/src/java/org/apache/solr/common/util/JsonRecordReader.java
+++ b/solr/solrj/src/java/org/apache/solr/common/util/JsonRecordReader.java
@@ -57,7 +57,7 @@ public class JsonRecordReader {
         fieldName = s.substring(0, idx);
         path = s.substring(idx + 1);
       }
-      jsonRecordReader.addField(path, fieldName, true, false);
+      jsonRecordReader.addField(path, fieldName, false);
     }
     return jsonRecordReader;
   }
@@ -82,9 +82,9 @@ public class JsonRecordReader {
       split = split.trim();
       if (split.startsWith("//"))
         throw new RuntimeException("split cannot start with '//': " + split);
-      if (split.length() == 0) continue;
+      if (split.isEmpty()) continue;
       // The created Node has a name set to the full split attribute path
-      addField(split, split, false, true);
+      addField(split, split, true);
     }
   }
 
@@ -95,19 +95,18 @@ public class JsonRecordReader {
    *
    * @param path The path expression for this field
    * @param fieldName The name for this field in the emitted record
-   * @param multiValued If 'true' then the emitted record will have values in a List&lt;String&gt;
    * @param isRecord Flags that this PATH is from a forEach statement
    */
-  private void addField(String path, String fieldName, boolean multiValued, boolean isRecord) {
+  private void addField(String path, String fieldName, boolean isRecord) {
     if (!path.startsWith("/")) throw new RuntimeException("All paths must start with '/' " + path);
     List<String> paths = splitEscapeQuote(path);
-    if (paths.size() == 0) {
+    if (paths.isEmpty()) {
       if (isRecord) rootNode.setAsRecord();
       return; // the path is "/"
     }
     // deal with how split behaves when separator starts with an empty string!
     if (paths.get(0).trim().isEmpty()) paths.remove(0);
-    rootNode.build(paths, fieldName, multiValued, isRecord, path);
+    rootNode.build(paths, fieldName, isRecord, path);
     rootNode.buildOptimize();
   }
 
@@ -138,7 +137,7 @@ public class JsonRecordReader {
   }
 
   public void streamRecords(JSONParser parser, Handler handler) throws IOException {
-    rootNode.parse(parser, handler, new LinkedHashMap<>());
+    rootNode.parse(parser, handler);
   }
 
   /**
@@ -170,12 +169,6 @@ public class JsonRecordReader {
       parent = p;
     }
 
-    public Node(String name, String fieldName) {
-      // This is only called from build() when describing an attribute.
-      this.name = name; // a segment from the path
-      this.fieldName = fieldName; // name to store collected values against
-    }
-
     void setAsRecord() {
       if (isMyChildARecord())
         throw new RuntimeException(name + " has a parent node at my level or lower");
@@ -218,13 +211,12 @@ public class JsonRecordReader {
     private void build(
         List<String> paths, // a List of segments from the split paths
         String fieldName, // the fieldName assoc with this path
-        boolean multiValued, // flag if this fieldName is multiValued or not
         boolean record, // is this path a record or a field
         String path) {
       // recursively walk the paths Lists adding new Nodes as required
       String segment = paths.remove(0); // shift out next path segment
 
-      if (segment.length() < 1)
+      if (segment.isEmpty())
         throw new RuntimeException("all pieces in path must be non empty " + path);
 
       // does this "name" already exist as a child node.
@@ -263,7 +255,7 @@ public class JsonRecordReader {
         if (WILDCARD_PATH.equals(name) || RECURSIVE_WILDCARD_PATH.equals(name))
           throw new RuntimeException("wild cards are allowed only in the end " + path);
         // recurse to handle next paths segment
-        n.build(paths, fieldName, multiValued, record, path);
+        n.build(paths, fieldName, record, path);
       }
     }
 
@@ -275,8 +267,7 @@ public class JsonRecordReader {
       return n;
     }
 
-    private void parse(JSONParser parser, Handler handler, Map<String, Object> values)
-        throws IOException {
+    private void parse(JSONParser parser, Handler handler) throws IOException {
 
       int event = -1;
       boolean recordStarted = false;
diff --git a/solr/solrj/src/java/org/apache/solr/common/util/JsonSchemaValidator.java b/solr/solrj/src/java/org/apache/solr/common/util/JsonSchemaValidator.java
index 9d19c35b8ac..fa8b41aac73 100644
--- a/solr/solrj/src/java/org/apache/solr/common/util/JsonSchemaValidator.java
+++ b/solr/solrj/src/java/org/apache/solr/common/util/JsonSchemaValidator.java
@@ -99,7 +99,6 @@ public class JsonSchemaValidator {
 
 abstract class Validator<T> {
   Validator(Map<?, ?> schema, T properties) {}
-  ;
 
   abstract boolean validate(Object o, List<String> errs);
 }
diff --git a/solr/solrj/src/java/org/apache/solr/common/util/JsonTextWriter.java b/solr/solrj/src/java/org/apache/solr/common/util/JsonTextWriter.java
index e3e9ff67b82..89e9e0fc4eb 100644
--- a/solr/solrj/src/java/org/apache/solr/common/util/JsonTextWriter.java
+++ b/solr/solrj/src/java/org/apache/solr/common/util/JsonTextWriter.java
@@ -314,85 +314,27 @@ public interface JsonTextWriter extends TextWriter {
   default void writeNamedList(String name, NamedList<?> val) throws IOException {
     String namedListStyle = getNamedListStyle();
     if (val instanceof SimpleOrderedMap) {
-      writeNamedListAsMapWithDups(name, val);
+      writeNamedListAsMapWithDups(val);
     } else if (Objects.equals(namedListStyle, JSON_NL_FLAT)) {
-      writeNamedListAsFlat(name, val);
+      writeNamedListAsFlat(val);
     } else if (Objects.equals(namedListStyle, JSON_NL_MAP)) {
-      writeNamedListAsMapWithDups(name, val);
+      writeNamedListAsMapWithDups(val);
     } else if (Objects.equals(namedListStyle, JSON_NL_ARROFARR)) {
-      writeNamedListAsArrArr(name, val);
+      writeNamedListAsArrArr(val);
     } else if (Objects.equals(namedListStyle, JSON_NL_ARROFMAP)) {
-      writeNamedListAsArrMap(name, val);
+      writeNamedListAsArrMap(val);
     } else if (Objects.equals(namedListStyle, JSON_NL_ARROFNTV)) {
       throw new UnsupportedOperationException(
           namedListStyle + " namedListStyle must only be used with ArrayOfNameTypeValueJSONWriter");
     }
   }
 
-  /**
-   * Represents a NamedList directly as a JSON Object (essentially a Map) Map null to "" and name
-   * mangle any repeated keys to avoid repeats in the output.
-   */
-  default void writeNamedListAsMapMangled(String name, NamedList<?> val) throws IOException {
-    int sz = val.size();
-    writeMapOpener(sz);
-    incLevel();
-
-    // In JSON objects (maps) we can't have null keys or duplicates...
-    // map null to "" and append a qualifier to duplicates.
-    //
-    // a=123,a=456 will be mapped to {a=1,a__1=456}
-    // Disad: this is ambiguous since a real key could be called a__1
-    //
-    // Another possible mapping could aggregate multiple keys to an array:
-    // a=123,a=456 maps to a=[123,456]
-    // Disad: this is ambiguous with a real single value that happens to be an array
-    //
-    // Both of these mappings have ambiguities.
-    Map<String, Integer> repeats = CollectionUtil.newHashMap(4);
-
-    boolean first = true;
-    for (int i = 0; i < sz; i++) {
-      String key = val.getName(i);
-      if (key == null) key = "";
-
-      if (first) {
-        first = false;
-        repeats.put(key, 0);
-      } else {
-        writeMapSeparator();
-
-        Integer repeatCount = repeats.get(key);
-        if (repeatCount == null) {
-          repeats.put(key, 0);
-        } else {
-          String newKey = key;
-          int newCount = repeatCount;
-          do { // avoid generated key clashing with a real key
-            newKey = key + ' ' + (++newCount);
-            repeatCount = repeats.get(newKey);
-          } while (repeatCount != null);
-
-          repeats.put(key, newCount);
-          key = newKey;
-        }
-      }
-
-      indent();
-      writeKey(key, true);
-      writeVal(key, val.getVal(i));
-    }
-
-    decLevel();
-    writeMapCloser();
-  }
-
   /**
    * Represents a NamedList directly as a JSON Object (essentially a Map) repeating any keys if they
    * are repeated in the NamedList. null key is mapped to "".
    */
   // NamedList("a"=1,"bar"="foo",null=3,null=null) => {"a":1,"bar":"foo","":3,"":null}
-  default void writeNamedListAsMapWithDups(String name, NamedList<?> val) throws IOException {
+  default void writeNamedListAsMapWithDups(NamedList<?> val) throws IOException {
     int sz = val.size();
     writeMapOpener(sz);
     incLevel();
@@ -415,7 +357,7 @@ public interface JsonTextWriter extends TextWriter {
 
   // Represents a NamedList directly as an array of JSON objects...
   // NamedList("a"=1,"b"=2,null=3,null=null) => [{"a":1},{"b":2},3,null]
-  default void writeNamedListAsArrMap(String name, NamedList<?> val) throws IOException {
+  default void writeNamedListAsArrMap(NamedList<?> val) throws IOException {
     int sz = val.size();
     indent();
     writeArrayOpener(sz);
@@ -449,7 +391,7 @@ public interface JsonTextWriter extends TextWriter {
 
   // Represents a NamedList directly as an array of JSON objects...
   // NamedList("a"=1,"b"=2,null=3,null=null) => [["a",1],["b",2],[null,3],[null,null]]
-  default void writeNamedListAsArrArr(String name, NamedList<?> val) throws IOException {
+  default void writeNamedListAsArrArr(NamedList<?> val) throws IOException {
     int sz = val.size();
     indent();
     writeArrayOpener(sz);
@@ -493,7 +435,7 @@ public interface JsonTextWriter extends TextWriter {
   // Represents a NamedList directly as an array with keys/values
   // interleaved.
   // NamedList("a"=1,"b"=2,null=3,null=null) => ["a",1,"b",2,null,3,null,null]
-  default void writeNamedListAsFlat(String name, NamedList<?> val) throws IOException {
+  default void writeNamedListAsFlat(NamedList<?> val) throws IOException {
     int sz = val.size();
     writeArrayOpener(sz * 2);
     incLevel();
diff --git a/solr/solrj/src/java/org/apache/solr/common/util/NamedList.java b/solr/solrj/src/java/org/apache/solr/common/util/NamedList.java
index 6b43da26de9..e4f27c4025b 100644
--- a/solr/solrj/src/java/org/apache/solr/common/util/NamedList.java
+++ b/solr/solrj/src/java/org/apache/solr/common/util/NamedList.java
@@ -135,7 +135,7 @@ public class NamedList<T>
 
   /**
    * Method to serialize Map.Entry&lt;String, ?&gt; to a List in which the even indexed elements
-   * (0,2,4, etc.) are Strings and odd elements (1,3,5,) are of the type "T".
+   * (0,2,4, etc.) are Strings and odd elements (1,3,5) are of the type "T".
    *
    * <p>NOTE: This a temporary placeholder method until the guts of the class are actually replaced
    * by List&lt;String, ?&gt;.
diff --git a/solr/solrj/src/java/org/apache/solr/common/util/ObjectReleaseTracker.java b/solr/solrj/src/java/org/apache/solr/common/util/ObjectReleaseTracker.java
index 5ee278997f5..f3e5e05c355 100644
--- a/solr/solrj/src/java/org/apache/solr/common/util/ObjectReleaseTracker.java
+++ b/solr/solrj/src/java/org/apache/solr/common/util/ObjectReleaseTracker.java
@@ -21,7 +21,6 @@ import java.io.PrintWriter;
 import java.io.StringWriter;
 import java.lang.invoke.MethodHandles;
 import java.util.ArrayList;
-import java.util.Arrays;
 import java.util.List;
 import java.util.Map;
 import java.util.Map.Entry;
@@ -35,16 +34,6 @@ import org.slf4j.LoggerFactory;
 public class ObjectReleaseTracker {
   private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
 
-  private static final List<String> DEFAULT_STACK_FILTERS =
-      Arrays.asList(
-          new String[] {
-            "org.junit.",
-            "junit.framework.",
-            "sun.",
-            "java.lang.reflect.",
-            "com.carrotsearch.randomizedtesting.",
-          });
-
   public static final Map<Object, Exception> OBJECTS = new ConcurrentHashMap<>();
 
   public static boolean track(Object object) {
diff --git a/solr/solrj/src/java/org/apache/solr/common/util/PathTrie.java b/solr/solrj/src/java/org/apache/solr/common/util/PathTrie.java
index 0fde7c457b2..9eb74a0bc19 100644
--- a/solr/solrj/src/java/org/apache/solr/common/util/PathTrie.java
+++ b/solr/solrj/src/java/org/apache/solr/common/util/PathTrie.java
@@ -32,8 +32,6 @@ public class PathTrie<T> {
   private final Set<String> reserved = new HashSet<>();
   Node root = new Node(List.of(), null, null);
 
-  public PathTrie() {}
-
   public PathTrie(Set<String> reserved) {
     this.reserved.addAll(reserved);
   }
diff --git a/solr/solrj/src/java/org/apache/solr/common/util/PropertiesUtil.java b/solr/solrj/src/java/org/apache/solr/common/util/PropertiesUtil.java
index 9ae768c1f0a..94ba0149622 100644
--- a/solr/solrj/src/java/org/apache/solr/common/util/PropertiesUtil.java
+++ b/solr/solrj/src/java/org/apache/solr/common/util/PropertiesUtil.java
@@ -139,23 +139,4 @@ public class PropertiesUtil {
       fragments.add(value.substring(prev));
     }
   }
-
-  /**
-   * Parse the given String value as an integer. If the string cannot be parsed, returns the default
-   *
-   * @param value the value to parse
-   * @param defValue the default to return if the value cannot be parsed
-   * @return an integer version of the passed in value
-   */
-  public static Integer toInteger(String value, Integer defValue) {
-    try {
-      return Integer.parseInt(value);
-    } catch (NumberFormatException e) {
-      return defValue;
-    }
-  }
-
-  public static boolean toBoolean(String value) {
-    return "true".equalsIgnoreCase(value) || "on".equalsIgnoreCase(value);
-  }
 }
diff --git a/solr/solrj/src/java/org/apache/solr/common/util/Template.java b/solr/solrj/src/java/org/apache/solr/common/util/Template.java
deleted file mode 100644
index 9d846dcca22..00000000000
--- a/solr/solrj/src/java/org/apache/solr/common/util/Template.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * 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.solr.common.util;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.function.Function;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-public class Template {
-  public final String template;
-  public static final Pattern DOLLAR_BRACES_PLACEHOLDER_PATTERN = Pattern.compile("[$][{](.*?)[}]");
-  public static final Pattern BRACES_PLACEHOLDER_PATTERN = Pattern.compile("[{](.*?)[}]");
-
-  public Template(String template, Pattern pattern) {
-    this.template = template;
-    List<String> variables = new ArrayList<>(2);
-    Matcher m = pattern.matcher(template);
-    while (m.find()) {
-      String variable = m.group(1);
-      startIndexes.add(m.start(0));
-      endOffsets.add(m.end(0));
-      variables.add(variable);
-    }
-    this.variables = Collections.unmodifiableList(variables);
-  }
-
-  public String apply(Function<String, Object> valueSupplier) {
-    if (startIndexes != null) {
-      StringBuilder sb = new StringBuilder(template);
-      for (int i = startIndexes.size() - 1; i >= 0; i--) {
-        String replacement = valueSupplier.apply(variables.get(i)).toString();
-        sb.replace(startIndexes.get(i), endOffsets.get(i), replacement);
-      }
-      return sb.toString();
-    } else {
-      return template;
-    }
-  }
-
-  private List<Integer> startIndexes = new ArrayList<>(2);
-  private List<Integer> endOffsets = new ArrayList<>(2);
-  public final List<String> variables;
-}
diff --git a/solr/solrj/src/java/org/apache/solr/common/util/URLUtil.java b/solr/solrj/src/java/org/apache/solr/common/util/URLUtil.java
index e4e97e355ac..75ee914ea1a 100644
--- a/solr/solrj/src/java/org/apache/solr/common/util/URLUtil.java
+++ b/solr/solrj/src/java/org/apache/solr/common/util/URLUtil.java
@@ -179,7 +179,7 @@ public class URLUtil {
    * @param baseUri the base URI (e.g., URI for "http://localhost:8983/solr")
    * @param path the path to append (e.g., "/config/overlay" or "admin/cores"). May include a query
    *     string (e.g., "/select?q=test")
-   * @param queryParams optional query parameters to append (may be null). If the path already
+   * @param queryParams optional query parameters to append (can be null). If the path already
    *     contains a query string, these params will be added to it.
    * @return a properly encoded URI
    * @throws IllegalArgumentException if the baseUri or path are invalid
diff --git a/solr/solrj/src/java/org/apache/solr/common/util/Utils.java b/solr/solrj/src/java/org/apache/solr/common/util/Utils.java
index acbbdac41d7..1657366840d 100644
--- a/solr/solrj/src/java/org/apache/solr/common/util/Utils.java
+++ b/solr/solrj/src/java/org/apache/solr/common/util/Utils.java
@@ -17,7 +17,6 @@
 package org.apache.solr.common.util;
 
 import static java.nio.charset.StandardCharsets.UTF_8;
-import static java.util.concurrent.TimeUnit.NANOSECONDS;
 import static org.apache.solr.common.SolrException.ErrorCode.SERVER_ERROR;
 
 import com.fasterxml.jackson.annotation.JsonAnyGetter;
@@ -63,7 +62,6 @@ import java.util.Random;
 import java.util.Set;
 import java.util.TreeMap;
 import java.util.TreeSet;
-import java.util.concurrent.Callable;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.TimeUnit;
 import java.util.function.BiConsumer;
@@ -82,7 +80,6 @@ import org.noggit.CharArr;
 import org.noggit.JSONParser;
 import org.noggit.JSONWriter;
 import org.noggit.ObjectBuilder;
-import org.slf4j.Logger;
 
 public class Utils {
 
@@ -366,20 +363,6 @@ public class Utils {
         }
       };
 
-  public static final Function<JSONParser, ObjectBuilder> MAPOBJBUILDER =
-      jsonParser -> {
-        try {
-          return new ObjectBuilder(jsonParser) {
-            @Override
-            public Object newObject() {
-              return new HashMap<>();
-            }
-          };
-        } catch (IOException e) {
-          throw new RuntimeException(e);
-        }
-      };
-
   /**
    * Util function to convert {@link Object} to {@link String} Specially handles {@link Date} to
    * string conversion
@@ -714,19 +697,6 @@ public class Utils {
     return isModified;
   }
 
-  /**
-   * Given a URL string with or without a scheme, return a new URL with the correct scheme applied.
-   *
-   * @param url A URL to change the scheme (http|https)
-   * @return A new URL with the correct scheme
-   */
-  public static String applyUrlScheme(final String url, final String urlScheme) {
-    Objects.requireNonNull(url, "URL must not be null!");
-    // heal an incorrect scheme if needed, otherwise return null indicating no change
-    final int at = url.indexOf("://");
-    return (at == -1) ? (urlScheme + "://" + url) : urlScheme + url.substring(at);
-  }
-
   /**
    * Construct a V1 base url for the Solr node, given its name (e.g., 'app-node-1:8983_solr') and a
    * URL scheme.
@@ -764,19 +734,6 @@ public class Utils {
     return unit.convert(timeSource.getTimeNs(), TimeUnit.NANOSECONDS);
   }
 
-  public static long timeElapsed(TimeSource timeSource, long start, TimeUnit unit) {
-    return unit.convert(timeSource.getTimeNs() - NANOSECONDS.convert(start, unit), NANOSECONDS);
-  }
-
-  public static <T> T handleExp(Logger logger, T def, Callable<T> c) {
-    try {
-      return c.call();
-    } catch (Exception e) {
-      logger.error(e.getMessage(), e);
-    }
-    return def;
-  }
-
   public interface InputStreamConsumer<T> {
 
     T accept(InputStream is) throws IOException;
diff --git a/solr/solrj/src/java/org/apache/solr/common/util/XML.java b/solr/solrj/src/java/org/apache/solr/common/util/XML.java
index 168b1b8b8ea..a0cf62c6570 100644
--- a/solr/solrj/src/java/org/apache/solr/common/util/XML.java
+++ b/solr/solrj/src/java/org/apache/solr/common/util/XML.java
@@ -18,8 +18,6 @@ package org.apache.solr.common.util;
 
 import java.io.IOException;
 import java.io.Writer;
-import java.util.Map;
-import java.util.stream.Stream;
 
 /** */
 public class XML {
@@ -82,43 +80,26 @@ public class XML {
     escape(str, out, attribute_escapes);
   }
 
-  public static void escapeAttributeValue(char[] chars, int start, int length, Writer out)
-      throws IOException {
-    escape(chars, start, length, out, attribute_escapes);
-  }
-
   /**
    * does NOT escape character data in val; it must already be valid XML. Attributes are always
    * escaped.
    */
-  public static final void writeUnescapedXML(Writer out, String tag, String val, Object... attrs)
+  public static void writeUnescapedXML(Writer out, String tag, String val, Object... attrs)
       throws IOException {
     writeXML(out, tag, (writer1) -> writer1.write(val), attrs);
   }
 
   /** escapes character data in val and attributes */
-  public static final void writeXML(Writer out, String tag, String val, Object... attrs)
+  public static void writeXML(Writer out, String tag, String val, Object... attrs)
       throws IOException {
     final Writable writable = val != null ? (writer1) -> XML.escapeCharData(val, writer1) : null;
     writeXML(out, tag, writable, attrs);
   }
 
-  /** escapes character data in val and attributes */
-  public static void writeXML(Writer out, String tag, String val, Map<String, String> attrs)
-      throws IOException {
-    writeXML(
-        out,
-        tag,
-        val,
-        attrs.entrySet().stream()
-            .flatMap((entry) -> Stream.of(entry.getKey(), entry.getValue()))
-            .toArray());
-  }
-
   /**
    * @lucene.internal
    */
-  public static final void writeXML(Writer out, String tag, Writable valWritable, Object... attrs)
+  public static void writeXML(Writer out, String tag, Writable valWritable, Object... attrs)
       throws IOException {
     out.write('<');
     out.write(tag);
@@ -149,21 +130,6 @@ public class XML {
     void write(Writer w) throws IOException;
   }
 
-  private static void escape(char[] chars, int offset, int length, Writer out, String[] escapes)
-      throws IOException {
-    for (int i = offset; i < length; i++) {
-      char ch = chars[i];
-      if (ch < escapes.length) {
-        String replacement = escapes[ch];
-        if (replacement != null) {
-          out.write(replacement);
-          continue;
-        }
-      }
-      out.write(ch);
-    }
-  }
-
   private static void escape(String str, Writer out, String[] escapes) throws IOException {
     for (int i = 0; i < str.length(); i++) {
       char ch = str.charAt(i);


(solr) 10/13: SolrRequest.setPath fix; allow null (#4686)

Posted by ds...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

dsmiley pushed a commit to branch branch_10x
in repository https://gitbox.apache.org/repos/asf/solr.git

commit ddba8752b8e1a9dc99277505c8a395f283eafa8f
Author: David Smiley <ds...@apache.org>
AuthorDate: Sat Aug 1 12:30:51 2026 -0400

    SolrRequest.setPath fix; allow null (#4686)
    
    Fixes a temporary regression from #4665
    
    (cherry picked from commit 14405d7ec176cc5db264eb4ffb70355b3916369e)
---
 .../src/java/org/apache/solr/client/solrj/SolrRequest.java    | 11 +++++++----
 1 file changed, 7 insertions(+), 4 deletions(-)

diff --git a/solr/solrj/src/java/org/apache/solr/client/solrj/SolrRequest.java b/solr/solrj/src/java/org/apache/solr/client/solrj/SolrRequest.java
index 7574bd38967..fb975b9bab2 100644
--- a/solr/solrj/src/java/org/apache/solr/client/solrj/SolrRequest.java
+++ b/solr/solrj/src/java/org/apache/solr/client/solrj/SolrRequest.java
@@ -157,7 +157,7 @@ public abstract class SolrRequest<T> implements Serializable {
 
   public SolrRequest(METHOD m, String path, SolrRequestType requestType) {
     this.method = m;
-    this.path = path;
+    this.path = validatePath(path);
     this.requestType = requestType;
   }
 
@@ -182,11 +182,14 @@ public abstract class SolrRequest<T> implements Serializable {
   }
 
   public void setPath(String path) {
-    if (path == null || !path.startsWith("/")) {
+    this.path = validatePath(path);
+  }
+
+  private static String validatePath(String path) {
+    if (path != null && !path.startsWith("/")) {
       throw new IllegalArgumentException("Must start with a '/': " + path);
     }
-
-    this.path = path;
+    return path;
   }
 
   /**


(solr) 03/13: SOLR-18099: CollapseQParser extensibility (#4112)

Posted by ds...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

dsmiley pushed a commit to branch branch_10x
in repository https://gitbox.apache.org/repos/asf/solr.git

commit 9b610b9a91d6f7cd12598d816c8925ed3d3d735c
Author: David Smiley <ds...@apache.org>
AuthorDate: Wed Jul 29 22:32:43 2026 -0400

    SOLR-18099: CollapseQParser extensibility (#4112)
    
    - `CollapsingQParserPlugin.java` — large refactor consolidating the many near-duplicate collector classes onto a shared `AbstractCollapseCollector` template-method base and converting `GroupHeadSelectorType` to a record; also swaps the collapsed-doc accumulator from `FixedBitSet` to `DocIdSetBuilder` to save memory on sparse result sets (benchmarked with no measurable speed regression). Net effect: ~575 fewer lines while opening up extension points for custom group-head selection.
    - `{IntFloatDynamicMap.java,IntIntDynamicMap.java,IntLongDynamicMap.java,DynamicMap.java}` — add a tracked `size()` so the refactored collectors can size `DocIdSetBuilder` growth calls.
    - `BitDocSet.java` — widen `makeQuery()`'s return type to `Query` to support subclassing.
    - `{TestCollapseQParserPlugin.java,TestRandomCollapseQParserPlugin.java}` — updated for the refactored collector APIs.
    - `collapse-and-expand-results.adoc` — doc touch-ups reflecting the refactor.
    
    (cherry picked from commit a77b42f784f85f0de7deb6fc0a0b0b889d82ecc4)
---
 .../src/java/org/apache/solr/search/BitDocSet.java |    3 +-
 .../solr/search/CollapsingQParserPlugin.java       | 4141 +++++++++-----------
 .../src/java/org/apache/solr/util/DynamicMap.java  |    3 +
 .../org/apache/solr/util/IntFloatDynamicMap.java   |   19 +-
 .../org/apache/solr/util/IntIntDynamicMap.java     |   19 +-
 .../org/apache/solr/util/IntLongDynamicMap.java    |   19 +-
 .../solr/search/TestCollapseQParserPlugin.java     |   16 +-
 .../search/TestRandomCollapseQParserPlugin.java    |    5 +-
 .../pages/collapse-and-expand-results.adoc         |   17 +-
 9 files changed, 1857 insertions(+), 2385 deletions(-)

diff --git a/solr/core/src/java/org/apache/solr/search/BitDocSet.java b/solr/core/src/java/org/apache/solr/search/BitDocSet.java
index db55581b339..f42185473fe 100644
--- a/solr/core/src/java/org/apache/solr/search/BitDocSet.java
+++ b/solr/core/src/java/org/apache/solr/search/BitDocSet.java
@@ -20,6 +20,7 @@ import java.util.Collection;
 import java.util.List;
 import org.apache.lucene.index.LeafReaderContext;
 import org.apache.lucene.search.DocIdSetIterator;
+import org.apache.lucene.search.Query;
 import org.apache.lucene.util.Accountable;
 import org.apache.lucene.util.BitSetIterator;
 import org.apache.lucene.util.FixedBitSet;
@@ -320,7 +321,7 @@ public class BitDocSet extends DocSet {
   }
 
   @Override
-  public DocSetQuery makeQuery() {
+  public Query makeQuery() {
     return new DocSetQuery(this);
   }
 
diff --git a/solr/core/src/java/org/apache/solr/search/CollapsingQParserPlugin.java b/solr/core/src/java/org/apache/solr/search/CollapsingQParserPlugin.java
index 5c76a1eb98c..044b9894d97 100644
--- a/solr/core/src/java/org/apache/solr/search/CollapsingQParserPlugin.java
+++ b/solr/core/src/java/org/apache/solr/search/CollapsingQParserPlugin.java
@@ -47,6 +47,7 @@ import org.apache.lucene.index.LeafReaderContext;
 import org.apache.lucene.index.MultiDocValues;
 import org.apache.lucene.index.NumericDocValues;
 import org.apache.lucene.index.OrdinalMap;
+import org.apache.lucene.index.ReaderUtil;
 import org.apache.lucene.index.SortedDocValues;
 import org.apache.lucene.queries.function.FunctionQuery;
 import org.apache.lucene.queries.function.FunctionValues;
@@ -63,9 +64,8 @@ import org.apache.lucene.search.ScoreMode;
 import org.apache.lucene.search.Sort;
 import org.apache.lucene.search.SortField;
 import org.apache.lucene.util.ArrayUtil;
-import org.apache.lucene.util.BitSetIterator;
 import org.apache.lucene.util.BytesRef;
-import org.apache.lucene.util.FixedBitSet;
+import org.apache.lucene.util.DocIdSetBuilder;
 import org.apache.lucene.util.LongValues;
 import org.apache.solr.common.SolrException;
 import org.apache.solr.common.params.GroupParams;
@@ -145,51 +145,33 @@ public class CollapsingQParserPlugin extends QParserPlugin {
    */
   public static String COLLECT_ELEVATED_DOCS_WHEN_COLLAPSING = "collectElevatedDocsWhenCollapsing";
 
-  /**
-   * @deprecated use {@link NullPolicy} instead.
-   */
-  @Deprecated public static final String NULL_COLLAPSE = "collapse";
-
-  @Deprecated public static final String NULL_IGNORE = "ignore";
-  @Deprecated public static final String NULL_EXPAND = "expand";
-  @Deprecated public static final String HINT_MULTI_DOCVALUES = "multi_docvalues";
-
   public enum NullPolicy {
-    IGNORE("ignore", 0),
-    COLLAPSE("collapse", 1),
-    EXPAND("expand", 2);
+    IGNORE("ignore"),
+    COLLAPSE("collapse"),
+    EXPAND("expand");
 
     private final String name;
-    private final int code;
 
-    NullPolicy(String name, int code) {
+    NullPolicy(String name) {
       this.name = name;
-      this.code = code;
     }
 
     public String getName() {
       return name;
     }
 
-    public int getCode() {
-      return code;
-    }
-
     public static NullPolicy fromString(String nullPolicy) {
       if (StrUtils.isNullOrEmpty(nullPolicy)) {
         return DEFAULT_POLICY;
       }
-      switch (nullPolicy) {
-        case "ignore":
-          return IGNORE;
-        case "collapse":
-          return COLLAPSE;
-        case "expand":
-          return EXPAND;
-        default:
-          throw new SolrException(
-              SolrException.ErrorCode.BAD_REQUEST, "Invalid nullPolicy: " + nullPolicy);
-      }
+      return switch (nullPolicy) {
+        case "ignore" -> IGNORE;
+        case "collapse" -> COLLAPSE;
+        case "expand" -> EXPAND;
+        default ->
+            throw new SolrException(
+                SolrException.ErrorCode.BAD_REQUEST, "Invalid nullPolicy: " + nullPolicy);
+      };
     }
 
     static final NullPolicy DEFAULT_POLICY = IGNORE;
@@ -222,50 +204,30 @@ public class CollapsingQParserPlugin extends QParserPlugin {
     MIN,
     MAX,
     SORT,
-    SCORE;
+    SCORE,
+    /** For use outside the Solr codebase */
+    CUSTOM;
     public static final EnumSet<GroupHeadSelectorType> MIN_MAX = EnumSet.of(MIN, MAX);
   }
 
-  /** Models all the information about how group head documents should be selected */
-  public static final class GroupHeadSelector {
-
-    /**
-     * The param value for this selector whose meaning depends on type. (ie: a field or valuesource
-     * for MIN/MAX, a sort string for SORT, "score" for SCORE). Will never be null.
-     */
-    public final String selectorText;
-
-    /** The type for this selector, will never be null */
-    public final GroupHeadSelectorType type;
+  /**
+   * Models all the information about how group head documents should be selected
+   *
+   * @param type The type for this selector, will never be null
+   * @param selectorText The param value for this selector whose meaning depends on type. (ie: a
+   *     field or valuesource for MIN/MAX, a sort string for SORT, "score" for SCORE). Will never be
+   *     null.
+   */
+  public record GroupHeadSelector(GroupHeadSelectorType type, String selectorText) {
 
-    private GroupHeadSelector(String s, GroupHeadSelectorType type) {
-      assert null != s;
+    public GroupHeadSelector {
+      assert null != selectorText;
       assert null != type;
-
-      this.selectorText = s;
-      this.type = type;
-    }
-
-    @Override
-    public boolean equals(final Object other) {
-      if (other instanceof GroupHeadSelector that) {
-        return (this.type == that.type) && this.selectorText.equals(that.selectorText);
-      }
-      return false;
-    }
-
-    @Override
-    public int hashCode() {
-      return 17 * (31 + selectorText.hashCode()) * (31 + type.hashCode());
-    }
-
-    @Override
-    public String toString() {
-      return "GroupHeadSelector(selectorText=" + this.selectorText + ", type=" + this.type + ")";
     }
 
     /** returns a new GroupHeadSelector based on the specified local params */
     public static GroupHeadSelector build(final SolrParams localParams) {
+      // note: subclasses using CUSTOM should do their own build logic
       final String sortString =
           StrUtils.isBlank(localParams.get(SORT)) ? null : localParams.get(SORT);
       final String max = StrUtils.isBlank(localParams.get("max")) ? null : localParams.get("max");
@@ -279,28 +241,41 @@ public class CollapsingQParserPlugin extends QParserPlugin {
       }
 
       if (null != sortString) {
-        return new GroupHeadSelector(sortString, GroupHeadSelectorType.SORT);
+        return new GroupHeadSelector(GroupHeadSelectorType.SORT, sortString);
       } else if (null != min) {
-        return new GroupHeadSelector(min, GroupHeadSelectorType.MIN);
+        return new GroupHeadSelector(GroupHeadSelectorType.MIN, min);
       } else if (null != max) {
-        return new GroupHeadSelector(max, GroupHeadSelectorType.MAX);
+        return new GroupHeadSelector(GroupHeadSelectorType.MAX, max);
       }
       // default
-      return new GroupHeadSelector("score", GroupHeadSelectorType.SCORE);
+      return new GroupHeadSelector(GroupHeadSelectorType.SCORE, "score");
+    }
+
+    /**
+     * Determines if scores are needed for collapsing based on this selector's type and
+     * configuration.
+     *
+     * @param sortSpec the SortSpec if this selector is SORT type, otherwise may be null
+     * @return true if scores are needed for the collapsing operation
+     */
+    public boolean needsScores(SortSpec sortSpec) {
+      return GroupHeadSelectorType.SCORE.equals(this.type)
+          || (GroupHeadSelectorType.SORT.equals(this.type) && sortSpec.includesScore())
+          || (GroupHeadSelectorType.MIN_MAX.contains(this.type)
+              && CollapseScore.wantsCScore(this.selectorText));
     }
   }
 
   public static class CollapsingPostFilter extends ExtendedQueryBase implements PostFilter {
 
-    private String collapseField;
-    private final GroupHeadSelector groupHeadSelector;
-    private final SortSpec sortSpec; // may be null, parsed at most once from groupHeadSelector
-    public String hint;
-    private boolean needsScores = true;
-    private boolean needsScores4Collapsing = false;
-    private NullPolicy nullPolicy;
-    private Set<BytesRef> boosted; // ordered by "priority"
-    private int size;
+    protected final String collapseField;
+    protected final GroupHeadSelector groupHeadSelector;
+    protected final SortSpec sortSpec; // may be null, parsed at most once from groupHeadSelector
+    public final String hint;
+    protected final boolean needsScores4Collapsing;
+    protected final NullPolicy nullPolicy;
+    protected final boolean collectElevatedDocsWhenCollapsing;
+    protected final int initialSize;
 
     public String getField() {
       return this.collapseField;
@@ -333,7 +308,8 @@ public class CollapsingQParserPlugin extends QParserPlugin {
     private boolean equalsTo(CollapsingPostFilter other) {
       return collapseField.equals(other.collapseField)
           && groupHeadSelector.equals(other.groupHeadSelector)
-          && nullPolicy == other.nullPolicy;
+          && nullPolicy == other.nullPolicy
+          && collectElevatedDocsWhenCollapsing == other.collectElevatedDocsWhenCollapsing;
     }
 
     @Override
@@ -356,7 +332,7 @@ public class CollapsingQParserPlugin extends QParserPlugin {
           + this.groupHeadSelector
           + (hint == null ? "" : ", hint=" + this.hint)
           + ", size="
-          + this.size
+          + this.initialSize
           + ")";
     }
 
@@ -389,7 +365,7 @@ public class CollapsingQParserPlugin extends QParserPlugin {
             SolrException.ErrorCode.BAD_REQUEST, "Collapsing not supported on multivalued fields");
       }
 
-      this.groupHeadSelector = GroupHeadSelector.build(localParams);
+      this.groupHeadSelector = buildGroupHeadSelector(localParams);
 
       if (groupHeadSelector.type.equals(GroupHeadSelectorType.SORT)
           && CollapseScore.wantsCScore(groupHeadSelector.selectorText)) {
@@ -409,7 +385,8 @@ public class CollapsingQParserPlugin extends QParserPlugin {
               : null;
 
       this.hint = localParams.get("hint");
-      this.size = localParams.getInt("size", 100000); // Only used for collapsing on int fields.
+      this.initialSize =
+          localParams.getInt("size", 100_000); // Only used for collapsing on int fields.
 
       {
         final SolrRequestInfo info = SolrRequestInfo.getRequestInfo();
@@ -417,71 +394,212 @@ public class CollapsingQParserPlugin extends QParserPlugin {
 
         // may be null in some esoteric corner usages
         final ResponseBuilder rb = info.getResponseBuilder();
-        final SortSpec topSort = null == rb ? null : rb.getSortSpec();
-
-        this.needsScores4Collapsing =
-            GroupHeadSelectorType.SCORE.equals(groupHeadSelector.type)
-                || (GroupHeadSelectorType.SORT.equals(groupHeadSelector.type)
-                    && this.sortSpec.includesScore())
-                || (GroupHeadSelectorType.MIN_MAX.contains(groupHeadSelector.type)
-                    && CollapseScore.wantsCScore(groupHeadSelector.selectorText));
-        this.needsScores =
-            needsScores4Collapsing
-                || (info.getRsp().getReturnFields().wantsScore()
-                    || (null != topSort && topSort.includesScore())
-                    || (this.boosted != null));
-
-        if (this.needsScores && null != rb) {
-          // regardless of why we need scores ensure the IndexSearcher will compute them
-          // for the "real" docs.  (ie: maybe we need them because we were
-          // asked to compute them for the collapsed docs, maybe we need them because in
-          // order to find the groupHead we need them computed for us.
 
+        this.needsScores4Collapsing = groupHeadSelector.needsScores(this.sortSpec);
+
+        if (this.needsScores4Collapsing && null != rb) {
+          // ensure the IndexSearcher will compute scores for the "real" docs
+          // when we need them to find the groupHead
           rb.setFieldFlags(rb.getFieldFlags() | SolrIndexSearcher.GET_SCORES);
         }
       }
 
       this.nullPolicy = NullPolicy.fromString(localParams.get("nullPolicy"));
+
+      this.collectElevatedDocsWhenCollapsing =
+          params.getBool(COLLECT_ELEVATED_DOCS_WHEN_COLLAPSING, true);
+    }
+
+    protected GroupHeadSelector buildGroupHeadSelector(SolrParams localParams) {
+      return GroupHeadSelector.build(localParams);
     }
 
     @Override
-    @SuppressWarnings({"unchecked"})
     public DelegatingCollector getFilterCollector(IndexSearcher indexSearcher) {
       try {
+        return this.getFilterCollector((SolrIndexSearcher) indexSearcher);
+      } catch (IOException e) {
+        throw new RuntimeException(e);
+      }
+    }
+
+    protected DelegatingCollector getFilterCollector(SolrIndexSearcher searcher)
+        throws IOException {
+      // We have to deal with it here rather than the constructor because
+      //  the QueryElevationComponent runs after the Queries are constructed.
+      IntIntHashMap boostDocs = getElevatedBoostDocsMap(searcher);
+
+      // block collapsing logic is much simpler and uses less memory, but is only viable in specific
+      // situations
+      final boolean blockCollapse =
+          (("_root_".equals(collapseField) || HINT_BLOCK.equals(hint))
+              // because we currently handle all min/max cases using
+              // AbstractBlockSortSpecCollector, we can't handle functions wrapping cscore()
+              // (for the same reason cscore() isn't supported in 'sort' local param)
+              && (!CollapseScore.wantsCScore(groupHeadSelector.selectorText))
+              //
+              && NullPolicy.COLLAPSE != nullPolicy);
+      if (HINT_BLOCK.equals(hint) && !blockCollapse) {
+        log.debug(
+            "Query specifies hint={} but other local params prevent the use block based collapse",
+            HINT_BLOCK);
+      }
 
-        SolrIndexSearcher searcher = (SolrIndexSearcher) indexSearcher;
-        CollectorFactory collectorFactory = new CollectorFactory();
-        // Deal with boosted docs.
-        // We have to deal with it here rather then the constructor because
-        // because the QueryElevationComponent runs after the Queries are constructed.
+      SchemaField schemaField = searcher.getSchema().getField(collapseField);
+      DocValuesProducer docValuesProducer =
+          getDocValuesProducer(schemaField, hint, searcher, blockCollapse);
+      FieldType collapseFieldType = schemaField.getType();
 
-        IntIntHashMap boostDocsMap = null;
-        Map<Object, Object> context = null;
-        SolrRequestInfo info = SolrRequestInfo.getRequestInfo();
-        if (info != null) {
-          context = info.getReq().getContext();
+      FunctionQuery funcQuery = null;
+      FieldType minMaxFieldType = null;
+      if (GroupHeadSelectorType.MIN_MAX.contains(groupHeadSelector.type)) {
+        final String text = groupHeadSelector.selectorText;
+        if (!text.contains("(")) {
+          minMaxFieldType = searcher.getSchema().getField(text).getType();
+        } else {
+          SolrParams params = new ModifiableSolrParams();
+          try (SolrQueryRequest request = SolrQueryRequest.wrapSearcher(searcher, params)) {
+            FunctionQParser functionQParser = new FunctionQParser(text, null, params, request);
+            funcQuery = (FunctionQuery) functionQParser.parse();
+          } catch (SyntaxError e) {
+            throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, e);
+          }
         }
+      }
+
+      if (GroupHeadSelectorType.SCORE.equals(groupHeadSelector.type)) {
+
+        if (collapseFieldType instanceof StrField) {
+          if (blockCollapse) {
+            return new BlockOrdScoreCollector(collapseField, nullPolicy, boostDocs);
+          }
+          return new OrdScoreCollector(searcher, docValuesProducer, nullPolicy, boostDocs);
+
+        } else if (isNumericCollapsible(collapseFieldType)) {
+          if (blockCollapse) {
+            return new BlockIntScoreCollector(collapseField, nullPolicy, boostDocs);
+          }
 
-        if (this.boosted == null && context != null) {
-          this.boosted = (Set<BytesRef>) context.get(QueryElevationComponent.BOOSTED);
+          return new IntScoreCollector(searcher, nullPolicy, boostDocs, collapseField, initialSize);
+
+        } else {
+          throw new SolrException(
+              SolrException.ErrorCode.BAD_REQUEST,
+              "Collapsing field should be of either String, Int or Float type");
         }
 
-        boostDocsMap = QueryElevationComponent.getBoostDocs(searcher, this.boosted, context);
-        return collectorFactory.getCollector(
-            this.collapseField,
-            this.groupHeadSelector,
-            this.sortSpec,
-            this.nullPolicy.getCode(),
-            this.hint,
-            this.needsScores4Collapsing,
-            this.needsScores,
-            this.size,
-            boostDocsMap,
-            searcher);
+      } else { // min, max, sort, etc.. something other then just "score"
 
-      } catch (IOException e) {
-        throw new RuntimeException(e);
+        if (collapseFieldType instanceof StrField) {
+          if (blockCollapse) {
+            // NOTE: for now we don't worry about whether this is a sortSpec of min/max
+            // groupHeadSelector, we use a "sort spec' based block collector unless/until there is
+            // some (performance?) reason to specialize
+            return new BlockOrdSortSpecCollector(
+                collapseField,
+                nullPolicy,
+                boostDocs,
+                BlockOrdSortSpecCollector.getSort(
+                    groupHeadSelector, sortSpec, funcQuery, searcher));
+          }
+
+          return new OrdFieldCollectorBuilder(
+                  groupHeadSelector,
+                  docValuesProducer,
+                  nullPolicy,
+                  needsScores4Collapsing,
+                  boostDocs,
+                  searcher)
+              .build(sortSpec, minMaxFieldType, funcQuery);
+
+        } else if (isNumericCollapsible(collapseFieldType)) {
+
+          if (blockCollapse) {
+            // NOTE: for now we don't worry about whether this is a sortSpec of min/max
+            // groupHeadSelector, we use a "sort spec' based block collector unless/until there is
+            // some (performance?) reason to specialize
+            return new BlockIntSortSpecCollector(
+                collapseField,
+                nullPolicy,
+                boostDocs,
+                BlockOrdSortSpecCollector.getSort(
+                    groupHeadSelector, sortSpec, funcQuery, searcher));
+          }
+
+          return new IntFieldCollectorBuilder(
+                  groupHeadSelector,
+                  nullPolicy,
+                  collapseField,
+                  initialSize,
+                  needsScores4Collapsing,
+                  boostDocs,
+                  searcher)
+              .build(sortSpec, minMaxFieldType, funcQuery);
+        } else {
+          throw new SolrException(
+              SolrException.ErrorCode.BAD_REQUEST,
+              "Collapsing field should be of either String, Int or Float type");
+        }
+      }
+    }
+
+    @SuppressWarnings({"unchecked"})
+    protected IntIntHashMap getElevatedBoostDocsMap(SolrIndexSearcher indexSearcher)
+        throws IOException {
+      if (!collectElevatedDocsWhenCollapsing) {
+        return null;
+      }
+      SolrRequestInfo info = SolrRequestInfo.getRequestInfo();
+      if (info != null) {
+        var context = info.getReq().getContext();
+        var boosted = (Set<BytesRef>) context.get(QueryElevationComponent.BOOSTED);
+        return QueryElevationComponent.getBoostDocs(indexSearcher, boosted, context);
+      }
+      return null;
+    }
+
+    private boolean isNumericCollapsible(FieldType collapseFieldType) {
+      return switch (collapseFieldType.getNumberType()) {
+        case NumberType.INTEGER, NumberType.FLOAT -> true;
+        default -> false;
+      };
+    }
+
+    protected DocValuesProducer getDocValuesProducer(
+        SchemaField schemaField, String hint, SolrIndexSearcher searcher, boolean blockCollapse) {
+      if (schemaField.getType() instanceof StrField) {
+        // if we are using blockCollapse, then there is no need to bother with TOP_FC
+        if (HINT_TOP_FC.equals(hint) && !blockCollapse) {
+          @SuppressWarnings("resource")
+          final LeafReader uninvertingReader = getTopFieldCacheReader(searcher, collapseField);
+
+          return new EmptyDocValuesProducer() {
+            @Override
+            public SortedDocValues getSorted(FieldInfo ignored) throws IOException {
+              SortedDocValues values = uninvertingReader.getSortedDocValues(collapseField);
+              if (values != null) {
+                return values;
+              } else {
+                return DocValues.emptySorted();
+              }
+            }
+          };
+        } else {
+          return new EmptyDocValuesProducer() {
+            @Override
+            public SortedDocValues getSorted(FieldInfo ignored) throws IOException {
+              return DocValues.getSorted(searcher.getSlowAtomicReader(), collapseField);
+            }
+          };
+        }
+      } else {
+        if (HINT_TOP_FC.equals(hint)) {
+          throw new SolrException(
+              SolrException.ErrorCode.BAD_REQUEST,
+              "top_fc hint is only supported when collapsing on String Fields");
+        }
       }
+      return null;
     }
   }
 
@@ -583,225 +701,337 @@ public class CollapsingQParserPlugin extends QParserPlugin {
     }
   }
 
+  private abstract static class CachedScoreScorable extends Scorable {
+    private final DocIdSetIterator disi;
+    private int cachedDocId = -1;
+    private float cachedScore;
+
+    CachedScoreScorable(DocIdSetIterator disi) {
+      this.disi = disi;
+    }
+
+    @Override
+    public final float score() throws IOException {
+      int docId = disi.docID();
+      if (docId != cachedDocId) {
+        cachedDocId = docId;
+        cachedScore = computeScore(docId);
+      }
+      return cachedScore;
+    }
+
+    protected abstract float computeScore(int globalDoc) throws IOException;
+  }
+
   /**
-   * Collapses on Ordinal Values using Score to select the group head.
+   * Abstract base class for all collapse collectors. Provides common configuration and result state
+   * shared across ordinal and integer-based collapse strategies.
    *
    * @lucene.internal
    */
-  static class OrdScoreCollector extends DelegatingCollector {
-
-    private LeafReaderContext[] contexts;
-    private final DocValuesProducer collapseValuesProducer;
-    private FixedBitSet collapsedSet;
-    private SortedDocValues collapseValues;
-    private OrdinalMap ordinalMap;
-    private SortedDocValues segmentValues;
-    private LongValues segmentOrdinalMap;
-    private MultiDocValues.MultiSortedDocValues multiSortedDocValues;
-    private IntIntDynamicMap ords;
-    private IntFloatDynamicMap scores;
-    private int maxDoc;
-    private int nullPolicy;
-    private float nullScore = -Float.MAX_VALUE;
-    private int nullDoc = -1;
-    private boolean collectElevatedDocsWhenCollapsing;
-    private FloatArrayList nullScores;
-
-    private final BoostedDocsCollector boostedDocsCollector;
+  protected abstract static class AbstractCollapseCollector extends DelegatingCollector {
+    // Configuration
+    protected final List<LeafReaderContext> contexts;
+    protected final int maxDoc;
+    protected final NullPolicy nullPolicy;
+    protected final boolean needsScores4Collapsing;
+    protected boolean needsScores; // cached from scoreMode()
+
+    // Results/accumulator
+    protected final DocIdSetBuilder collapsedSet;
+    protected final BoostedDocsCollector boostedDocsCollector;
+    protected FloatArrayList nullScores;
+    protected float nullScore;
+    protected int nullDoc = -1;
 
-    public OrdScoreCollector(
-        int maxDoc,
-        int segments,
-        DocValuesProducer collapseValuesProducer,
-        int nullPolicy,
-        IntIntHashMap boostDocsMap,
+    protected AbstractCollapseCollector(
         IndexSearcher searcher,
-        boolean collectElevatedDocsWhenCollapsing)
-        throws IOException {
-      this.maxDoc = maxDoc;
-      this.contexts = new LeafReaderContext[segments];
-      this.collectElevatedDocsWhenCollapsing = collectElevatedDocsWhenCollapsing;
-      List<LeafReaderContext> con = searcher.getTopReaderContext().leaves();
-      for (int i = 0; i < con.size(); i++) {
-        contexts[i] = con.get(i);
-      }
-
-      this.collapsedSet = new FixedBitSet(maxDoc);
-      this.collapseValuesProducer = collapseValuesProducer;
-      this.collapseValues = collapseValuesProducer.getSorted(null);
+        NullPolicy nullPolicy,
+        boolean needsScores4Collapsing,
+        IntIntHashMap boostDocsMap) {
 
-      int valueCount = collapseValues.getValueCount();
-      if (collapseValues instanceof MultiDocValues.MultiSortedDocValues) {
-        this.multiSortedDocValues = (MultiDocValues.MultiSortedDocValues) collapseValues;
-        this.ordinalMap = multiSortedDocValues.mapping;
-      }
-      this.ords = new IntIntDynamicMap(valueCount, -1);
-      this.scores = new IntFloatDynamicMap(valueCount, -Float.MAX_VALUE);
+      this.contexts = searcher.getTopReaderContext().leaves();
+      this.maxDoc = searcher.getIndexReader().maxDoc();
       this.nullPolicy = nullPolicy;
-      if (nullPolicy == NullPolicy.EXPAND.getCode()) {
-        nullScores = new FloatArrayList();
-      }
+      this.needsScores4Collapsing = needsScores4Collapsing;
+
+      this.collapsedSet = new DocIdSetBuilder(Math.max(1, maxDoc));
       this.boostedDocsCollector = BoostedDocsCollector.build(boostDocsMap);
     }
 
     @Override
     public ScoreMode scoreMode() {
-      return ScoreMode.COMPLETE;
+      return needsScores4Collapsing ? ScoreMode.COMPLETE : super.scoreMode();
     }
 
-    @Override
-    protected void doSetNextReader(LeafReaderContext context) throws IOException {
-      this.contexts[context.ord] = context;
-      this.docBase = context.docBase;
-      if (ordinalMap != null) {
-        this.segmentValues = this.multiSortedDocValues.values[context.ord];
-        this.segmentOrdinalMap = ordinalMap.getGlobalOrds(context.ord);
-      } else {
-        this.segmentValues = collapseValues;
+    /**
+     * Initialize data structures for collection. Called once before collecting begins. This is
+     * useful for initialization dependent on {@link #needsScores}, which isn't known in the
+     * constructor.
+     */
+    protected void initializeCollection(boolean needsScores) {
+      if (needsScores && nullPolicy == NullPolicy.EXPAND) {
+        this.nullScores = new FloatArrayList();
       }
     }
 
     @Override
-    public void collect(int contextDoc) throws IOException {
-      int globalDoc = contextDoc + this.docBase;
-      int ord = -1;
-      if (this.ordinalMap != null) {
-        // Handle ordinalMapping case
-        if (segmentValues.advanceExact(contextDoc)) {
-          ord = (int) segmentOrdinalMap.get(segmentValues.ordValue());
-        } else {
-          ord = -1;
-        }
-      } else {
-        // Handle top Level FieldCache or Single Segment Case
-        if (segmentValues.advanceExact(globalDoc)) {
-          ord = segmentValues.ordValue();
-        } else {
-          ord = -1;
-        }
-      }
-
-      if (collectElevatedDocsWhenCollapsing) {
-        // Check to see if we have documents boosted by the QueryElevationComponent
-        if (0 <= ord) {
-          if (boostedDocsCollector.collectIfBoosted(ord, globalDoc)) return;
-        } else {
-          if (boostedDocsCollector.collectInNullGroupIfBoosted(globalDoc)) return;
-        }
+    protected void doSetNextReader(LeafReaderContext context) throws IOException {
+      if (this.context == null) { // first time detection
+        initializeCollection(this.needsScores = scoreMode().needsScores());
       }
 
-      if (ord > -1) {
-        float score = scorer.score();
-        if (score > scores.get(ord)) {
-          ords.put(ord, globalDoc);
-          scores.put(ord, score);
-        }
-      } else if (nullPolicy == NullPolicy.COLLAPSE.getCode()) {
-        float score = scorer.score();
-        if (score > nullScore) {
-          nullScore = score;
-          nullDoc = globalDoc;
-        }
-      } else if (nullPolicy == NullPolicy.EXPAND.getCode()) {
-        collapsedSet.set(globalDoc);
-        nullScores.add(scorer.score());
-      }
+      // Do NOT set leafDelegate (calling super() would do this).
+      // That's handled in complete() for these collectors.
+      assert this.contexts.get(context.ord) == context;
+      assert leafDelegate == null;
+      this.context = context;
+      this.docBase = context.docBase;
     }
 
+    /** Core/general algorithm */
     @Override
-    public void complete() throws IOException {
-      if (contexts.length == 0) {
-        return;
-      }
+    public final void complete() throws IOException {
 
-      // Handle the boosted docs.
-      boostedDocsCollector.purgeGroupsThatHaveBoostedDocs(
-          collapsedSet,
-          (ord) -> {
-            ords.remove(ord);
-          },
-          () -> {
-            nullDoc = -1;
-          });
+      DocIdSetIterator collapsedDocs = getCollapsedDocs();
 
-      // Build the sorted DocSet of group heads.
-      if (nullDoc > -1) {
-        collapsedSet.set(nullDoc);
-      }
-      ords.forEachValue(doc -> collapsedSet.set(doc));
+      int nextDocBase = 0;
+      int globalDoc;
 
-      int currentContext = 0;
-      int currentDocBase = 0;
+      while ((globalDoc = collapsedDocs.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) {
+        if (globalDoc >= nextDocBase) {
+          // finish previous leaf
+          if (leafDelegate != null) {
+            leafDelegate.finish();
+          }
 
-      collapseValues = collapseValuesProducer.getSorted(null);
+          int ctxIdx = ReaderUtil.subIndex(globalDoc, contexts);
+          context = contexts.get(ctxIdx);
+          docBase = context.docBase;
+          nextDocBase = ctxIdx + 1 < contexts.size() ? contexts.get(ctxIdx + 1).docBase : maxDoc;
+          leafDelegate = delegate.getLeafCollector(context);
+          if (delegate.scoreMode().needsScores()) {
+            scorer = getCollapsedScores(collapsedDocs, context);
+            leafDelegate.setScorer(scorer);
+          }
+        }
 
-      if (collapseValues instanceof MultiDocValues.MultiSortedDocValues) {
-        this.multiSortedDocValues = (MultiDocValues.MultiSortedDocValues) collapseValues;
-        this.ordinalMap = multiSortedDocValues.mapping;
+        leafDelegate.collect(globalDoc - docBase);
+      }
+
+      if (leafDelegate != null) {
+        leafDelegate.finish();
+      }
+
+      super.complete();
+    }
+
+    /**
+     * Produce the final list of global docs that we'll pass on through to delegated/chained
+     * collectors. This is the first step of {@link #complete()}.
+     */
+    protected DocIdSetIterator getCollapsedDocs() throws IOException {
+      // all subclasses have this common logic to do first regarding boosted/elevated & nullDoc:
+
+      boostedDocsCollector.addBoostedDocsTo(collapsedSet);
+
+      if (boostedDocsCollector.isBoostedNullGroup()) {
+        // If we're using IGNORE then no (matching) null docs were collected (by caller)
+        // If we're using EXPAND then all (matching) null docs were already collected (by us)
+        //   ...and that's *good* because each is treated like its own group, our boosts don't
+        // matter
+        // We only have to worry about removing null docs when using COLLAPSE, in which case any
+        // boosted null doc means we clear the group head of the null group.
+        nullDoc = -1;
+      }
+
+      if (nullDoc > -1) {
+        collapsedSet.grow(1).add(nullDoc);
+      }
+
+      finishCollapsedSet();
+
+      DocIdSetIterator iterator = collapsedSet.build().iterator();
+      return iterator != null ? iterator : DocIdSetIterator.empty();
+    }
+
+    /**
+     * Finishes adding docs to {@link #collapsedSet} so that it's ready. First step is usually to
+     * call {@link BoostedDocsCollector#visitBoostedGroupKeys(IntProcedure)} to ensure we don't add
+     * docs for these group keys as they have already been added by the caller, which are query
+     * elevated / boosted docs. Called by {@link #getCollapsedDocs()}
+     */
+    protected abstract void finishCollapsedSet();
+
+    /**
+     * Return a {@link Scorable} that provides the score for the current doc in the given {@code
+     * disi} (global doc IDs). Called once per segment during {@link #complete()}.
+     */
+    protected abstract Scorable getCollapsedScores(DocIdSetIterator disi, LeafReaderContext context)
+        throws IOException;
+
+    private MergeBoost mergeBoost;
+    private int nullScoreIndex = 0; // next nullScores index to return from scoreNullGroup if EXPAND
+
+    /** Returns the score for a null-group doc during {@link #complete()}. Only called once. */
+    protected float scoreNullGroup(int globalDoc) {
+      if (mergeBoost == null) { // lazy init
+        mergeBoost = boostedDocsCollector.getMergeBoost();
+      }
+      if (mergeBoost.boost(globalDoc)) { // has side effect
+        return 0F;
+      } else if (nullPolicy == NullPolicy.COLLAPSE) {
+        return nullScore;
+      } else if (nullPolicy == NullPolicy.EXPAND) {
+        return nullScores.get(nullScoreIndex++); // side effect
+      }
+      return 0F;
+    }
+  }
+
+  /**
+   * Collapses on Ordinal Values using Score to select the group head.
+   *
+   * @lucene.internal
+   */
+  static class OrdScoreCollector extends AbstractCollapseCollector {
+
+    // Source data
+    private final DocValuesProducer collapseValuesProducer;
+    private SortedDocValues collapseValues;
+    private OrdinalMap ordinalMap;
+    private MultiDocValues.MultiSortedDocValues multiSortedDocValues;
+    private SortedDocValues segmentValues;
+    private LongValues segmentOrdinalMap;
+
+    // Results/accumulator
+    private final IntIntDynamicMap ords;
+    private final IntFloatDynamicMap scores;
+
+    public OrdScoreCollector(
+        IndexSearcher searcher,
+        DocValuesProducer collapseValuesProducer,
+        NullPolicy nullPolicy,
+        IntIntHashMap boostDocsMap)
+        throws IOException {
+      super(searcher, nullPolicy, true, boostDocsMap);
+
+      this.collapseValuesProducer = collapseValuesProducer;
+      initCollapseValues();
+      int valueCount = collapseValues.getValueCount();
+
+      this.ords = new IntIntDynamicMap(valueCount, -1);
+      this.scores = new IntFloatDynamicMap(valueCount, -Float.MAX_VALUE);
+      this.nullScore = -Float.MAX_VALUE;
+    }
+
+    private void initCollapseValues() throws IOException {
+      this.collapseValues = collapseValuesProducer.getSorted(null);
+      if (collapseValues instanceof MultiDocValues.MultiSortedDocValues multi) {
+        this.multiSortedDocValues = multi;
+        this.ordinalMap = multi.mapping;
       }
+    }
+
+    @Override
+    protected void doSetNextReader(LeafReaderContext context) throws IOException {
+      super.doSetNextReader(context);
+      initSegmentValues(context);
+    }
 
+    private void initSegmentValues(LeafReaderContext context) {
       if (ordinalMap != null) {
-        this.segmentValues = this.multiSortedDocValues.values[currentContext];
-        this.segmentOrdinalMap = this.ordinalMap.getGlobalOrds(currentContext);
+        this.segmentValues = this.multiSortedDocValues.values[context.ord];
+        this.segmentOrdinalMap = ordinalMap.getGlobalOrds(context.ord);
       } else {
         this.segmentValues = collapseValues;
       }
+    }
 
-      int nextDocBase =
-          currentContext + 1 < contexts.length ? contexts[currentContext + 1].docBase : maxDoc;
-      leafDelegate = delegate.getLeafCollector(contexts[currentContext]);
-      ScoreAndDoc dummy = new ScoreAndDoc();
-      leafDelegate.setScorer(dummy);
-      DocIdSetIterator it = new BitSetIterator(collapsedSet, 0L); // cost is not useful here
-      final MergeBoost mergeBoost = boostedDocsCollector.getMergeBoost();
-      int docId = -1;
-      int index = -1;
-      while ((docId = it.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) {
-        while (docId >= nextDocBase) {
-          currentContext++;
-          currentDocBase = contexts[currentContext].docBase;
-          nextDocBase =
-              currentContext + 1 < contexts.length ? contexts[currentContext + 1].docBase : maxDoc;
-          leafDelegate = delegate.getLeafCollector(contexts[currentContext]);
-          leafDelegate.setScorer(dummy);
-          if (ordinalMap != null) {
-            this.segmentValues = this.multiSortedDocValues.values[currentContext];
-            this.segmentOrdinalMap = this.ordinalMap.getGlobalOrds(currentContext);
-          }
+    @Override
+    public void collect(int contextDoc) throws IOException {
+      int globalDoc = contextDoc + this.docBase;
+      int ord = -1;
+      if (this.ordinalMap != null) {
+        // Handle ordinalMapping case
+        if (segmentValues.advanceExact(contextDoc)) {
+          ord = (int) segmentOrdinalMap.get(segmentValues.ordValue());
+        } else {
+          ord = -1;
         }
-
-        int contextDoc = docId - currentDocBase;
-
-        int ord = -1;
-        if (this.ordinalMap != null) {
-          // Handle ordinalMapping case
-          if (segmentValues.advanceExact(contextDoc)) {
-            ord = (int) segmentOrdinalMap.get(segmentValues.ordValue());
-          }
+      } else {
+        // Handle top Level FieldCache or Single Segment Case
+        if (segmentValues.advanceExact(globalDoc)) {
+          ord = segmentValues.ordValue();
         } else {
-          // Handle top Level FieldCache or Single Segment Case
-          if (segmentValues.advanceExact(docId)) {
-            ord = segmentValues.ordValue();
-          }
+          ord = -1;
         }
+      }
 
-        if (ord > -1) {
-          dummy.score = scores.get(ord);
-        } else if (mergeBoost.boost(docId)) {
-          // Ignore so it doesn't mess up the null scoring.
-        } else if (this.nullPolicy == NullPolicy.COLLAPSE.getCode()) {
-          dummy.score = nullScore;
-        } else if (this.nullPolicy == NullPolicy.EXPAND.getCode()) {
-          dummy.score = nullScores.get(++index);
+      if (boostedDocsCollector.hasBoosts()) {
+        if (0 <= ord) {
+          if (boostedDocsCollector.collectIfBoosted(ord, globalDoc)) return;
+        } else {
+          if (boostedDocsCollector.collectInNullGroupIfBoosted(globalDoc)) return;
         }
+      }
 
-        dummy.docId = contextDoc;
-        leafDelegate.collect(contextDoc);
+      if (ord > -1) {
+        float score = scorer.score();
+        if (score > scores.get(ord)) {
+          ords.put(ord, globalDoc);
+          scores.put(ord, score);
+        }
+      } else if (nullPolicy == NullPolicy.COLLAPSE) {
+        float score = scorer.score();
+        if (score > nullScore) {
+          nullScore = score;
+          nullDoc = globalDoc;
+        }
+      } else if (nullPolicy == NullPolicy.EXPAND) {
+        collapsedSet.grow(1).add(globalDoc);
+        nullScores.add(scorer.score());
       }
+    }
+
+    @Override
+    protected void finishCollapsedSet() {
+      boostedDocsCollector.visitBoostedGroupKeys(ords::remove);
+
+      DocIdSetBuilder.BulkAdder adder = collapsedSet.grow(ords.size());
+      ords.forEachValue(adder::add);
+    }
+
+    private boolean collapsedScoresInitialized;
 
-      if (delegate instanceof DelegatingCollector) {
-        ((DelegatingCollector) delegate).complete();
+    @Override
+    protected Scorable getCollapsedScores(DocIdSetIterator disi, LeafReaderContext context)
+        throws IOException {
+      if (!collapsedScoresInitialized) {
+        collapsedScoresInitialized = true;
+        initCollapseValues();
       }
+      initSegmentValues(context);
+      return new CachedScoreScorable(disi) {
+        @Override
+        protected float computeScore(int globalDoc) throws IOException {
+          int ord = -1;
+          if (ordinalMap != null) {
+            int contextDoc = globalDoc - context.docBase;
+            if (segmentValues.advanceExact(contextDoc)) {
+              ord = (int) segmentOrdinalMap.get(segmentValues.ordValue());
+            }
+          } else {
+            if (segmentValues.advanceExact(globalDoc)) {
+              ord = segmentValues.ordValue();
+            }
+          }
+          if (ord > -1) {
+            return scores.get(ord);
+          }
+          return scoreNullGroup(globalDoc);
+        }
+      };
     }
   }
 
@@ -810,59 +1040,34 @@ public class CollapsingQParserPlugin extends QParserPlugin {
    *
    * @lucene.internal
    */
-  static class IntScoreCollector extends DelegatingCollector {
+  static class IntScoreCollector extends AbstractCollapseCollector {
+
+    // Configuration
+    private final String field;
 
-    private LeafReaderContext[] contexts;
-    private FixedBitSet collapsedSet;
+    // Source data
     private NumericDocValues collapseValues;
-    private IntLongHashMap cmap;
-    private int maxDoc;
-    private int nullPolicy;
-    private float nullScore = -Float.MAX_VALUE;
-    private int nullDoc = -1;
-    private FloatArrayList nullScores;
-    private String field;
-    private boolean collectElevatedDocsWhenCollapsing;
 
-    private final BoostedDocsCollector boostedDocsCollector;
+    // Results/accumulator
+    private final IntLongHashMap cmap;
 
     public IntScoreCollector(
-        int maxDoc,
-        int segments,
-        int nullPolicy,
-        int size,
-        String field,
+        SolrIndexSearcher searcher,
+        NullPolicy nullPolicy,
         IntIntHashMap boostDocsMap,
-        IndexSearcher searcher,
-        boolean collectElevatedDocsWhenCollapsing) {
-      this.maxDoc = maxDoc;
-      this.contexts = new LeafReaderContext[segments];
-      this.collectElevatedDocsWhenCollapsing = collectElevatedDocsWhenCollapsing;
-      List<LeafReaderContext> con = searcher.getTopReaderContext().leaves();
-      for (int i = 0; i < con.size(); i++) {
-        contexts[i] = con.get(i);
-      }
+        String field,
+        int initialSize) {
+      super(searcher, nullPolicy, true, boostDocsMap);
 
-      this.collapsedSet = new FixedBitSet(maxDoc);
-      this.nullPolicy = nullPolicy;
-      if (nullPolicy == NullPolicy.EXPAND.getCode()) {
-        nullScores = new FloatArrayList();
-      }
-      this.cmap = new IntLongHashMap(size);
       this.field = field;
 
-      this.boostedDocsCollector = BoostedDocsCollector.build(boostDocsMap);
-    }
-
-    @Override
-    public ScoreMode scoreMode() {
-      return ScoreMode.COMPLETE;
+      this.cmap = new IntLongHashMap(initialSize);
+      this.nullScore = -Float.MAX_VALUE;
     }
 
     @Override
     protected void doSetNextReader(LeafReaderContext context) throws IOException {
-      this.contexts[context.ord] = context;
-      this.docBase = context.docBase;
+      super.doSetNextReader(context);
       this.collapseValues = DocValues.getNumeric(context.reader(), this.field);
     }
 
@@ -872,11 +1077,7 @@ public class CollapsingQParserPlugin extends QParserPlugin {
       if (collapseValues.advanceExact(contextDoc)) {
         final int collapseValue = (int) collapseValues.longValue();
 
-        if (collectElevatedDocsWhenCollapsing) {
-          // Check to see if we have documents boosted by the QueryElevationComponent (skip normal
-          // strategy based collection)
-          if (boostedDocsCollector.collectIfBoosted(collapseValue, globalDoc)) return;
-        }
+        if (boostedDocsCollector.collectIfBoosted(collapseValue, globalDoc)) return;
 
         float score = scorer.score();
         final int idx;
@@ -896,101 +1097,84 @@ public class CollapsingQParserPlugin extends QParserPlugin {
 
       } else { // Null Group...
 
-        if (collectElevatedDocsWhenCollapsing) {
-          // Check to see if we have documents boosted by the QueryElevationComponent (skip normal
-          // strategy based collection)
-          if (boostedDocsCollector.collectInNullGroupIfBoosted(globalDoc)) return;
-        }
+        if (boostedDocsCollector.collectInNullGroupIfBoosted(globalDoc)) return;
 
-        if (nullPolicy == NullPolicy.COLLAPSE.getCode()) {
+        if (nullPolicy == NullPolicy.COLLAPSE) {
           float score = scorer.score();
           if (score > this.nullScore) {
             this.nullScore = score;
             this.nullDoc = globalDoc;
           }
-        } else if (nullPolicy == NullPolicy.EXPAND.getCode()) {
-          collapsedSet.set(globalDoc);
+        } else if (nullPolicy == NullPolicy.EXPAND) {
+          collapsedSet.grow(1).add(globalDoc);
           nullScores.add(scorer.score());
         }
       }
     }
 
     @Override
-    public void complete() throws IOException {
-      if (contexts.length == 0) {
-        return;
-      }
+    protected void finishCollapsedSet() {
+      boostedDocsCollector.visitBoostedGroupKeys(cmap::remove);
 
-      // Handle the boosted docs.
-      boostedDocsCollector.purgeGroupsThatHaveBoostedDocs(
-          collapsedSet,
-          (key) -> {
-            cmap.remove(key);
-          },
-          () -> {
-            nullDoc = -1;
-          });
+      DocIdSetBuilder.BulkAdder adder = collapsedSet.grow(cmap.size());
+      for (IntLongCursor cursor : cmap) {
+        // the low bits of the long is the global doc ID
+        adder.add((int) cursor.value);
+      }
+    }
 
-      // Build the sorted DocSet of group heads.
-      if (nullDoc > -1) {
-        collapsedSet.set(nullDoc);
-      }
-      Iterator<IntLongCursor> it1 = cmap.iterator();
-      while (it1.hasNext()) {
-        IntLongCursor cursor = it1.next();
-        int doc = (int) cursor.value;
-        collapsedSet.set(doc);
-      }
-
-      int currentContext = 0;
-      int currentDocBase = 0;
-
-      collapseValues = DocValues.getNumeric(contexts[currentContext].reader(), this.field);
-      int nextDocBase =
-          currentContext + 1 < contexts.length ? contexts[currentContext + 1].docBase : maxDoc;
-      leafDelegate = delegate.getLeafCollector(contexts[currentContext]);
-      ScoreAndDoc dummy = new ScoreAndDoc();
-      leafDelegate.setScorer(dummy);
-      DocIdSetIterator it = new BitSetIterator(collapsedSet, 0L); // cost is not useful here
-      final MergeBoost mergeBoost = boostedDocsCollector.getMergeBoost();
-      int globalDoc = -1;
-      int nullScoreIndex = 0;
-      while ((globalDoc = it.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) {
-
-        while (globalDoc >= nextDocBase) {
-          currentContext++;
-          currentDocBase = contexts[currentContext].docBase;
-          nextDocBase =
-              currentContext + 1 < contexts.length ? contexts[currentContext + 1].docBase : maxDoc;
-          leafDelegate = delegate.getLeafCollector(contexts[currentContext]);
-          leafDelegate.setScorer(dummy);
-          collapseValues = DocValues.getNumeric(contexts[currentContext].reader(), this.field);
-        }
-
-        final int contextDoc = globalDoc - currentDocBase;
-        if (collapseValues.advanceExact(contextDoc)) {
-          final int collapseValue = (int) collapseValues.longValue();
-          final long scoreDoc = cmap.get(collapseValue);
-          dummy.score = Float.intBitsToFloat((int) (scoreDoc >> 32));
-
-        } else { // Null Group...
-
-          if (mergeBoost.boost(globalDoc)) {
-            // It's an elevated doc so no score is needed (and should not have been populated)
-            dummy.score = 0F;
-          } else if (nullPolicy == NullPolicy.COLLAPSE.getCode()) {
-            dummy.score = nullScore;
-          } else if (nullPolicy == NullPolicy.EXPAND.getCode()) {
-            dummy.score = nullScores.get(nullScoreIndex++);
+    @Override
+    protected Scorable getCollapsedScores(DocIdSetIterator disi, LeafReaderContext context)
+        throws IOException {
+      this.collapseValues = DocValues.getNumeric(context.reader(), this.field);
+      return new CachedScoreScorable(disi) {
+        @Override
+        protected float computeScore(int globalDoc) throws IOException {
+          int contextDoc = globalDoc - context.docBase;
+          if (collapseValues.advanceExact(contextDoc)) {
+            int collapseValue = (int) collapseValues.longValue();
+            long scoreDoc = cmap.get(collapseValue);
+            return Float.intBitsToFloat((int) (scoreDoc >> 32));
           }
+          return scoreNullGroup(globalDoc);
         }
+      };
+    }
+  }
 
-        dummy.docId = contextDoc;
-        leafDelegate.collect(contextDoc);
-      }
+  /** Builder for {@link OrdFieldValueCollector}. */
+  public record OrdFieldCollectorBuilder(
+      GroupHeadSelector groupHeadSelector,
+      DocValuesProducer collapseValuesProducer,
+      NullPolicy nullPolicy,
+      boolean needsScores4Collapsing,
+      IntIntHashMap boostDocsMap,
+      SolrIndexSearcher searcher) {
+
+    /** Builds the appropriate OrdFieldValueCollector subclass based on the selection strategy. */
+    public DelegatingCollector build(
+        SortSpec sortSpec, FieldType fieldType, FunctionQuery funcQuery) throws IOException {
 
-      if (delegate instanceof DelegatingCollector) {
-        ((DelegatingCollector) delegate).complete();
+      if (null != sortSpec) {
+        return new OrdSortSpecCollector(this, sortSpec);
+      } else if (funcQuery != null) {
+        return new OrdValueSourceCollector(this, funcQuery);
+      } else {
+        NumberType numType = fieldType.getNumberType();
+        if (null == numType) {
+          throw new SolrException(
+              SolrException.ErrorCode.BAD_REQUEST,
+              "min/max must be either Int/Long/Float based field types");
+        }
+        return switch (numType) {
+          case INTEGER -> new OrdIntCollector(this);
+          case FLOAT -> new OrdFloatCollector(this);
+          case LONG -> new OrdLongCollector(this);
+          default ->
+              throw new SolrException(
+                  SolrException.ErrorCode.BAD_REQUEST,
+                  "min/max must be either Int/Long/Float field types");
+        };
       }
     }
   }
@@ -1000,163 +1184,54 @@ public class CollapsingQParserPlugin extends QParserPlugin {
    *
    * @lucene.internal
    */
-  static class OrdFieldValueCollector extends DelegatingCollector {
-    private LeafReaderContext[] contexts;
-
-    private DocValuesProducer collapseValuesProducer;
-    private SortedDocValues collapseValues;
+  protected abstract static class OrdFieldValueCollector extends AbstractCollapseCollector {
+    // Source data
+    protected final int valueCount;
+    protected final DocValuesProducer collapseValuesProducer;
+    protected SortedDocValues collapseValues;
     protected OrdinalMap ordinalMap;
+    protected MultiDocValues.MultiSortedDocValues multiSortedDocValues;
     protected SortedDocValues segmentValues;
     protected LongValues segmentOrdinalMap;
-    protected MultiDocValues.MultiSortedDocValues multiSortedDocValues;
 
-    private int maxDoc;
-    private int nullPolicy;
-
-    private OrdFieldValueStrategy collapseStrategy;
-    private boolean needsScores4Collapsing;
-    private boolean needsScores;
+    // Results/accumulator
+    protected final IntIntDynamicMap ords;
+    protected IntFloatDynamicMap scores;
 
-    private boolean collectElevatedDocsWhenCollapsing;
+    protected OrdFieldValueCollector(OrdFieldCollectorBuilder ctx) throws IOException {
+      super(ctx.searcher, ctx.nullPolicy, ctx.needsScores4Collapsing, ctx.boostDocsMap);
 
-    private final BoostedDocsCollector boostedDocsCollector;
+      this.collapseValuesProducer = ctx.collapseValuesProducer;
 
-    public OrdFieldValueCollector(
-        int maxDoc,
-        int segments,
-        DocValuesProducer collapseValuesProducer,
-        int nullPolicy,
-        GroupHeadSelector groupHeadSelector,
-        SortSpec sortSpec,
-        boolean needsScores4Collapsing,
-        boolean needsScores,
-        FieldType fieldType,
-        IntIntHashMap boostDocsMap,
-        FunctionQuery funcQuery,
-        IndexSearcher searcher,
-        boolean collectElevatedDocsWhenCollapsing)
-        throws IOException {
+      initCollapseValues();
+      this.valueCount = collapseValues.getValueCount();
 
-      assert !GroupHeadSelectorType.SCORE.equals(groupHeadSelector.type);
+      this.ords = new IntIntDynamicMap(valueCount, -1);
+    }
 
-      this.collectElevatedDocsWhenCollapsing = collectElevatedDocsWhenCollapsing;
-      this.maxDoc = maxDoc;
-      this.contexts = new LeafReaderContext[segments];
-      List<LeafReaderContext> con = searcher.getTopReaderContext().leaves();
-      for (int i = 0; i < con.size(); i++) {
-        contexts[i] = con.get(i);
-      }
-      this.collapseValuesProducer = collapseValuesProducer;
+    private void initCollapseValues() throws IOException {
       this.collapseValues = collapseValuesProducer.getSorted(null);
       if (collapseValues instanceof MultiDocValues.MultiSortedDocValues) {
         this.multiSortedDocValues = (MultiDocValues.MultiSortedDocValues) collapseValues;
         this.ordinalMap = multiSortedDocValues.mapping;
       }
-
-      this.boostedDocsCollector = BoostedDocsCollector.build(boostDocsMap);
-
-      int valueCount = collapseValues.getValueCount();
-      this.nullPolicy = nullPolicy;
-      this.needsScores4Collapsing = needsScores4Collapsing;
-      this.needsScores = needsScores;
-      if (null != sortSpec) {
-        this.collapseStrategy =
-            new OrdSortSpecStrategy(
-                maxDoc,
-                nullPolicy,
-                valueCount,
-                groupHeadSelector,
-                this.needsScores4Collapsing,
-                this.needsScores,
-                boostedDocsCollector,
-                sortSpec,
-                searcher,
-                collapseValues);
-      } else if (funcQuery != null) {
-        this.collapseStrategy =
-            new OrdValueSourceStrategy(
-                maxDoc,
-                nullPolicy,
-                valueCount,
-                groupHeadSelector,
-                this.needsScores4Collapsing,
-                this.needsScores,
-                boostedDocsCollector,
-                funcQuery,
-                searcher,
-                collapseValues);
-      } else {
-        NumberType numType = fieldType.getNumberType();
-        if (null == numType) {
-          throw new SolrException(
-              SolrException.ErrorCode.BAD_REQUEST,
-              "min/max must be either Int/Long/Float based field types");
-        }
-        switch (numType) {
-          case INTEGER:
-            {
-              this.collapseStrategy =
-                  new OrdIntStrategy(
-                      maxDoc,
-                      nullPolicy,
-                      valueCount,
-                      groupHeadSelector,
-                      this.needsScores,
-                      boostedDocsCollector,
-                      collapseValues);
-              break;
-            }
-          case FLOAT:
-            {
-              this.collapseStrategy =
-                  new OrdFloatStrategy(
-                      maxDoc,
-                      nullPolicy,
-                      valueCount,
-                      groupHeadSelector,
-                      this.needsScores,
-                      boostedDocsCollector,
-                      collapseValues);
-              break;
-            }
-          case LONG:
-            {
-              this.collapseStrategy =
-                  new OrdLongStrategy(
-                      maxDoc,
-                      nullPolicy,
-                      valueCount,
-                      groupHeadSelector,
-                      this.needsScores,
-                      boostedDocsCollector,
-                      collapseValues);
-              break;
-            }
-          default:
-            {
-              throw new SolrException(
-                  SolrException.ErrorCode.BAD_REQUEST,
-                  "min/max must be either Int/Long/Float field types");
-            }
-        }
-      }
     }
 
     @Override
-    public ScoreMode scoreMode() {
-      return needsScores ? ScoreMode.COMPLETE : super.scoreMode();
+    protected void initializeCollection(boolean needsScores) {
+      super.initializeCollection(needsScores);
+      if (needsScores) {
+        this.scores = new IntFloatDynamicMap(valueCount, 0.0f);
+      }
     }
 
     @Override
-    public void setScorer(Scorable scorer) throws IOException {
-      this.collapseStrategy.setScorer(scorer);
+    protected void doSetNextReader(LeafReaderContext context) throws IOException {
+      super.doSetNextReader(context);
+      initSegmentValues(context);
     }
 
-    @Override
-    public void doSetNextReader(LeafReaderContext context) throws IOException {
-      this.contexts[context.ord] = context;
-      this.docBase = context.docBase;
-      this.collapseStrategy.setNextReader(context);
+    private void initSegmentValues(LeafReaderContext context) {
       if (ordinalMap != null) {
         this.segmentValues = this.multiSortedDocValues.values[context.ord];
         this.segmentOrdinalMap = ordinalMap.getGlobalOrds(context.ord);
@@ -1179,9 +1254,7 @@ public class CollapsingQParserPlugin extends QParserPlugin {
         }
       }
 
-      if (collectElevatedDocsWhenCollapsing) {
-        // Check to see if we have documents boosted by the QueryElevationComponent (skip normal
-        // strategy based collection)
+      if (boostedDocsCollector.hasBoosts()) {
         if (-1 == ord) {
           if (boostedDocsCollector.collectInNullGroupIfBoosted(globalDoc)) return;
         } else {
@@ -1189,1327 +1262,659 @@ public class CollapsingQParserPlugin extends QParserPlugin {
         }
       }
 
-      collapseStrategy.collapse(ord, contextDoc, globalDoc);
+      collapse(ord, contextDoc, globalDoc);
     }
 
+    /**
+     * Strategy-specific collapse logic. Subclasses implement this to define how to select the group
+     * head document.
+     */
+    protected abstract void collapse(int ord, int contextDoc, int globalDoc) throws IOException;
+
     @Override
-    public void complete() throws IOException {
-      if (contexts.length == 0) {
-        return;
-      }
+    protected void finishCollapsedSet() {
+      boostedDocsCollector.visitBoostedGroupKeys(ords::remove);
+
+      DocIdSetBuilder.BulkAdder adder = collapsedSet.grow(ords.size());
+      ords.forEachValue(adder::add);
+    }
 
-      int currentContext = 0;
-      int currentDocBase = 0;
+    private boolean collapsedScoresInitialized;
 
-      this.collapseValues = collapseValuesProducer.getSorted(null);
-      if (collapseValues instanceof MultiDocValues.MultiSortedDocValues) {
-        this.multiSortedDocValues = (MultiDocValues.MultiSortedDocValues) collapseValues;
-        this.ordinalMap = multiSortedDocValues.mapping;
-      }
-      if (ordinalMap != null) {
-        this.segmentValues = this.multiSortedDocValues.values[currentContext];
-        this.segmentOrdinalMap = this.ordinalMap.getGlobalOrds(currentContext);
-      } else {
-        this.segmentValues = collapseValues;
+    @Override
+    protected Scorable getCollapsedScores(DocIdSetIterator disi, LeafReaderContext context)
+        throws IOException {
+      if (!collapsedScoresInitialized) {
+        collapsedScoresInitialized = true;
+        initCollapseValues();
       }
 
-      int nextDocBase =
-          currentContext + 1 < contexts.length ? contexts[currentContext + 1].docBase : maxDoc;
-      leafDelegate = delegate.getLeafCollector(contexts[currentContext]);
-      ScoreAndDoc dummy = new ScoreAndDoc();
-      leafDelegate.setScorer(dummy);
-      DocIdSetIterator it =
-          new BitSetIterator(collapseStrategy.getCollapsedSet(), 0); // cost is not useful here
-      int globalDoc = -1;
-      int nullScoreIndex = 0;
-      IntFloatDynamicMap scores = collapseStrategy.getScores();
-      FloatArrayList nullScores = collapseStrategy.getNullScores();
-      float nullScore = collapseStrategy.getNullScore();
-      final MergeBoost mergeBoost = boostedDocsCollector.getMergeBoost();
-
-      while ((globalDoc = it.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) {
-
-        while (globalDoc >= nextDocBase) {
-          currentContext++;
-          currentDocBase = contexts[currentContext].docBase;
-          nextDocBase =
-              currentContext + 1 < contexts.length ? contexts[currentContext + 1].docBase : maxDoc;
-          leafDelegate = delegate.getLeafCollector(contexts[currentContext]);
-          leafDelegate.setScorer(dummy);
-          if (ordinalMap != null) {
-            this.segmentValues = this.multiSortedDocValues.values[currentContext];
-            this.segmentOrdinalMap = this.ordinalMap.getGlobalOrds(currentContext);
-          }
-        }
-
-        int contextDoc = globalDoc - currentDocBase;
+      initSegmentValues(context);
 
-        if (this.needsScores) {
+      return new CachedScoreScorable(disi) {
+        @Override
+        protected float computeScore(int globalDoc) throws IOException {
           int ord = -1;
-          if (this.ordinalMap != null) {
-            // Handle ordinalMapping case
+          if (ordinalMap != null) {
+            int contextDoc = globalDoc - context.docBase;
             if (segmentValues.advanceExact(contextDoc)) {
               ord = (int) segmentOrdinalMap.get(segmentValues.ordValue());
             }
           } else {
-            // Handle top Level FieldCache or Single Segment Case
             if (segmentValues.advanceExact(globalDoc)) {
               ord = segmentValues.ordValue();
             }
           }
-
           if (ord > -1) {
-            dummy.score = scores.get(ord);
-          } else if (mergeBoost.boost(globalDoc)) {
-            // It's an elevated doc so no score is needed (and should not have been populated)
-            dummy.score = 0F;
-          } else if (nullPolicy == NullPolicy.COLLAPSE.getCode()) {
-            dummy.score = nullScore;
-          } else if (nullPolicy == NullPolicy.EXPAND.getCode()) {
-            dummy.score = nullScores.get(nullScoreIndex++);
+            return scores.get(ord);
           }
+          return scoreNullGroup(globalDoc);
         }
-
-        dummy.docId = contextDoc;
-        leafDelegate.collect(contextDoc);
-      }
-
-      if (delegate instanceof DelegatingCollector) {
-        ((DelegatingCollector) delegate).complete();
-      }
+      };
     }
   }
 
-  /**
-   * Collapses on an integer field.
-   *
-   * @lucene.internal
-   */
-  static class IntFieldValueCollector extends DelegatingCollector {
-    private LeafReaderContext[] contexts;
-    private NumericDocValues collapseValues;
-    private int maxDoc;
-    private int nullPolicy;
-
-    private IntFieldValueStrategy collapseStrategy;
-    private boolean needsScores4Collapsing;
-    private boolean needsScores;
-    private String collapseField;
-
-    private final BoostedDocsCollector boostedDocsCollector;
-    private boolean collectElevatedDocsWhenCollapsing;
-
-    public IntFieldValueCollector(
-        int maxDoc,
-        int size,
-        int segments,
-        int nullPolicy,
-        String collapseField,
-        GroupHeadSelector groupHeadSelector,
-        SortSpec sortSpec,
-        boolean needsScores4Collapsing,
-        boolean needsScores,
-        FieldType fieldType,
-        IntIntHashMap boostDocsMap,
-        FunctionQuery funcQuery,
-        IndexSearcher searcher,
-        boolean collectElevatedDocsWhenCollapsing)
-        throws IOException {
-      this.collectElevatedDocsWhenCollapsing = collectElevatedDocsWhenCollapsing;
-
-      assert !GroupHeadSelectorType.SCORE.equals(groupHeadSelector.type);
+  /** Collector for collapsing on ordinal using min/max of an int field to select group head. */
+  protected static class OrdIntCollector extends OrdFieldValueCollector {
+    // Configuration
+    private final String field;
+    private final IntCompare comp;
 
-      this.maxDoc = maxDoc;
-      this.contexts = new LeafReaderContext[segments];
-      List<LeafReaderContext> con = searcher.getTopReaderContext().leaves();
-      for (int i = 0; i < con.size(); i++) {
-        contexts[i] = con.get(i);
-      }
-      this.collapseField = collapseField;
-      this.nullPolicy = nullPolicy;
-      this.needsScores4Collapsing = needsScores4Collapsing;
-      this.needsScores = needsScores;
+    // Source data
+    private NumericDocValues minMaxValues;
 
-      this.boostedDocsCollector = BoostedDocsCollector.build(boostDocsMap);
+    // Results/accumulator
+    private final IntIntDynamicMap ordVals;
+    private int nullVal;
 
-      if (null != sortSpec) {
-        this.collapseStrategy =
-            new IntSortSpecStrategy(
-                maxDoc,
-                size,
-                collapseField,
-                nullPolicy,
-                groupHeadSelector,
-                this.needsScores4Collapsing,
-                this.needsScores,
-                boostedDocsCollector,
-                sortSpec,
-                searcher);
-      } else if (funcQuery != null) {
-        this.collapseStrategy =
-            new IntValueSourceStrategy(
-                maxDoc,
-                size,
-                collapseField,
-                nullPolicy,
-                groupHeadSelector,
-                this.needsScores4Collapsing,
-                this.needsScores,
-                boostedDocsCollector,
-                funcQuery,
-                searcher);
+    public OrdIntCollector(OrdFieldCollectorBuilder ctx) throws IOException {
+      super(ctx);
+      this.field = ctx.groupHeadSelector.selectorText;
+      assert GroupHeadSelectorType.MIN_MAX.contains(ctx.groupHeadSelector.type);
+      if (GroupHeadSelectorType.MAX.equals(ctx.groupHeadSelector.type)) {
+        comp = new MaxIntComp();
+        this.ordVals = new IntIntDynamicMap(valueCount, Integer.MIN_VALUE);
       } else {
-        NumberType numType = fieldType.getNumberType();
-        assert null != numType; // shouldn't make it here for non-numeric types
-        switch (numType) {
-          case INTEGER:
-            {
-              this.collapseStrategy =
-                  new IntIntStrategy(
-                      maxDoc,
-                      size,
-                      collapseField,
-                      nullPolicy,
-                      groupHeadSelector,
-                      this.needsScores,
-                      boostedDocsCollector);
-              break;
-            }
-          case FLOAT:
-            {
-              this.collapseStrategy =
-                  new IntFloatStrategy(
-                      maxDoc,
-                      size,
-                      collapseField,
-                      nullPolicy,
-                      groupHeadSelector,
-                      this.needsScores,
-                      boostedDocsCollector);
-              break;
-            }
-          default:
-            {
-              throw new SolrException(
-                  SolrException.ErrorCode.BAD_REQUEST,
-                  "min/max must be Int or Float field types when collapsing on numeric fields");
-            }
-        }
+        comp = new MinIntComp();
+        this.ordVals = new IntIntDynamicMap(valueCount, Integer.MAX_VALUE);
+        this.nullVal = Integer.MAX_VALUE;
       }
     }
 
     @Override
-    public ScoreMode scoreMode() {
-      return needsScores ? ScoreMode.COMPLETE : super.scoreMode();
+    protected void doSetNextReader(LeafReaderContext context) throws IOException {
+      super.doSetNextReader(context);
+      this.minMaxValues = DocValues.getNumeric(context.reader(), this.field);
     }
 
     @Override
-    public void setScorer(Scorable scorer) throws IOException {
-      this.collapseStrategy.setScorer(scorer);
-    }
+    protected void collapse(int ord, int contextDoc, int globalDoc) throws IOException {
+      int currentVal;
+      if (minMaxValues.advanceExact(contextDoc)) {
+        currentVal = (int) minMaxValues.longValue();
+      } else {
+        currentVal = 0;
+      }
 
-    @Override
-    public void doSetNextReader(LeafReaderContext context) throws IOException {
-      this.contexts[context.ord] = context;
-      this.docBase = context.docBase;
-      this.collapseStrategy.setNextReader(context);
-      this.collapseValues = DocValues.getNumeric(context.reader(), this.collapseField);
+      if (ord > -1) {
+        if (comp.test(currentVal, ordVals.get(ord))) {
+          ords.put(ord, globalDoc);
+          ordVals.put(ord, currentVal);
+          if (needsScores) {
+            scores.put(ord, scorer.score());
+          }
+        }
+      } else if (this.nullPolicy == NullPolicy.COLLAPSE) {
+        if (comp.test(currentVal, nullVal)) {
+          nullVal = currentVal;
+          nullDoc = globalDoc;
+          if (needsScores) {
+            nullScore = scorer.score();
+          }
+        }
+      } else if (this.nullPolicy == NullPolicy.EXPAND) {
+        this.collapsedSet.grow(1).add(globalDoc);
+        if (needsScores) {
+          nullScores.add(scorer.score());
+        }
+      }
     }
+  }
 
-    @Override
-    public void collect(int contextDoc) throws IOException {
-      final int globalDoc = contextDoc + this.docBase;
-      if (collapseValues.advanceExact(contextDoc)) {
-        final int collapseKey = (int) collapseValues.longValue();
-        // Check to see if we have documents boosted by the QueryElevationComponent (skip normal
-        // strategy based collection)
-        if (boostedDocsCollector.collectIfBoosted(collapseKey, globalDoc)) return;
-        collapseStrategy.collapse(collapseKey, contextDoc, globalDoc);
+  /** Collector for collapsing on ordinal using min/max of a float field to select group head. */
+  protected static class OrdFloatCollector extends OrdFieldValueCollector {
+    // Configuration
+    private final String field;
+    private final FloatCompare comp;
 
-      } else { // Null Group...
+    // Source data
+    private NumericDocValues minMaxValues;
 
-        if (collectElevatedDocsWhenCollapsing) {
-          // Check to see if we have documents boosted by the QueryElevationComponent (skip normal
-          // strategy based collection)
-          if (boostedDocsCollector.collectInNullGroupIfBoosted(globalDoc)) return;
-        }
-        if (NullPolicy.IGNORE.getCode() != nullPolicy) {
-          collapseStrategy.collapseNullGroup(contextDoc, globalDoc);
-        }
+    // Results/accumulator
+    private final IntFloatDynamicMap ordVals;
+    private float nullVal;
+
+    public OrdFloatCollector(OrdFieldCollectorBuilder ctx) throws IOException {
+      super(ctx);
+      this.field = ctx.groupHeadSelector.selectorText;
+      assert GroupHeadSelectorType.MIN_MAX.contains(ctx.groupHeadSelector.type);
+      if (GroupHeadSelectorType.MAX.equals(ctx.groupHeadSelector.type)) {
+        comp = new MaxFloatComp();
+        this.ordVals = new IntFloatDynamicMap(valueCount, -Float.MAX_VALUE);
+        this.nullVal = -Float.MAX_VALUE;
+      } else {
+        comp = new MinFloatComp();
+        this.ordVals = new IntFloatDynamicMap(valueCount, Float.MAX_VALUE);
+        this.nullVal = Float.MAX_VALUE;
       }
     }
 
     @Override
-    public void complete() throws IOException {
-      if (contexts.length == 0) {
-        return;
-      }
-
-      int currentContext = 0;
-      int currentDocBase = 0;
-      this.collapseValues =
-          DocValues.getNumeric(contexts[currentContext].reader(), this.collapseField);
-      int nextDocBase =
-          currentContext + 1 < contexts.length ? contexts[currentContext + 1].docBase : maxDoc;
-      leafDelegate = delegate.getLeafCollector(contexts[currentContext]);
-      ScoreAndDoc dummy = new ScoreAndDoc();
-      leafDelegate.setScorer(dummy);
-      DocIdSetIterator it =
-          new BitSetIterator(collapseStrategy.getCollapsedSet(), 0); // cost is not useful here
-      int globalDoc = -1;
-      int nullScoreIndex = 0;
-      IntIntHashMap cmap = collapseStrategy.getCollapseMap();
-      IntFloatDynamicMap scores = collapseStrategy.getScores();
-      FloatArrayList nullScores = collapseStrategy.getNullScores();
-      float nullScore = collapseStrategy.getNullScore();
-      final MergeBoost mergeBoost = boostedDocsCollector.getMergeBoost();
-
-      while ((globalDoc = it.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) {
-
-        while (globalDoc >= nextDocBase) {
-          currentContext++;
-          currentDocBase = contexts[currentContext].docBase;
-          nextDocBase =
-              currentContext + 1 < contexts.length ? contexts[currentContext + 1].docBase : maxDoc;
-          leafDelegate = delegate.getLeafCollector(contexts[currentContext]);
-          leafDelegate.setScorer(dummy);
-          this.collapseValues =
-              DocValues.getNumeric(contexts[currentContext].reader(), this.collapseField);
-        }
-
-        final int contextDoc = globalDoc - currentDocBase;
-
-        if (this.needsScores) {
-          if (collapseValues.advanceExact(contextDoc)) {
-            final int collapseValue = (int) collapseValues.longValue();
+    protected void doSetNextReader(LeafReaderContext context) throws IOException {
+      super.doSetNextReader(context);
+      this.minMaxValues = DocValues.getNumeric(context.reader(), this.field);
+    }
 
-            final int pointer = cmap.get(collapseValue);
-            dummy.score = scores.get(pointer);
+    @Override
+    protected void collapse(int ord, int contextDoc, int globalDoc) throws IOException {
+      int currentMinMax;
+      if (minMaxValues.advanceExact(contextDoc)) {
+        currentMinMax = (int) minMaxValues.longValue();
+      } else {
+        currentMinMax = 0;
+      }
 
-          } else { // Null Group...
+      float currentVal = Float.intBitsToFloat(currentMinMax);
 
-            if (mergeBoost.boost(globalDoc)) {
-              // It's an elevated doc so no score is needed (and should not have been populated)
-              dummy.score = 0F;
-            } else if (nullPolicy == NullPolicy.COLLAPSE.getCode()) {
-              dummy.score = nullScore;
-            } else if (nullPolicy == NullPolicy.EXPAND.getCode()) {
-              dummy.score = nullScores.get(nullScoreIndex++);
-            }
+      if (ord > -1) {
+        if (comp.test(currentVal, ordVals.get(ord))) {
+          ords.put(ord, globalDoc);
+          ordVals.put(ord, currentVal);
+          if (needsScores) {
+            scores.put(ord, scorer.score());
           }
         }
-
-        dummy.docId = contextDoc;
-        leafDelegate.collect(contextDoc);
-      }
-
-      if (delegate instanceof DelegatingCollector) {
-        ((DelegatingCollector) delegate).complete();
+      } else if (this.nullPolicy == NullPolicy.COLLAPSE) {
+        if (comp.test(currentVal, nullVal)) {
+          nullVal = currentVal;
+          nullDoc = globalDoc;
+          if (needsScores) {
+            nullScore = scorer.score();
+          }
+        }
+      } else if (this.nullPolicy == NullPolicy.EXPAND) {
+        this.collapsedSet.grow(1).add(globalDoc);
+        if (needsScores) {
+          nullScores.add(scorer.score());
+        }
       }
     }
   }
 
-  /**
-   * Base class for collectors that will do collapsing using "block indexed" documents
-   *
-   * @lucene.internal
-   */
-  private abstract static class AbstractBlockCollector extends DelegatingCollector {
-
-    protected final BlockGroupState currentGroupState = new BlockGroupState();
-    protected final String collapseField;
-    protected final boolean needsScores;
-    protected final boolean expandNulls;
-    private final MergeBoost boostDocs;
+  /** Collector for collapsing on ordinal using min/max of a long field to select group head. */
+  protected static class OrdLongCollector extends OrdFieldValueCollector {
+    // Configuration
+    private final String field;
+    private final LongCompare comp;
 
-    protected AbstractBlockCollector(
-        final String collapseField,
-        final int nullPolicy,
-        final IntIntHashMap boostDocsMap,
-        final boolean needsScores) {
+    // Source data
+    private NumericDocValues minMaxVals;
 
-      this.collapseField = collapseField;
-      this.needsScores = needsScores;
+    // Results/accumulator
+    private final IntLongDynamicMap ordVals;
+    private long nullVal;
 
-      assert nullPolicy != NullPolicy.COLLAPSE.getCode();
-      assert nullPolicy == NullPolicy.IGNORE.getCode() || nullPolicy == NullPolicy.EXPAND.getCode();
-      this.expandNulls = (NullPolicy.EXPAND.getCode() == nullPolicy);
-      this.boostDocs = BoostedDocsCollector.build(boostDocsMap).getMergeBoost();
+    public OrdLongCollector(OrdFieldCollectorBuilder ctx) throws IOException {
+      super(ctx);
 
-      currentGroupState.resetForNewGroup();
+      this.field = ctx.groupHeadSelector.selectorText;
+      assert GroupHeadSelectorType.MIN_MAX.contains(ctx.groupHeadSelector.type);
+      if (GroupHeadSelectorType.MAX.equals(ctx.groupHeadSelector.type)) {
+        comp = new MaxLongComp();
+        this.ordVals = new IntLongDynamicMap(valueCount, Long.MIN_VALUE);
+      } else {
+        this.nullVal = Long.MAX_VALUE;
+        comp = new MinLongComp();
+        this.ordVals = new IntLongDynamicMap(valueCount, Long.MAX_VALUE);
+      }
     }
 
     @Override
-    public ScoreMode scoreMode() {
-      return needsScores ? ScoreMode.COMPLETE : super.scoreMode();
+    protected void doSetNextReader(LeafReaderContext context) throws IOException {
+      super.doSetNextReader(context);
+      this.minMaxVals = DocValues.getNumeric(context.reader(), this.field);
     }
 
-    /** If we have a candidate match, delegate the collection of that match. */
-    protected void maybeDelegateCollect() throws IOException {
-      if (currentGroupState.isCurrentDocCollectable()) {
-        delegateCollect();
+    @Override
+    protected void collapse(int ord, int contextDoc, int globalDoc) throws IOException {
+      long currentVal;
+      if (minMaxVals.advanceExact(contextDoc)) {
+        currentVal = minMaxVals.longValue();
+      } else {
+        currentVal = 0;
+      }
+
+      if (ord > -1) {
+        if (comp.test(currentVal, ordVals.get(ord))) {
+          ords.put(ord, globalDoc);
+          ordVals.put(ord, currentVal);
+          if (needsScores) {
+            scores.put(ord, scorer.score());
+          }
+        }
+      } else if (this.nullPolicy == NullPolicy.COLLAPSE) {
+        if (comp.test(currentVal, nullVal)) {
+          nullVal = currentVal;
+          nullDoc = globalDoc;
+          if (needsScores) {
+            nullScore = scorer.score();
+          }
+        }
+      } else if (this.nullPolicy == NullPolicy.EXPAND) {
+        this.collapsedSet.grow(1).add(globalDoc);
+        if (needsScores) {
+          nullScores.add(scorer.score());
+        }
       }
     }
+  }
 
-    /** Immediately delegate the collection of the current doc */
-    protected void delegateCollect() throws IOException {
-      // ensure we have the 'correct' scorer
-      // (our supper class may have set the "real" scorer on our leafDelegate
-      // and it may have an incorrect docID)
-      leafDelegate.setScorer(currentGroupState);
-      leafDelegate.collect(currentGroupState.docId);
+  /**
+   * Collector for collapsing on ordinal using min/max of a value source function to select group
+   * head.
+   */
+  protected static class OrdValueSourceCollector extends OrdFieldValueCollector {
+    // Configuration
+    private final FloatCompare comp;
+    private final ValueSource valueSource;
+    private final Map<Object, Object> rcontext;
+    private final CollapseScore collapseScore = new CollapseScore();
+
+    // Source data
+    private FunctionValues functionValues;
+
+    // Results/accumulator
+    private final IntFloatDynamicMap ordVals;
+    private float nullVal;
+
+    public OrdValueSourceCollector(OrdFieldCollectorBuilder ctx, FunctionQuery funcQuery)
+        throws IOException {
+      super(ctx);
+      assert GroupHeadSelectorType.MIN_MAX.contains(ctx.groupHeadSelector.type);
+      if (GroupHeadSelectorType.MAX.equals(ctx.groupHeadSelector.type)) {
+        comp = new MaxFloatComp();
+        this.ordVals = new IntFloatDynamicMap(valueCount, -Float.MAX_VALUE);
+      } else {
+        this.nullVal = Float.MAX_VALUE;
+        comp = new MinFloatComp();
+        this.ordVals = new IntFloatDynamicMap(valueCount, Float.MAX_VALUE);
+      }
+      this.valueSource = funcQuery.getValueSource();
+      this.rcontext = ValueSource.newContext(ctx.searcher);
+      collapseScore.setupIfNeeded(ctx.groupHeadSelector, rcontext);
     }
 
-    /**
-     * NOTE: collects the best doc for the last group in the previous segment subclasses must call
-     * super <em>BEFORE</em> they make any changes to their own state that might influence
-     * collection
-     */
     @Override
     protected void doSetNextReader(LeafReaderContext context) throws IOException {
-      maybeDelegateCollect();
-      // Now setup for the next segment.
-      currentGroupState.resetForNewGroup();
-      this.docBase = context.docBase;
       super.doSetNextReader(context);
-    }
-
-    /**
-     * Acts as an id iterator over the boosted docs
-     *
-     * @param contextDoc the context specific docId to check for, iterator is advanced to this id
-     * @return true if the contextDoc is boosted, false otherwise.
-     */
-    protected boolean isBoostedAdvanceExact(final int contextDoc) {
-      return boostDocs.boost(contextDoc + docBase);
+      functionValues = this.valueSource.getValues(rcontext, context);
     }
 
     @Override
-    public void complete() throws IOException {
-      // Deal with last group (if any)...
-      maybeDelegateCollect();
+    protected void collapse(int ord, int contextDoc, int globalDoc) throws IOException {
+      float score = 0;
 
-      super.complete();
-    }
+      if (needsScores4Collapsing) {
+        score = scorer.score();
+        this.collapseScore.score = score;
+      }
 
-    /**
-     * Encapsulates basic state information about the current group, and the "best matching"
-     * document in that group (so far)
-     */
-    protected static final class BlockGroupState extends ScoreAndDoc {
-      /**
-       * Specific values have no intrinsic meaning, but can <em>only</em> be considered if the
-       * current docID is non-negative
-       */
-      private int currentGroup = 0;
-
-      private boolean groupHasBoostedDocs;
-
-      public void setCurrentGroup(final int groupId) {
-        this.currentGroup = groupId;
-      }
-
-      public int getCurrentGroup() {
-        assert -1 < this.docId;
-        return this.currentGroup;
-      }
-
-      public void setBestDocForCurrentGroup(final int contextDoc, final boolean isBoosted) {
-        this.docId = contextDoc;
-        this.groupHasBoostedDocs |= isBoosted;
-      }
-
-      public void resetForNewGroup() {
-        this.docId = -1;
-        this.score = Float.MIN_VALUE;
-        this.groupHasBoostedDocs = false;
-      }
-
-      public boolean hasBoostedDocs() {
-        assert -1 < this.docId;
-        return groupHasBoostedDocs;
-      }
-
-      /**
-       * Returns true if we have a valid ("best match") docId for the current group and there are no
-       * boosted docs for this group (If the current doc was boosted, it should have already been
-       * collected)
-       */
-      public boolean isCurrentDocCollectable() {
-        return (-1 < this.docId && !groupHasBoostedDocs);
-      }
-    }
-  }
-
-  /**
-   * Collapses groups on a block using a field that has values unique to that block (example: <code>
-   * _root_</code>) choosing the group head based on score
-   *
-   * @lucene.internal
-   */
-  abstract static class AbstractBlockScoreCollector extends AbstractBlockCollector {
-
-    public AbstractBlockScoreCollector(
-        final String collapseField, final int nullPolicy, final IntIntHashMap boostDocsMap) {
-      super(collapseField, nullPolicy, boostDocsMap, true);
-    }
-
-    private void setCurrentGroupBestMatch(
-        final int contextDocId, final float score, final boolean isBoosted) {
-      currentGroupState.setBestDocForCurrentGroup(contextDocId, isBoosted);
-      currentGroupState.score = score;
-    }
-
-    /**
-     * This method should be called by subclasses for each doc + group encountered
-     *
-     * @param contextDoc a valid doc id relative to the current reader context
-     * @param docGroup some uique identifier for the group - the base class makes no assumptions
-     *     about it's meaning
-     * @see #collectDocWithNullGroup
-     */
-    protected void collectDocWithGroup(int contextDoc, int docGroup) throws IOException {
-      assert 0 <= contextDoc;
-
-      final boolean isBoosted = isBoostedAdvanceExact(contextDoc);
-
-      if (-1 < currentGroupState.docId && docGroup == currentGroupState.getCurrentGroup()) {
-        // we have an existing group, and contextDoc is in that group.
-
-        if (isBoosted) {
-          // this doc is the best and should be immediately collected regardless of score
-          setCurrentGroupBestMatch(contextDoc, scorer.score(), isBoosted);
-          delegateCollect();
-
-        } else if (currentGroupState.hasBoostedDocs()) {
-          // No-Op: nothing about this doc matters since we've already collected boosted docs in
-          // this group
-
-          // No-Op
-        } else {
-          // check if this doc the new 'best' doc in this group...
-          final float score = scorer.score();
-          if (score > currentGroupState.score) {
-            setCurrentGroupBestMatch(contextDoc, scorer.score(), isBoosted);
-          }
-        }
-
-      } else {
-        // We have a document that starts a new group (or may be the first doc+group we've collected
-        // this segment)
-
-        // first collect the prior group if needed...
-        maybeDelegateCollect();
-
-        // then setup the new group and current best match
-        currentGroupState.resetForNewGroup();
-        currentGroupState.setCurrentGroup(docGroup);
-        setCurrentGroupBestMatch(contextDoc, scorer.score(), isBoosted);
-
-        if (isBoosted) { // collect immediately
-          delegateCollect();
-        }
-      }
-    }
-
-    /**
-     * This method should be called by subclasses for each doc encountered that is not in a group
-     * (ie: null group)
-     *
-     * @param contextDoc a valid doc id relative to the current reader context
-     * @see #collectDocWithGroup
-     */
-    protected void collectDocWithNullGroup(int contextDoc) throws IOException {
-      assert 0 <= contextDoc;
-
-      // NOTE: with 'null group' docs, it doesn't matter if they are boosted since we don't suppor
-      // collapsing nulls
-
-      // this doc is definitely not part of any prior group, so collect if needed...
-      maybeDelegateCollect();
-
-      if (expandNulls) {
-        // set & immediately collect our current doc...
-        setCurrentGroupBestMatch(contextDoc, scorer.score(), false);
-        delegateCollect();
-
-      } else {
-        // we're ignoring nulls, so: No-Op.
-      }
-
-      // either way re-set for the next doc / group
-      currentGroupState.resetForNewGroup();
-    }
-  }
-
-  /**
-   * A block based score collector that uses a field's "ord" as the group ids
-   *
-   * @lucene.internal
-   */
-  static class BlockOrdScoreCollector extends AbstractBlockScoreCollector {
-    private SortedDocValues segmentValues;
-
-    public BlockOrdScoreCollector(
-        final String collapseField, final int nullPolicy, final IntIntHashMap boostDocsMap)
-        throws IOException {
-      super(collapseField, nullPolicy, boostDocsMap);
-    }
-
-    @Override
-    protected void doSetNextReader(LeafReaderContext context) throws IOException {
-      super.doSetNextReader(context);
-      this.segmentValues = DocValues.getSorted(context.reader(), collapseField);
-    }
-
-    @Override
-    public void collect(int contextDoc) throws IOException {
-      if (segmentValues.advanceExact(contextDoc)) {
-        int ord = segmentValues.ordValue();
-        collectDocWithGroup(contextDoc, ord);
-      } else {
-        collectDocWithNullGroup(contextDoc);
-      }
-    }
-  }
-
-  /**
-   * A block based score collector that uses a field's numeric value as the group ids
-   *
-   * @lucene.internal
-   */
-  static class BlockIntScoreCollector extends AbstractBlockScoreCollector {
-    private NumericDocValues segmentValues;
-
-    public BlockIntScoreCollector(
-        final String collapseField, final int nullPolicy, final IntIntHashMap boostDocsMap)
-        throws IOException {
-      super(collapseField, nullPolicy, boostDocsMap);
-    }
-
-    @Override
-    protected void doSetNextReader(LeafReaderContext context) throws IOException {
-      super.doSetNextReader(context);
-      this.segmentValues = DocValues.getNumeric(context.reader(), collapseField);
-    }
-
-    @Override
-    public void collect(int contextDoc) throws IOException {
-      if (segmentValues.advanceExact(contextDoc)) {
-        int group = (int) segmentValues.longValue();
-        collectDocWithGroup(contextDoc, group);
-      } else {
-        collectDocWithNullGroup(contextDoc);
-      }
-    }
-  }
-
-  /**
-   * Collapses groups on a block using a field that has values unique to that block (example: <code>
-   * _root_</code>) choosing the group head based on a {@link SortSpec} (which can be synthetically
-   * created for min/max group head selectors using {@link #getSort})
-   *
-   * <p>Note that since this collector does a single pass, and unlike other collectors doesn't need
-   * to maintain a large data structure of scores (for all matching docs) when they might be needed
-   * for the response, it has no need to distinguish between the concepts of <code>
-   * needsScores4Collapsing</code> vs </code>needsScores</code>
-   *
-   * @lucene.internal
-   */
-  abstract static class AbstractBlockSortSpecCollector extends AbstractBlockCollector {
-
-    /**
-     * Helper method for extracting a {@link Sort} out of a {@link SortSpec} <em>or</em> creating
-     * one synthetically for "min/max" {@link GroupHeadSelector} against a {@link FunctionQuery}
-     * <em>or</em> simple field name.
-     *
-     * @return appropriate (already re-written) Sort to use with a AbstractBlockSortSpecCollector
-     */
-    public static Sort getSort(
-        final GroupHeadSelector groupHeadSelector,
-        final SortSpec sortSpec,
-        final FunctionQuery funcQuery,
-        final SolrIndexSearcher searcher)
-        throws IOException {
-      if (null != sortSpec) {
-        assert GroupHeadSelectorType.SORT.equals(groupHeadSelector.type);
-
-        // a "feature" of SortSpec is that getSort() is null if we're just using 'score desc'
-        if (null == sortSpec.getSort()) {
-          return Sort.RELEVANCE.rewrite(searcher);
-        }
-        return sortSpec.getSort().rewrite(searcher);
-      } // else: min/max on field or value source...
-
-      assert GroupHeadSelectorType.MIN_MAX.contains(groupHeadSelector.type);
-      assert !CollapseScore.wantsCScore(groupHeadSelector.selectorText);
-
-      final boolean reverse = GroupHeadSelectorType.MAX.equals(groupHeadSelector.type);
-      final SortField sf =
-          (null != funcQuery)
-              ? funcQuery.getValueSource().getSortField(reverse)
-              : searcher.getSchema().getField(groupHeadSelector.selectorText).getSortField(reverse);
-
-      return (new Sort(sf)).rewrite(searcher);
-    }
-
-    private final BlockBasedSortFieldsCompare sortsCompare;
-
-    public AbstractBlockSortSpecCollector(
-        final String collapseField,
-        final int nullPolicy,
-        final IntIntHashMap boostDocsMap,
-        final Sort sort,
-        final boolean needsScores) {
-      super(collapseField, nullPolicy, boostDocsMap, needsScores);
-      this.sortsCompare = new BlockBasedSortFieldsCompare(sort.getSort());
-    }
-
-    @Override
-    public void setScorer(Scorable scorer) throws IOException {
-      sortsCompare.setScorer(scorer);
-      super.setScorer(scorer);
-    }
-
-    private void setCurrentGroupBestMatch(final int contextDocId, final boolean isBoosted)
-        throws IOException {
-      currentGroupState.setBestDocForCurrentGroup(contextDocId, isBoosted);
-      if (needsScores) {
-        currentGroupState.score = scorer.score();
-      }
-    }
-
-    @Override
-    protected void doSetNextReader(LeafReaderContext context) throws IOException {
-      super.doSetNextReader(context);
-      this.sortsCompare.setNextReader(context);
-    }
-
-    /**
-     * This method should be called by subclasses for each doc + group encountered
-     *
-     * @param contextDoc a valid doc id relative to the current reader context
-     * @param docGroup some uique identifier for the group - the base class makes no assumptions
-     *     about it's meaning
-     * @see #collectDocWithNullGroup
-     */
-    protected void collectDocWithGroup(int contextDoc, int docGroup) throws IOException {
-      assert 0 <= contextDoc;
-
-      final boolean isBoosted = isBoostedAdvanceExact(contextDoc);
-
-      if (-1 < currentGroupState.docId && docGroup == currentGroupState.getCurrentGroup()) {
-        // we have an existing group, and contextDoc is in that group.
-
-        if (isBoosted) {
-          // this doc is the best and should be immediately collected regardless of sort values
-          setCurrentGroupBestMatch(contextDoc, isBoosted);
-          delegateCollect();
-
-        } else if (currentGroupState.hasBoostedDocs()) {
-          // No-Op: nothing about this doc matters since we've already collected boosted docs in
-          // this group
+      float currentVal = functionValues.floatVal(contextDoc);
 
-          // No-Op
-        } else {
-          // check if it's the new 'best' doc in this group...
-          if (sortsCompare.testAndSetGroupValues(contextDoc)) {
-            setCurrentGroupBestMatch(contextDoc, isBoosted);
+      if (ord > -1) {
+        if (comp.test(currentVal, ordVals.get(ord))) {
+          ords.put(ord, globalDoc);
+          ordVals.put(ord, currentVal);
+          if (needsScores) {
+            if (!needsScores4Collapsing) {
+              score = scorer.score();
+            }
+            scores.put(ord, score);
           }
         }
-
-      } else {
-        // We have a document that starts a new group (or may be the first doc+group we've collected
-        // this segmen)
-
-        // first collect the prior group if needed...
-        maybeDelegateCollect();
-
-        // then setup the new group and current best match
-        currentGroupState.resetForNewGroup();
-        currentGroupState.setCurrentGroup(docGroup);
-        sortsCompare.setGroupValues(contextDoc);
-        setCurrentGroupBestMatch(contextDoc, isBoosted);
-
-        if (isBoosted) { // collect immediately
-          delegateCollect();
-        }
-      }
-    }
-
-    /**
-     * This method should be called by subclasses for each doc encountered that is not in a group
-     * (ie: null group)
-     *
-     * @param contextDoc a valid doc id relative to the current reader context
-     * @see #collectDocWithGroup
-     */
-    protected void collectDocWithNullGroup(int contextDoc) throws IOException {
-      assert 0 <= contextDoc;
-
-      // NOTE: with 'null group' docs, it doesn't matter if they are boosted since we don't suppor
-      // collapsing nulls
-
-      // this doc is definitely not part of any prior group, so collect if needed...
-      maybeDelegateCollect();
-
-      if (expandNulls) {
-        // set & immediately collect our current doc...
-        setCurrentGroupBestMatch(contextDoc, false);
-        // NOTE: sort values don't matter
-        delegateCollect();
-
-      } else {
-        // we're ignoring nulls, so: No-Op.
-      }
-
-      // either way re-set for the next doc / group
-      currentGroupState.resetForNewGroup();
-    }
-  }
-
-  /**
-   * A block based score collector that uses a field's "ord" as the group ids
-   *
-   * @lucene.internal
-   */
-  static class BlockOrdSortSpecCollector extends AbstractBlockSortSpecCollector {
-    private SortedDocValues segmentValues;
-
-    public BlockOrdSortSpecCollector(
-        final String collapseField,
-        final int nullPolicy,
-        final IntIntHashMap boostDocsMap,
-        final Sort sort,
-        final boolean needsScores)
-        throws IOException {
-      super(collapseField, nullPolicy, boostDocsMap, sort, needsScores);
-    }
-
-    @Override
-    protected void doSetNextReader(LeafReaderContext context) throws IOException {
-      super.doSetNextReader(context);
-      this.segmentValues = DocValues.getSorted(context.reader(), collapseField);
-    }
-
-    @Override
-    public void collect(int contextDoc) throws IOException {
-      if (segmentValues.advanceExact(contextDoc)) {
-        int ord = segmentValues.ordValue();
-        collectDocWithGroup(contextDoc, ord);
-      } else {
-        collectDocWithNullGroup(contextDoc);
-      }
-    }
-  }
-
-  /**
-   * A block based score collector that uses a field's numeric value as the group ids
-   *
-   * @lucene.internal
-   */
-  static class BlockIntSortSpecCollector extends AbstractBlockSortSpecCollector {
-    private NumericDocValues segmentValues;
-
-    public BlockIntSortSpecCollector(
-        final String collapseField,
-        final int nullPolicy,
-        final IntIntHashMap boostDocsMap,
-        final Sort sort,
-        final boolean needsScores)
-        throws IOException {
-      super(collapseField, nullPolicy, boostDocsMap, sort, needsScores);
-    }
-
-    @Override
-    protected void doSetNextReader(LeafReaderContext context) throws IOException {
-      super.doSetNextReader(context);
-      this.segmentValues = DocValues.getNumeric(context.reader(), collapseField);
-    }
-
-    @Override
-    public void collect(int contextDoc) throws IOException {
-      if (segmentValues.advanceExact(contextDoc)) {
-        int group = (int) segmentValues.longValue();
-        collectDocWithGroup(contextDoc, group);
-      } else {
-        collectDocWithNullGroup(contextDoc);
+      } else if (this.nullPolicy == NullPolicy.COLLAPSE) {
+        if (comp.test(currentVal, nullVal)) {
+          nullVal = currentVal;
+          nullDoc = globalDoc;
+          if (needsScores) {
+            if (!needsScores4Collapsing) {
+              score = scorer.score();
+            }
+            this.nullScore = score;
+          }
+        }
+      } else if (this.nullPolicy == NullPolicy.EXPAND) {
+        this.collapsedSet.grow(1).add(globalDoc);
+        if (needsScores) {
+          if (!needsScores4Collapsing) {
+            score = scorer.score();
+          }
+          nullScores.add(score);
+        }
       }
     }
   }
 
-  private static class CollectorFactory {
-    /**
-     * @see #isNumericCollapsible
-     */
-    private static final EnumSet<NumberType> NUMERIC_COLLAPSIBLE_TYPES =
-        EnumSet.of(NumberType.INTEGER, NumberType.FLOAT);
+  /**
+   * Collector for collapsing on ordinal using the first document according to a complex sort as the
+   * group head.
+   */
+  protected static class OrdSortSpecCollector extends OrdFieldValueCollector {
+    // Configuration
+    private final SortFieldsCompare compareState;
 
-    private boolean isNumericCollapsible(FieldType collapseFieldType) {
-      return NUMERIC_COLLAPSIBLE_TYPES.contains(collapseFieldType.getNumberType());
-    }
+    // Results/accumulator
+    private float score;
 
-    public DelegatingCollector getCollector(
-        String collapseField,
-        GroupHeadSelector groupHeadSelector,
-        SortSpec sortSpec,
-        int nullPolicy,
-        String hint,
-        boolean needsScores4Collapsing,
-        boolean needsScores,
-        int size,
-        IntIntHashMap boostDocs,
-        SolrIndexSearcher searcher)
+    public OrdSortSpecCollector(OrdFieldCollectorBuilder ctx, SortSpec sortSpec)
         throws IOException {
+      super(ctx);
 
-      DocValuesProducer docValuesProducer = null;
-      FunctionQuery funcQuery = null;
+      assert GroupHeadSelectorType.SORT.equals(ctx.groupHeadSelector.type);
 
-      // block collapsing logic is much simpler and uses less memory, but is only viable in specific
-      // situations
-      final boolean blockCollapse =
-          (("_root_".equals(collapseField) || HINT_BLOCK.equals(hint))
-              // because we currently handle all min/max cases using
-              // AbstractBlockSortSpecCollector, we can't handle functions wrapping cscore()
-              // (for the same reason cscore() isn't supported in 'sort' local param)
-              && (!CollapseScore.wantsCScore(groupHeadSelector.selectorText))
-              //
-              && NullPolicy.COLLAPSE.getCode() != nullPolicy);
-      if (HINT_BLOCK.equals(hint) && !blockCollapse) {
-        log.debug(
-            "Query specifies hint={} but other local params prevent the use block based collapse",
-            HINT_BLOCK);
-      }
+      Sort sort = rewriteSort(sortSpec, ctx.searcher);
+      this.compareState = new SortFieldsCompare(sort.getSort(), valueCount);
+    }
 
-      FieldType collapseFieldType = searcher.getSchema().getField(collapseField).getType();
+    @Override
+    protected void doSetNextReader(LeafReaderContext context) throws IOException {
+      super.doSetNextReader(context);
+      compareState.setNextReader(context);
+    }
 
-      if (collapseFieldType instanceof StrField) {
-        // if we are using blockCollapse, then there is no need to bother with TOP_FC
-        if (HINT_TOP_FC.equals(hint) && !blockCollapse) {
-          @SuppressWarnings("resource")
-          final LeafReader uninvertingReader = getTopFieldCacheReader(searcher, collapseField);
+    @Override
+    public void setScorer(Scorable scorer) throws IOException {
+      super.setScorer(scorer);
+      this.compareState.setScorer(scorer);
+    }
 
-          docValuesProducer =
-              new EmptyDocValuesProducer() {
-                @Override
-                public SortedDocValues getSorted(FieldInfo ignored) throws IOException {
-                  SortedDocValues values = uninvertingReader.getSortedDocValues(collapseField);
-                  if (values != null) {
-                    return values;
-                  } else {
-                    return DocValues.emptySorted();
-                  }
-                }
-              };
-        } else {
-          docValuesProducer =
-              new EmptyDocValuesProducer() {
-                @Override
-                public SortedDocValues getSorted(FieldInfo ignored) throws IOException {
-                  return DocValues.getSorted(searcher.getSlowAtomicReader(), collapseField);
-                }
-              };
-        }
-      } else {
-        if (HINT_TOP_FC.equals(hint)) {
-          throw new SolrException(
-              SolrException.ErrorCode.BAD_REQUEST,
-              "top_fc hint is only supported when collapsing on String Fields");
-        }
+    @Override
+    protected void collapse(int ord, int contextDoc, int globalDoc) throws IOException {
+      if (needsScores4Collapsing) {
+        this.score = scorer.score();
       }
 
-      FieldType minMaxFieldType = null;
-      if (GroupHeadSelectorType.MIN_MAX.contains(groupHeadSelector.type)) {
-        final String text = groupHeadSelector.selectorText;
-        if (!text.contains("(")) {
-          minMaxFieldType = searcher.getSchema().getField(text).getType();
+      if (ord > -1) { // real collapseKey
+        if (-1 == ords.get(ord)) {
+          // we've never seen this ord (aka: collapseKey) before, treat it as group head for now
+          compareState.setGroupValues(ord, contextDoc);
+          ords.put(ord, globalDoc);
+          if (needsScores) {
+            if (!needsScores4Collapsing) {
+              this.score = scorer.score();
+            }
+            scores.put(ord, score);
+          }
         } else {
-          SolrParams params = new ModifiableSolrParams();
-          try (SolrQueryRequest request = SolrQueryRequest.wrapSearcher(searcher, params)) {
-            FunctionQParser functionQParser = new FunctionQParser(text, null, params, request);
-            funcQuery = (FunctionQuery) functionQParser.parse();
-          } catch (SyntaxError e) {
-            throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, e);
+          // test this ord to see if it's a new group leader
+          if (compareState.testAndSetGroupValues(ord, contextDoc)) {
+            ords.put(ord, globalDoc);
+            if (needsScores) {
+              if (!needsScores4Collapsing) {
+                this.score = scorer.score();
+              }
+              scores.put(ord, score);
+            }
           }
         }
-      }
-
-      int maxDoc = searcher.maxDoc();
-      int leafCount = searcher.getTopReaderContext().leaves().size();
-
-      SolrRequestInfo req = SolrRequestInfo.getRequestInfo();
-      boolean collectElevatedDocsWhenCollapsing =
-          req != null
-              && req.getReq().getParams().getBool(COLLECT_ELEVATED_DOCS_WHEN_COLLAPSING, true);
-
-      if (GroupHeadSelectorType.SCORE.equals(groupHeadSelector.type)) {
-
-        if (collapseFieldType instanceof StrField) {
-          if (blockCollapse) {
-            return new BlockOrdScoreCollector(collapseField, nullPolicy, boostDocs);
-          }
-          return new OrdScoreCollector(
-              maxDoc,
-              leafCount,
-              docValuesProducer,
-              nullPolicy,
-              boostDocs,
-              searcher,
-              collectElevatedDocsWhenCollapsing);
-
-        } else if (isNumericCollapsible(collapseFieldType)) {
-          if (blockCollapse) {
-            return new BlockIntScoreCollector(collapseField, nullPolicy, boostDocs);
+      } else if (this.nullPolicy == NullPolicy.COLLAPSE) {
+        if (-1 == nullDoc) {
+          // we've never seen a doc with null collapse key yet, treat it as the null group head for
+          // now
+          compareState.setNullGroupValues(contextDoc);
+          nullDoc = globalDoc;
+          if (needsScores) {
+            if (!needsScores4Collapsing) {
+              this.score = scorer.score();
+            }
+            this.nullScore = score;
           }
-
-          return new IntScoreCollector(
-              maxDoc,
-              leafCount,
-              nullPolicy,
-              size,
-              collapseField,
-              boostDocs,
-              searcher,
-              collectElevatedDocsWhenCollapsing);
-
         } else {
-          throw new SolrException(
-              SolrException.ErrorCode.BAD_REQUEST,
-              "Collapsing field should be of either String, Int or Float type");
-        }
-
-      } else { // min, max, sort, etc.. something other then just "score"
-
-        if (collapseFieldType instanceof StrField) {
-          if (blockCollapse) {
-            // NOTE: for now we don't worry about whether this is a sortSpec of min/max
-            // groupHeadSelector, we use a "sort spec' based block collector unless/until there is
-            // some (performance?) reason to specialize
-            return new BlockOrdSortSpecCollector(
-                collapseField,
-                nullPolicy,
-                boostDocs,
-                BlockOrdSortSpecCollector.getSort(groupHeadSelector, sortSpec, funcQuery, searcher),
-                needsScores || needsScores4Collapsing);
+          // test this doc to see if it's the new null leader
+          if (compareState.testAndSetNullGroupValues(contextDoc)) {
+            nullDoc = globalDoc;
+            if (needsScores) {
+              if (!needsScores4Collapsing) {
+                this.score = scorer.score();
+              }
+              this.nullScore = score;
+            }
           }
-
-          return new OrdFieldValueCollector(
-              maxDoc,
-              leafCount,
-              docValuesProducer,
-              nullPolicy,
-              groupHeadSelector,
-              sortSpec,
-              needsScores4Collapsing,
-              needsScores,
-              minMaxFieldType,
-              boostDocs,
-              funcQuery,
-              searcher,
-              collectElevatedDocsWhenCollapsing);
-
-        } else if (isNumericCollapsible(collapseFieldType)) {
-
-          if (blockCollapse) {
-            // NOTE: for now we don't worry about whether this is a sortSpec of min/max
-            // groupHeadSelector, we use a "sort spec' based block collector unless/until there is
-            // some (performance?) reason to specialize
-            return new BlockIntSortSpecCollector(
-                collapseField,
-                nullPolicy,
-                boostDocs,
-                BlockOrdSortSpecCollector.getSort(groupHeadSelector, sortSpec, funcQuery, searcher),
-                needsScores || needsScores4Collapsing);
+        }
+      } else if (this.nullPolicy == NullPolicy.EXPAND) {
+        this.collapsedSet.grow(1).add(globalDoc);
+        if (needsScores) {
+          if (!needsScores4Collapsing) {
+            this.score = scorer.score();
           }
-
-          return new IntFieldValueCollector(
-              maxDoc,
-              size,
-              leafCount,
-              nullPolicy,
-              collapseField,
-              groupHeadSelector,
-              sortSpec,
-              needsScores4Collapsing,
-              needsScores,
-              minMaxFieldType,
-              boostDocs,
-              funcQuery,
-              searcher,
-              collectElevatedDocsWhenCollapsing);
-        } else {
-          throw new SolrException(
-              SolrException.ErrorCode.BAD_REQUEST,
-              "Collapsing field should be of either String, Int or Float type");
+          nullScores.add(score);
         }
       }
     }
   }
 
-  public static final class CollapseScore {
-    /**
-     * Inspects the GroupHeadSelector to determine if this CollapseScore is needed. If it is, then
-     * "this" will be added to the readerContext using the "CSCORE" key, and true will be returned.
-     * If not returns false.
-     */
-    public boolean setupIfNeeded(
-        final GroupHeadSelector groupHeadSelector,
-        final Map<? super String, ? super CollapseScore> readerContext) {
-      // HACK, but not really any better options until/unless we can recursively
-      // ask value sources if they depend on score
-      if (wantsCScore(groupHeadSelector.selectorText)) {
-        readerContext.put("CSCORE", this);
-        return true;
+  /** Builder for {@link IntFieldValueCollector}. */
+  public record IntFieldCollectorBuilder(
+      GroupHeadSelector groupHeadSelector,
+      NullPolicy nullPolicy,
+      String collapseField,
+      int initialSize,
+      boolean needsScores4Collapsing,
+      IntIntHashMap boostDocsMap,
+      IndexSearcher searcher) {
+
+    public DelegatingCollector build(
+        SortSpec sortSpec, FieldType fieldType, FunctionQuery funcQuery) throws IOException {
+      if (null != sortSpec) {
+        return new IntSortSpecCollector(this, sortSpec);
+      } else if (funcQuery != null) {
+        return new IntValueSourceCollector(this, funcQuery);
+      } else {
+        NumberType numType = fieldType.getNumberType();
+        assert null != numType; // shouldn't make it here for non-numeric types
+        return switch (numType) {
+          case INTEGER -> new IntIntCollector(this);
+          case FLOAT -> new IntFloatCollector(this);
+          default ->
+              throw new SolrException(
+                  SolrException.ErrorCode.BAD_REQUEST,
+                  "min/max must be Int or Float field types when collapsing on numeric fields");
+        };
       }
-      return false;
-    }
-
-    /**
-     * Huge HACK, but not really any better options until/unless we can recursively ask value
-     * sources if they depend on score
-     */
-    public static boolean wantsCScore(final String text) {
-      return (text.contains("cscore()"));
-    }
-
-    private CollapseScore() {
-      // No-Op
     }
-
-    public float score;
   }
 
-  /*
-   * Collapse Strategies
-   */
-
   /**
-   * The abstract base Strategy for collapse strategies that collapse on an ordinal using min/max
-   * field value to select the group head.
+   * Collapses on an integer field.
+   *
+   * @lucene.internal
    */
-  private abstract static class OrdFieldValueStrategy {
-    protected int nullPolicy;
-    protected IntIntDynamicMap ords;
-    protected Scorable scorer;
-    protected FloatArrayList nullScores;
-    protected float nullScore;
-    protected IntFloatDynamicMap scores;
-    protected FixedBitSet collapsedSet;
-    protected int nullDoc = -1;
-    protected boolean needsScores;
+  protected abstract static class IntFieldValueCollector extends AbstractCollapseCollector {
+    // Configuration
+    protected final String collapseField;
+    protected final int initialSize; // data structure size hint
 
-    private final BoostedDocsCollector boostedDocsCollector;
+    // Source data
+    protected NumericDocValues collapseValues;
 
-    public abstract void collapse(int ord, int contextDoc, int globalDoc) throws IOException;
+    // Results/accumulator
+    protected final IntIntHashMap cmap;
+    protected final IntIntDynamicMap docs;
+    protected IntFloatDynamicMap scores;
 
-    public abstract void setNextReader(LeafReaderContext context) throws IOException;
+    protected IntFieldValueCollector(IntFieldCollectorBuilder ctx) throws IOException {
+      super(ctx.searcher, ctx.nullPolicy, ctx.needsScores4Collapsing, ctx.boostDocsMap);
 
-    public OrdFieldValueStrategy(
-        int maxDoc,
-        int valueCount,
-        int nullPolicy,
-        boolean needsScores,
-        BoostedDocsCollector boostedDocsCollector,
-        SortedDocValues values) {
-      this.ords = new IntIntDynamicMap(valueCount, -1);
-      this.nullPolicy = nullPolicy;
-      this.needsScores = needsScores;
-      this.collapsedSet = new FixedBitSet(maxDoc);
+      assert !GroupHeadSelectorType.SCORE.equals(ctx.groupHeadSelector.type);
 
-      this.boostedDocsCollector = boostedDocsCollector;
+      this.collapseField = ctx.collapseField;
+      this.initialSize = ctx.initialSize;
 
-      if (this.needsScores) {
-        this.scores = new IntFloatDynamicMap(valueCount, 0.0f);
-        if (nullPolicy == NullPolicy.EXPAND.getCode()) {
-          nullScores = new FloatArrayList();
-        }
-      }
+      this.cmap = new IntIntHashMap(ctx.initialSize);
+      this.docs = new IntIntDynamicMap(ctx.initialSize, 0);
     }
 
-    public FixedBitSet getCollapsedSet() {
-      // Handle the boosted docs.
-      boostedDocsCollector.purgeGroupsThatHaveBoostedDocs(
-          collapsedSet,
-          (ord) -> {
-            ords.remove(ord);
-          },
-          () -> {
-            nullDoc = -1;
-          });
-
-      // Build the sorted DocSet of group heads.
-      if (nullDoc > -1) {
-        this.collapsedSet.set(nullDoc);
+    @Override
+    protected void initializeCollection(boolean needsScores) {
+      super.initializeCollection(needsScores);
+      if (needsScores) {
+        this.scores = new IntFloatDynamicMap(initialSize, 0.0f);
       }
-      ords.forEachValue(doc -> collapsedSet.set(doc));
-
-      return collapsedSet;
-    }
-
-    public void setScorer(Scorable scorer) throws IOException {
-      this.scorer = scorer;
     }
 
-    public FloatArrayList getNullScores() {
-      return nullScores;
-    }
+    protected abstract void collapseNullGroup(int contextDoc, int globalDoc) throws IOException;
 
-    public float getNullScore() {
-      return this.nullScore;
-    }
+    protected abstract void collapse(int collapseKey, int contextDoc, int globalDoc)
+        throws IOException;
 
-    public IntFloatDynamicMap getScores() {
-      return scores;
+    @Override
+    protected void doSetNextReader(LeafReaderContext context) throws IOException {
+      super.doSetNextReader(context);
+      this.collapseValues = DocValues.getNumeric(context.reader(), this.collapseField);
     }
-  }
 
-  /*
-   * Strategy for collapsing on ordinal using min/max of an int field to select the group head.
-   */
-  private static class OrdIntStrategy extends OrdFieldValueStrategy {
-
-    private final String field;
-    private NumericDocValues minMaxValues;
-    private IntCompare comp;
-    private int nullVal;
-    private IntIntDynamicMap ordVals;
-
-    public OrdIntStrategy(
-        int maxDoc,
-        int nullPolicy,
-        int valueCount,
-        GroupHeadSelector groupHeadSelector,
-        boolean needsScores,
-        BoostedDocsCollector boostedDocsCollector,
-        SortedDocValues values)
-        throws IOException {
-      super(maxDoc, valueCount, nullPolicy, needsScores, boostedDocsCollector, values);
-      this.field = groupHeadSelector.selectorText;
-
-      assert GroupHeadSelectorType.MIN_MAX.contains(groupHeadSelector.type);
+    @Override
+    public void collect(int contextDoc) throws IOException {
+      final int globalDoc = contextDoc + this.docBase;
+      if (collapseValues.advanceExact(contextDoc)) {
+        final int collapseKey = (int) collapseValues.longValue();
+        // Check to see if we have documents boosted by the QueryElevationComponent
+        if (boostedDocsCollector.collectIfBoosted(collapseKey, globalDoc)) return;
+        collapse(collapseKey, contextDoc, globalDoc);
 
-      if (GroupHeadSelectorType.MAX.equals(groupHeadSelector.type)) {
-        comp = new MaxIntComp();
-        this.ordVals = new IntIntDynamicMap(valueCount, Integer.MIN_VALUE);
-      } else {
-        comp = new MinIntComp();
-        this.ordVals = new IntIntDynamicMap(valueCount, Integer.MAX_VALUE);
-        this.nullVal = Integer.MAX_VALUE;
+      } else { // Null Group...
+        // Check to see if we have documents boosted by the QueryElevationComponent
+        if (boostedDocsCollector.collectInNullGroupIfBoosted(globalDoc)) return;
+        if (NullPolicy.IGNORE != nullPolicy) {
+          collapseNullGroup(contextDoc, globalDoc);
+        }
       }
     }
 
     @Override
-    public void setNextReader(LeafReaderContext context) throws IOException {
-      this.minMaxValues = DocValues.getNumeric(context.reader(), this.field);
-    }
-
-    @Override
-    public void collapse(int ord, int contextDoc, int globalDoc) throws IOException {
+    protected void finishCollapsedSet() {
+      boostedDocsCollector.visitBoostedGroupKeys(cmap::remove);
 
-      int currentVal;
-      if (minMaxValues.advanceExact(contextDoc)) {
-        currentVal = (int) minMaxValues.longValue();
-      } else {
-        currentVal = 0;
+      DocIdSetBuilder.BulkAdder adder = collapsedSet.grow(cmap.size());
+      for (IntIntCursor cursor : cmap) {
+        int pointer = cursor.value;
+        adder.add(docs.get(pointer));
       }
+    }
 
-      if (ord > -1) {
-        if (comp.test(currentVal, ordVals.get(ord))) {
-          ords.put(ord, globalDoc);
-          ordVals.put(ord, currentVal);
-          if (needsScores) {
-            scores.put(ord, scorer.score());
-          }
-        }
-      } else if (this.nullPolicy == NullPolicy.COLLAPSE.getCode()) {
-        if (comp.test(currentVal, nullVal)) {
-          nullVal = currentVal;
-          nullDoc = globalDoc;
-          if (needsScores) {
-            nullScore = scorer.score();
+    @Override
+    protected Scorable getCollapsedScores(DocIdSetIterator disi, LeafReaderContext context)
+        throws IOException {
+      this.collapseValues = DocValues.getNumeric(context.reader(), this.collapseField);
+      return new CachedScoreScorable(disi) {
+        @Override
+        protected float computeScore(int globalDoc) throws IOException {
+          int contextDoc = globalDoc - context.docBase;
+          if (collapseValues.advanceExact(contextDoc)) {
+            final int collapseValue = (int) collapseValues.longValue();
+            final int pointer = cmap.get(collapseValue);
+            return scores.get(pointer);
           }
+          return scoreNullGroup(globalDoc);
         }
-      } else if (this.nullPolicy == NullPolicy.EXPAND.getCode()) {
-        this.collapsedSet.set(globalDoc);
-        if (needsScores) {
-          nullScores.add(scorer.score());
-        }
-      }
+      };
     }
   }
 
   /**
-   * Strategy for collapsing on ordinal and using the min/max value of a float field to select the
-   * group head
+   * Collector for collapsing on int field using min/max of an integer field to select group head.
    */
-  private static class OrdFloatStrategy extends OrdFieldValueStrategy {
-
+  protected static class IntIntCollector extends IntFieldValueCollector {
+    // Configuration
     private final String field;
-    private NumericDocValues minMaxValues;
-    private FloatCompare comp;
-    private float nullVal;
-    private IntFloatDynamicMap ordVals;
-
-    public OrdFloatStrategy(
-        int maxDoc,
-        int nullPolicy,
-        int valueCount,
-        GroupHeadSelector groupHeadSelector,
-        boolean needsScores,
-        BoostedDocsCollector boostedDocsCollector,
-        SortedDocValues values)
-        throws IOException {
-      super(maxDoc, valueCount, nullPolicy, needsScores, boostedDocsCollector, values);
-      this.field = groupHeadSelector.selectorText;
+    private final IntCompare comp;
 
-      assert GroupHeadSelectorType.MIN_MAX.contains(groupHeadSelector.type);
+    // Source data
+    private NumericDocValues minMaxVals;
 
-      if (GroupHeadSelectorType.MAX.equals(groupHeadSelector.type)) {
-        comp = new MaxFloatComp();
-        this.ordVals = new IntFloatDynamicMap(valueCount, -Float.MAX_VALUE);
-        this.nullVal = -Float.MAX_VALUE;
+    // Results/accumulator
+    private final IntIntDynamicMap testValues;
+    private int nullCompVal;
+    private int index = -1;
+
+    public IntIntCollector(IntFieldCollectorBuilder ctx) throws IOException {
+      super(ctx);
+      this.field = ctx.groupHeadSelector.selectorText;
+      assert GroupHeadSelectorType.MIN_MAX.contains(ctx.groupHeadSelector.type);
+      if (GroupHeadSelectorType.MAX.equals(ctx.groupHeadSelector.type)) {
+        comp = new MaxIntComp();
+        this.nullCompVal = Integer.MIN_VALUE;
       } else {
-        comp = new MinFloatComp();
-        this.ordVals = new IntFloatDynamicMap(valueCount, Float.MAX_VALUE);
-        this.nullVal = Float.MAX_VALUE;
+        comp = new MinIntComp();
+        this.nullCompVal = Integer.MAX_VALUE;
       }
-    }
 
-    @Override
-    public void setNextReader(LeafReaderContext context) throws IOException {
-      this.minMaxValues = DocValues.getNumeric(context.reader(), this.field);
+      this.testValues = new IntIntDynamicMap(ctx.initialSize, 0);
     }
 
     @Override
-    public void collapse(int ord, int contextDoc, int globalDoc) throws IOException {
+    protected void doSetNextReader(LeafReaderContext context) throws IOException {
+      super.doSetNextReader(context);
+      this.minMaxVals = DocValues.getNumeric(context.reader(), this.field);
+    }
 
-      int currentMinMax;
-      if (minMaxValues.advanceExact(contextDoc)) {
-        currentMinMax = (int) minMaxValues.longValue();
-      } else {
-        currentMinMax = 0;
+    private int advanceAndGetCurrentVal(int contextDoc) throws IOException {
+      if (minMaxVals.advanceExact(contextDoc)) {
+        return (int) minMaxVals.longValue();
       }
+      return 0;
+    }
 
-      float currentVal = Float.intBitsToFloat(currentMinMax);
+    @Override
+    protected void collapse(int collapseKey, int contextDoc, int globalDoc) throws IOException {
+      final int currentVal = advanceAndGetCurrentVal(contextDoc);
 
-      if (ord > -1) {
-        if (comp.test(currentVal, ordVals.get(ord))) {
-          ords.put(ord, globalDoc);
-          ordVals.put(ord, currentVal);
+      final int idx;
+      if ((idx = cmap.indexOf(collapseKey)) >= 0) {
+        int pointer = cmap.indexGet(idx);
+        if (comp.test(currentVal, testValues.get(pointer))) {
+          testValues.put(pointer, currentVal);
+          docs.put(pointer, globalDoc);
           if (needsScores) {
-            scores.put(ord, scorer.score());
+            scores.put(pointer, scorer.score());
           }
         }
-      } else if (this.nullPolicy == NullPolicy.COLLAPSE.getCode()) {
-        if (comp.test(currentVal, nullVal)) {
-          nullVal = currentVal;
+      } else {
+        ++index;
+        cmap.put(collapseKey, index);
+        testValues.put(index, currentVal);
+        docs.put(index, globalDoc);
+        if (needsScores) {
+          scores.put(index, scorer.score());
+        }
+      }
+    }
+
+    @Override
+    protected void collapseNullGroup(int contextDoc, int globalDoc) throws IOException {
+      assert NullPolicy.IGNORE != this.nullPolicy;
+
+      final int currentVal = advanceAndGetCurrentVal(contextDoc);
+      if (this.nullPolicy == NullPolicy.COLLAPSE) {
+        if (comp.test(currentVal, nullCompVal)) {
+          nullCompVal = currentVal;
           nullDoc = globalDoc;
           if (needsScores) {
             nullScore = scorer.score();
           }
         }
-      } else if (this.nullPolicy == NullPolicy.EXPAND.getCode()) {
-        this.collapsedSet.set(globalDoc);
+      } else if (this.nullPolicy == NullPolicy.EXPAND) {
+        this.collapsedSet.grow(1).add(globalDoc);
         if (needsScores) {
           nullScores.add(scorer.score());
         }
@@ -2517,76 +1922,87 @@ public class CollapsingQParserPlugin extends QParserPlugin {
     }
   }
 
-  /*
-   * Strategy for collapsing on ordinal and using the min/max value of a long
-   * field to select the group head
-   */
-
-  private static class OrdLongStrategy extends OrdFieldValueStrategy {
-
+  /** Collector for collapsing on int field using min/max of a float field to select group head. */
+  protected static class IntFloatCollector extends IntFieldValueCollector {
+    // Configuration
     private final String field;
+    private final FloatCompare comp;
+
+    // Source data
     private NumericDocValues minMaxVals;
-    private LongCompare comp;
-    private long nullVal;
-    private IntLongDynamicMap ordVals;
-
-    public OrdLongStrategy(
-        int maxDoc,
-        int nullPolicy,
-        int valueCount,
-        GroupHeadSelector groupHeadSelector,
-        boolean needsScores,
-        BoostedDocsCollector boostedDocsCollector,
-        SortedDocValues values)
-        throws IOException {
-      super(maxDoc, valueCount, nullPolicy, needsScores, boostedDocsCollector, values);
-      this.field = groupHeadSelector.selectorText;
 
-      assert GroupHeadSelectorType.MIN_MAX.contains(groupHeadSelector.type);
+    // Results/accumulator
+    private final IntFloatDynamicMap testValues;
+    private float nullCompVal;
+    private int index = -1;
 
-      if (GroupHeadSelectorType.MAX.equals(groupHeadSelector.type)) {
-        comp = new MaxLongComp();
-        this.ordVals = new IntLongDynamicMap(valueCount, Long.MIN_VALUE);
+    public IntFloatCollector(IntFieldCollectorBuilder ctx) throws IOException {
+      super(ctx);
+      this.field = ctx.groupHeadSelector.selectorText;
+      assert GroupHeadSelectorType.MIN_MAX.contains(ctx.groupHeadSelector.type);
+      if (GroupHeadSelectorType.MAX.equals(ctx.groupHeadSelector.type)) {
+        comp = new MaxFloatComp();
+        this.nullCompVal = -Float.MAX_VALUE;
       } else {
-        this.nullVal = Long.MAX_VALUE;
-        comp = new MinLongComp();
-        this.ordVals = new IntLongDynamicMap(valueCount, Long.MAX_VALUE);
+        comp = new MinFloatComp();
+        this.nullCompVal = Float.MAX_VALUE;
       }
+
+      this.testValues = new IntFloatDynamicMap(ctx.initialSize, 0.0f);
     }
 
     @Override
-    public void setNextReader(LeafReaderContext context) throws IOException {
+    protected void doSetNextReader(LeafReaderContext context) throws IOException {
+      super.doSetNextReader(context);
       this.minMaxVals = DocValues.getNumeric(context.reader(), this.field);
     }
 
-    @Override
-    public void collapse(int ord, int contextDoc, int globalDoc) throws IOException {
-
-      long currentVal;
+    private float advanceAndGetCurrentVal(int contextDoc) throws IOException {
       if (minMaxVals.advanceExact(contextDoc)) {
-        currentVal = minMaxVals.longValue();
-      } else {
-        currentVal = 0;
+        return Float.intBitsToFloat((int) minMaxVals.longValue());
       }
+      return 0.0f;
+    }
 
-      if (ord > -1) {
-        if (comp.test(currentVal, ordVals.get(ord))) {
-          ords.put(ord, globalDoc);
-          ordVals.put(ord, currentVal);
+    @Override
+    protected void collapse(int collapseKey, int contextDoc, int globalDoc) throws IOException {
+      final float currentVal = advanceAndGetCurrentVal(contextDoc);
+
+      final int idx;
+      if ((idx = cmap.indexOf(collapseKey)) >= 0) {
+        int pointer = cmap.indexGet(idx);
+        if (comp.test(currentVal, testValues.get(pointer))) {
+          testValues.put(pointer, currentVal);
+          docs.put(pointer, globalDoc);
           if (needsScores) {
-            scores.put(ord, scorer.score());
+            scores.put(pointer, scorer.score());
           }
         }
-      } else if (this.nullPolicy == NullPolicy.COLLAPSE.getCode()) {
-        if (comp.test(currentVal, nullVal)) {
-          nullVal = currentVal;
+      } else {
+        ++index;
+        cmap.put(collapseKey, index);
+        testValues.put(index, currentVal);
+        docs.put(index, globalDoc);
+        if (needsScores) {
+          scores.put(index, scorer.score());
+        }
+      }
+    }
+
+    @Override
+    protected void collapseNullGroup(int contextDoc, int globalDoc) throws IOException {
+      assert NullPolicy.IGNORE != this.nullPolicy;
+      final float currentVal = advanceAndGetCurrentVal(contextDoc);
+      if (this.nullPolicy == NullPolicy.COLLAPSE) {
+        if (comp.test(currentVal, nullCompVal)) {
+          nullCompVal = currentVal;
           nullDoc = globalDoc;
           if (needsScores) {
             nullScore = scorer.score();
           }
         }
-      } else if (this.nullPolicy == NullPolicy.EXPAND.getCode()) {
-        this.collapsedSet.set(globalDoc);
+      } else if (this.nullPolicy == NullPolicy.EXPAND) {
+        this.collapsedSet.grow(1).add(globalDoc);
         if (needsScores) {
           nullScores.add(scorer.score());
         }
@@ -2594,83 +2010,97 @@ public class CollapsingQParserPlugin extends QParserPlugin {
     }
   }
 
-  /*
-   * Strategy for collapsing on ordinal and using the min/max value of a value source function
-   * to select the group head
-   */
-  private static class OrdValueSourceStrategy extends OrdFieldValueStrategy {
+  /** Collector for collapsing on int field using function query to select group head. */
+  protected static class IntValueSourceCollector extends IntFieldValueCollector {
+    // Configuration
+    private final FloatCompare comp;
+    private final ValueSource valueSource;
+    private final Map<Object, Object> rcontext;
 
-    private FloatCompare comp;
-    private float nullVal;
-    private ValueSource valueSource;
+    // Source data
     private FunctionValues functionValues;
-    private IntFloatDynamicMap ordVals;
-    private Map<Object, Object> rcontext;
+
+    // Results/accumulator
     private final CollapseScore collapseScore = new CollapseScore();
-    private boolean needsScores4Collapsing;
+    private final IntFloatDynamicMap testValues;
+    private float nullCompVal;
+    private int index = -1;
 
-    public OrdValueSourceStrategy(
-        int maxDoc,
-        int nullPolicy,
-        int valueCount,
-        GroupHeadSelector groupHeadSelector,
-        boolean needsScores4Collapsing,
-        boolean needsScores,
-        BoostedDocsCollector boostedDocsCollector,
-        FunctionQuery funcQuery,
-        IndexSearcher searcher,
-        SortedDocValues values)
+    public IntValueSourceCollector(IntFieldCollectorBuilder ctx, FunctionQuery funcQuery)
         throws IOException {
-      super(maxDoc, valueCount, nullPolicy, needsScores, boostedDocsCollector, values);
-      this.needsScores4Collapsing = needsScores4Collapsing;
-      this.valueSource = funcQuery.getValueSource();
-      this.rcontext = ValueSource.newContext(searcher);
-
-      assert GroupHeadSelectorType.MIN_MAX.contains(groupHeadSelector.type);
-
-      if (GroupHeadSelectorType.MAX.equals(groupHeadSelector.type)) {
+      super(ctx);
+      assert GroupHeadSelectorType.MIN_MAX.contains(ctx.groupHeadSelector.type);
+      if (GroupHeadSelectorType.MAX.equals(ctx.groupHeadSelector.type)) {
         comp = new MaxFloatComp();
-        this.ordVals = new IntFloatDynamicMap(valueCount, -Float.MAX_VALUE);
+        nullCompVal = -Float.MAX_VALUE;
       } else {
-        this.nullVal = Float.MAX_VALUE;
         comp = new MinFloatComp();
-        this.ordVals = new IntFloatDynamicMap(valueCount, Float.MAX_VALUE);
+        nullCompVal = Float.MAX_VALUE;
       }
+      this.valueSource = funcQuery.getValueSource();
+      this.rcontext = ValueSource.newContext(ctx.searcher);
 
-      collapseScore.setupIfNeeded(groupHeadSelector, rcontext);
+      collapseScore.setupIfNeeded(ctx.groupHeadSelector, rcontext);
+
+      this.testValues = new IntFloatDynamicMap(ctx.initialSize, 0.0f);
     }
 
     @Override
-    public void setNextReader(LeafReaderContext context) throws IOException {
+    protected void doSetNextReader(LeafReaderContext context) throws IOException {
+      super.doSetNextReader(context);
       functionValues = this.valueSource.getValues(rcontext, context);
     }
 
-    @Override
-    public void collapse(int ord, int contextDoc, int globalDoc) throws IOException {
-
-      float score = 0;
-
+    private float computeScoreIfNeeded4Collapse() throws IOException {
       if (needsScores4Collapsing) {
-        score = scorer.score();
-        this.collapseScore.score = score;
+        this.collapseScore.score = scorer.score();
+        return this.collapseScore.score;
       }
+      return 0F;
+    }
 
-      float currentVal = functionValues.floatVal(contextDoc);
+    @Override
+    protected void collapse(int collapseKey, int contextDoc, int globalDoc) throws IOException {
+      float score = computeScoreIfNeeded4Collapse();
+      final float currentVal = functionValues.floatVal(contextDoc);
 
-      if (ord > -1) {
-        if (comp.test(currentVal, ordVals.get(ord))) {
-          ords.put(ord, globalDoc);
-          ordVals.put(ord, currentVal);
+      final int idx;
+      if ((idx = cmap.indexOf(collapseKey)) >= 0) {
+        int pointer = cmap.indexGet(idx);
+        if (comp.test(currentVal, testValues.get(pointer))) {
+          testValues.put(pointer, currentVal);
+          docs.put(pointer, globalDoc);
           if (needsScores) {
             if (!needsScores4Collapsing) {
               score = scorer.score();
             }
-            scores.put(ord, score);
+            scores.put(pointer, score);
           }
         }
-      } else if (this.nullPolicy == NullPolicy.COLLAPSE.getCode()) {
-        if (comp.test(currentVal, nullVal)) {
-          nullVal = currentVal;
+      } else {
+        ++index;
+        cmap.put(collapseKey, index);
+        docs.put(index, globalDoc);
+        testValues.put(index, currentVal);
+        if (needsScores) {
+          if (!needsScores4Collapsing) {
+            score = scorer.score();
+          }
+          scores.put(index, score);
+        }
+      }
+    }
+
+    @Override
+    protected void collapseNullGroup(int contextDoc, int globalDoc) throws IOException {
+      assert NullPolicy.IGNORE != this.nullPolicy;
+
+      float score = computeScoreIfNeeded4Collapse();
+      final float currentVal = functionValues.floatVal(contextDoc);
+
+      if (this.nullPolicy == NullPolicy.COLLAPSE) {
+        if (comp.test(currentVal, nullCompVal)) {
+          nullCompVal = currentVal;
           nullDoc = globalDoc;
           if (needsScores) {
             if (!needsScores4Collapsing) {
@@ -2679,8 +2109,8 @@ public class CollapsingQParserPlugin extends QParserPlugin {
             nullScore = score;
           }
         }
-      } else if (this.nullPolicy == NullPolicy.EXPAND.getCode()) {
-        this.collapsedSet.set(globalDoc);
+      } else if (this.nullPolicy == NullPolicy.EXPAND) {
+        this.collapsedSet.grow(1).add(globalDoc);
         if (needsScores) {
           if (!needsScores4Collapsing) {
             score = scorer.score();
@@ -2691,85 +2121,82 @@ public class CollapsingQParserPlugin extends QParserPlugin {
     }
   }
 
-  /*
-   * Strategy for collapsing on ordinal and using the first document according to a complex sort
-   * as the group head
-   */
-  private static class OrdSortSpecStrategy extends OrdFieldValueStrategy {
-
+  /** Collector for collapsing on int field using a sort spec to select group head. */
+  protected static class IntSortSpecCollector extends IntFieldValueCollector {
+    // Configuration
     private final SortFieldsCompare compareState;
-    private final Sort sort;
 
+    // Results/accumulator
     private float score;
-    private boolean needsScores4Collapsing;
+    private int index = -1;
 
-    public OrdSortSpecStrategy(
-        int maxDoc,
-        int nullPolicy,
-        int valueCount,
-        GroupHeadSelector groupHeadSelector,
-        boolean needsScores4Collapsing,
-        boolean needsScores,
-        BoostedDocsCollector boostedDocsCollector,
-        SortSpec sortSpec,
-        IndexSearcher searcher,
-        SortedDocValues values)
+    public IntSortSpecCollector(IntFieldCollectorBuilder ctx, SortSpec sortSpec)
         throws IOException {
-      super(maxDoc, valueCount, nullPolicy, needsScores, boostedDocsCollector, values);
-      this.needsScores4Collapsing = needsScores4Collapsing;
-
-      assert GroupHeadSelectorType.SORT.equals(groupHeadSelector.type);
-
-      this.sort = rewriteSort(sortSpec, searcher);
+      super(ctx);
 
-      this.compareState = new SortFieldsCompare(sort.getSort(), valueCount);
-    }
+      assert GroupHeadSelectorType.SORT.equals(ctx.groupHeadSelector.type);
 
-    @Override
-    public void setNextReader(LeafReaderContext context) throws IOException {
-      compareState.setNextReader(context);
+      Sort sort = rewriteSort(sortSpec, ctx.searcher);
+      this.compareState = new SortFieldsCompare(sort.getSort(), ctx.initialSize);
     }
 
     @Override
-    public void setScorer(Scorable s) throws IOException {
-      super.setScorer(s);
-      this.compareState.setScorer(s);
+    protected void doSetNextReader(LeafReaderContext context) throws IOException {
+      super.doSetNextReader(context);
+      compareState.setNextReader(context);
     }
 
     @Override
-    public void collapse(int ord, int contextDoc, int globalDoc) throws IOException {
+    public void setScorer(Scorable scorer) throws IOException {
+      super.setScorer(scorer);
+      this.compareState.setScorer(scorer);
+    }
 
+    private float computeScoreIfNeeded4Collapse() throws IOException {
       if (needsScores4Collapsing) {
-        this.score = scorer.score();
+        return scorer.score();
       }
+      return 0f;
+    }
 
-      if (ord > -1) { // real collapseKey
-        if (-1 == ords.get(ord)) {
-          // we've never seen this ord (aka: collapseKey) before, treat it as group head for now
-          compareState.setGroupValues(ord, contextDoc);
-          ords.put(ord, globalDoc);
+    @Override
+    protected void collapse(int collapseKey, int contextDoc, int globalDoc) throws IOException {
+      score = computeScoreIfNeeded4Collapse();
+
+      final int idx;
+      if ((idx = cmap.indexOf(collapseKey)) >= 0) {
+        int pointer = cmap.indexGet(idx);
+        if (compareState.testAndSetGroupValues(pointer, contextDoc)) {
+          docs.put(pointer, globalDoc);
           if (needsScores) {
             if (!needsScores4Collapsing) {
               this.score = scorer.score();
             }
-            scores.put(ord, score);
+            scores.put(pointer, score);
           }
-        } else {
-          // test this ord to see if it's a new group leader
-          if (compareState.testAndSetGroupValues(ord, contextDoc)) { // TODO X
-            ords.put(ord, globalDoc);
-            if (needsScores) {
-              if (!needsScores4Collapsing) {
-                this.score = scorer.score();
-              }
-              scores.put(ord, score);
-            }
+        }
+      } else {
+        ++index;
+        cmap.put(collapseKey, index);
+        docs.put(index, globalDoc);
+        compareState.setGroupValues(index, contextDoc);
+        if (needsScores) {
+          if (!needsScores4Collapsing) {
+            this.score = scorer.score();
           }
+          scores.put(index, score);
         }
-      } else if (this.nullPolicy == NullPolicy.COLLAPSE.getCode()) {
+      }
+    }
+
+    @Override
+    protected void collapseNullGroup(int contextDoc, int globalDoc) throws IOException {
+      assert NullPolicy.IGNORE != this.nullPolicy;
+
+      score = computeScoreIfNeeded4Collapse();
+
+      if (this.nullPolicy == NullPolicy.COLLAPSE) {
         if (-1 == nullDoc) {
-          // we've never seen a doc with null collapse key yet, treat it as the null group head for
-          // now
           compareState.setNullGroupValues(contextDoc);
           nullDoc = globalDoc;
           if (needsScores) {
@@ -2779,7 +2206,6 @@ public class CollapsingQParserPlugin extends QParserPlugin {
             nullScore = score;
           }
         } else {
-          // test this doc to see if it's the new null leader
           if (compareState.testAndSetNullGroupValues(contextDoc)) {
             nullDoc = globalDoc;
             if (needsScores) {
@@ -2790,8 +2216,8 @@ public class CollapsingQParserPlugin extends QParserPlugin {
             }
           }
         }
-      } else if (this.nullPolicy == NullPolicy.EXPAND.getCode()) {
-        this.collapsedSet.set(globalDoc);
+      } else if (this.nullPolicy == NullPolicy.EXPAND) {
+        this.collapsedSet.grow(1).add(globalDoc);
         if (needsScores) {
           if (!needsScores4Collapsing) {
             this.score = scorer.score();
@@ -2802,550 +2228,565 @@ public class CollapsingQParserPlugin extends QParserPlugin {
     }
   }
 
-  /*
-   * Base strategy for collapsing on a 32 bit numeric field and selecting a group head
-   * based on min/max value of a 32 bit numeric field.
+  /**
+   * Base class for collectors that will do collapsing using "block indexed" documents
+   *
+   * @lucene.internal
    */
+  private abstract static class AbstractBlockCollector extends DelegatingCollector {
 
-  private abstract static class IntFieldValueStrategy {
-    protected int nullPolicy;
-    protected IntIntHashMap cmap;
-    protected Scorable scorer;
-    protected FloatArrayList nullScores;
-    protected float nullScore;
-    protected IntFloatDynamicMap scores;
-    protected FixedBitSet collapsedSet;
-    protected int nullDoc = -1;
-    protected boolean needsScores;
-    protected String collapseField;
-    protected IntIntDynamicMap docs;
+    // Configuration
+    protected final String collapseField;
+    protected final boolean needsScores4Collapsing;
+    protected final boolean expandNulls;
 
-    private final BoostedDocsCollector boostedDocsCollector;
+    // Results/accumulator
+    protected final BlockGroupState currentGroupState = new BlockGroupState();
+    private final MergeBoost boostDocs;
 
-    public abstract void collapseNullGroup(int contextDoc, int globalDoc) throws IOException;
+    protected AbstractBlockCollector(
+        final String collapseField,
+        final NullPolicy nullPolicy,
+        final IntIntHashMap boostDocsMap,
+        final boolean needsScores4Collapsing) {
 
-    public abstract void collapse(int collapseKey, int contextDoc, int globalDoc)
-        throws IOException;
+      this.collapseField = collapseField;
+      this.needsScores4Collapsing = needsScores4Collapsing;
 
-    public abstract void setNextReader(LeafReaderContext context) throws IOException;
+      assert nullPolicy == NullPolicy.IGNORE || nullPolicy == NullPolicy.EXPAND;
+      this.expandNulls = (NullPolicy.EXPAND == nullPolicy);
+      this.boostDocs = BoostedDocsCollector.build(boostDocsMap).getMergeBoost();
 
-    public IntFieldValueStrategy(
-        int maxDoc,
-        int size,
-        String collapseField,
-        int nullPolicy,
-        boolean needsScores,
-        BoostedDocsCollector boostedDocsCollector) {
-      this.collapseField = collapseField;
-      this.nullPolicy = nullPolicy;
-      this.needsScores = needsScores;
-      this.collapsedSet = new FixedBitSet(maxDoc);
-      this.cmap = new IntIntHashMap(size);
-      this.docs = new IntIntDynamicMap(size, 0);
+      currentGroupState.resetForNewGroup();
+    }
 
-      this.boostedDocsCollector = boostedDocsCollector;
+    @Override
+    public ScoreMode scoreMode() {
+      return needsScores4Collapsing ? ScoreMode.COMPLETE : super.scoreMode();
+    }
 
-      if (needsScores) {
-        this.scores = new IntFloatDynamicMap(size, 0.0f);
-        if (nullPolicy == NullPolicy.EXPAND.getCode()) {
-          nullScores = new FloatArrayList();
-        }
+    /** If we have a candidate match, delegate the collection of that match. */
+    protected void maybeDelegateCollect() throws IOException {
+      if (currentGroupState.isCurrentDocCollectable()) {
+        delegateCollect();
       }
     }
 
-    public FixedBitSet getCollapsedSet() {
+    /** Immediately delegate the collection of the current doc */
+    protected void delegateCollect() throws IOException {
+      // ensure we have the 'correct' scorer
+      // (our supper class may have set the "real" scorer on our leafDelegate
+      // and it may have an incorrect docID)
+      leafDelegate.setScorer(currentGroupState);
+      leafDelegate.collect(currentGroupState.docId);
+    }
+
+    /**
+     * NOTE: collects the best doc for the last group in the previous segment subclasses must call
+     * super <em>BEFORE</em> they make any changes to their own state that might influence
+     * collection
+     */
+    @Override
+    protected void doSetNextReader(LeafReaderContext context) throws IOException {
+      maybeDelegateCollect();
+      // Now setup for the next segment.
+      currentGroupState.resetForNewGroup();
+      this.docBase = context.docBase;
+      super.doSetNextReader(context);
+    }
+
+    /**
+     * Acts as an id iterator over the boosted docs
+     *
+     * @param contextDoc the context specific docId to check for, iterator is advanced to this id
+     * @return true if the contextDoc is boosted, false otherwise.
+     */
+    protected boolean isBoostedAdvanceExact(final int contextDoc) {
+      return boostDocs.boost(contextDoc + docBase);
+    }
+
+    @Override
+    public void complete() throws IOException {
+      // Deal with last group (if any)...
+      maybeDelegateCollect();
 
-      // Handle the boosted docs.
-      boostedDocsCollector.purgeGroupsThatHaveBoostedDocs(
-          collapsedSet,
-          (key) -> {
-            cmap.remove(key);
-          },
-          () -> {
-            nullDoc = -1;
-          });
+      super.complete();
+    }
 
-      // Build the sorted DocSet of group heads.
-      if (nullDoc > -1) {
-        this.collapsedSet.set(nullDoc);
+    /**
+     * Encapsulates basic state information about the current group, and the "best matching"
+     * document in that group (so far)
+     */
+    protected static final class BlockGroupState extends ScoreAndDoc {
+      /**
+       * Specific values have no intrinsic meaning, but can <em>only</em> be considered if the
+       * current docID is non-negative
+       */
+      private int currentGroup = 0;
+
+      private boolean groupHasBoostedDocs;
+
+      public void setCurrentGroup(final int groupId) {
+        this.currentGroup = groupId;
       }
-      Iterator<IntIntCursor> it1 = cmap.iterator();
-      while (it1.hasNext()) {
-        IntIntCursor cursor = it1.next();
-        int pointer = cursor.value;
-        collapsedSet.set(docs.get(pointer));
+
+      public int getCurrentGroup() {
+        assert -1 < this.docId;
+        return this.currentGroup;
+      }
+
+      public void setBestDocForCurrentGroup(final int contextDoc, final boolean isBoosted) {
+        this.docId = contextDoc;
+        this.groupHasBoostedDocs |= isBoosted;
+      }
+
+      public void resetForNewGroup() {
+        this.docId = -1;
+        this.score = Float.MIN_VALUE;
+        this.groupHasBoostedDocs = false;
+      }
+
+      public boolean hasBoostedDocs() {
+        assert -1 < this.docId;
+        return groupHasBoostedDocs;
+      }
+
+      /**
+       * Returns true if we have a valid ("best match") docId for the current group and there are no
+       * boosted docs for this group (If the current doc was boosted, it should have already been
+       * collected)
+       */
+      public boolean isCurrentDocCollectable() {
+        return (-1 < this.docId && !groupHasBoostedDocs);
       }
+    }
+  }
+
+  /**
+   * Collapses groups on a block using a field that has values unique to that block (example: <code>
+   * _root_</code>) choosing the group head based on score
+   *
+   * @lucene.internal
+   */
+  abstract static class AbstractBlockScoreCollector extends AbstractBlockCollector {
+
+    public AbstractBlockScoreCollector(
+        final String collapseField, final NullPolicy nullPolicy, final IntIntHashMap boostDocsMap) {
+      super(collapseField, nullPolicy, boostDocsMap, true);
+    }
+
+    private void setCurrentGroupBestMatch(
+        final int contextDocId, final float score, final boolean isBoosted) {
+      currentGroupState.setBestDocForCurrentGroup(contextDocId, isBoosted);
+      currentGroupState.score = score;
+    }
+
+    /**
+     * This method should be called by subclasses for each doc + group encountered
+     *
+     * @param contextDoc a valid doc id relative to the current reader context
+     * @param docGroup some uique identifier for the group - the base class makes no assumptions
+     *     about it's meaning
+     * @see #collectDocWithNullGroup
+     */
+    protected void collectDocWithGroup(int contextDoc, int docGroup) throws IOException {
+      assert 0 <= contextDoc;
+
+      final boolean isBoosted = isBoostedAdvanceExact(contextDoc);
+
+      if (-1 < currentGroupState.docId && docGroup == currentGroupState.getCurrentGroup()) {
+        // we have an existing group, and contextDoc is in that group.
+
+        if (isBoosted) {
+          // this doc is the best and should be immediately collected regardless of score
+          setCurrentGroupBestMatch(contextDoc, scorer.score(), isBoosted);
+          delegateCollect();
+
+        } else if (currentGroupState.hasBoostedDocs()) {
+          // No-Op: nothing about this doc matters since we've already collected boosted docs in
+          // this group
+
+          // No-Op
+        } else {
+          // check if this doc the new 'best' doc in this group...
+          final float score = scorer.score();
+          if (score > currentGroupState.score) {
+            setCurrentGroupBestMatch(contextDoc, scorer.score(), isBoosted);
+          }
+        }
+
+      } else {
+        // We have a document that starts a new group (or may be the first doc+group we've collected
+        // this segment)
+
+        // first collect the prior group if needed...
+        maybeDelegateCollect();
+
+        // then setup the new group and current best match
+        currentGroupState.resetForNewGroup();
+        currentGroupState.setCurrentGroup(docGroup);
+        setCurrentGroupBestMatch(contextDoc, scorer.score(), isBoosted);
 
-      return collapsedSet;
+        if (isBoosted) { // collect immediately
+          delegateCollect();
+        }
+      }
     }
 
-    public void setScorer(Scorable scorer) throws IOException {
-      this.scorer = scorer;
-    }
+    /**
+     * This method should be called by subclasses for each doc encountered that is not in a group
+     * (ie: null group)
+     *
+     * @param contextDoc a valid doc id relative to the current reader context
+     * @see #collectDocWithGroup
+     */
+    protected void collectDocWithNullGroup(int contextDoc) throws IOException {
+      assert 0 <= contextDoc;
+
+      // NOTE: with 'null group' docs, it doesn't matter if they are boosted since we don't suppor
+      // collapsing nulls
+
+      // this doc is definitely not part of any prior group, so collect if needed...
+      maybeDelegateCollect();
+
+      if (expandNulls) {
+        // set & immediately collect our current doc...
+        setCurrentGroupBestMatch(contextDoc, scorer.score(), false);
+        delegateCollect();
+
+      } else {
+        // we're ignoring nulls, so: No-Op.
+      }
 
-    public FloatArrayList getNullScores() {
-      return nullScores;
+      // either way re-set for the next doc / group
+      currentGroupState.resetForNewGroup();
     }
+  }
 
-    public IntIntHashMap getCollapseMap() {
-      return cmap;
-    }
+  /**
+   * A block based score collector that uses a field's "ord" as the group ids
+   *
+   * @lucene.internal
+   */
+  static class BlockOrdScoreCollector extends AbstractBlockScoreCollector {
+    private SortedDocValues segmentValues;
 
-    public float getNullScore() {
-      return this.nullScore;
+    public BlockOrdScoreCollector(
+        final String collapseField, final NullPolicy nullPolicy, final IntIntHashMap boostDocsMap)
+        throws IOException {
+      super(collapseField, nullPolicy, boostDocsMap);
     }
 
-    public IntFloatDynamicMap getScores() {
-      return scores;
+    @Override
+    protected void doSetNextReader(LeafReaderContext context) throws IOException {
+      super.doSetNextReader(context);
+      this.segmentValues = DocValues.getSorted(context.reader(), collapseField);
     }
 
-    public IntIntDynamicMap getDocs() {
-      return docs;
+    @Override
+    public void collect(int contextDoc) throws IOException {
+      if (segmentValues.advanceExact(contextDoc)) {
+        int ord = segmentValues.ordValue();
+        collectDocWithGroup(contextDoc, ord);
+      } else {
+        collectDocWithNullGroup(contextDoc);
+      }
     }
   }
 
-  /*
-   *  Strategy for collapsing on a 32 bit numeric field and selecting the group head based
-   *  on the min/max value of a 32 bit field numeric field.
+  /**
+   * A block based score collector that uses a field's numeric value as the group ids
+   *
+   * @lucene.internal
    */
-  private static class IntIntStrategy extends IntFieldValueStrategy {
-
-    private final String field;
-    private NumericDocValues minMaxVals;
-    private IntIntDynamicMap testValues;
-    private IntCompare comp;
-    private int nullCompVal;
-
-    private int index = -1;
+  static class BlockIntScoreCollector extends AbstractBlockScoreCollector {
+    private NumericDocValues segmentValues;
 
-    public IntIntStrategy(
-        int maxDoc,
-        int size,
-        String collapseField,
-        int nullPolicy,
-        GroupHeadSelector groupHeadSelector,
-        boolean needsScores,
-        BoostedDocsCollector boostedDocsCollector)
+    public BlockIntScoreCollector(
+        final String collapseField, final NullPolicy nullPolicy, final IntIntHashMap boostDocsMap)
         throws IOException {
-
-      super(maxDoc, size, collapseField, nullPolicy, needsScores, boostedDocsCollector);
-      this.field = groupHeadSelector.selectorText;
-      this.testValues = new IntIntDynamicMap(size, 0);
-
-      assert GroupHeadSelectorType.MIN_MAX.contains(groupHeadSelector.type);
-
-      if (GroupHeadSelectorType.MAX.equals(groupHeadSelector.type)) {
-        comp = new MaxIntComp();
-        this.nullCompVal = Integer.MIN_VALUE;
-      } else {
-        comp = new MinIntComp();
-        this.nullCompVal = Integer.MAX_VALUE;
-      }
+      super(collapseField, nullPolicy, boostDocsMap);
     }
 
     @Override
-    public void setNextReader(LeafReaderContext context) throws IOException {
-      this.minMaxVals = DocValues.getNumeric(context.reader(), this.field);
-    }
-
-    private int advanceAndGetCurrentVal(int contextDoc) throws IOException {
-      if (minMaxVals.advanceExact(contextDoc)) {
-        return (int) minMaxVals.longValue();
-      } // else...
-      return 0;
+    protected void doSetNextReader(LeafReaderContext context) throws IOException {
+      super.doSetNextReader(context);
+      this.segmentValues = DocValues.getNumeric(context.reader(), collapseField);
     }
 
     @Override
-    public void collapse(int collapseKey, int contextDoc, int globalDoc) throws IOException {
-      final int currentVal = advanceAndGetCurrentVal(contextDoc);
-
-      final int idx;
-      if ((idx = cmap.indexOf(collapseKey)) >= 0) {
-        int pointer = cmap.indexGet(idx);
-        if (comp.test(currentVal, testValues.get(pointer))) {
-          testValues.put(pointer, currentVal);
-          docs.put(pointer, globalDoc);
-          if (needsScores) {
-            scores.put(pointer, scorer.score());
-          }
-        }
+    public void collect(int contextDoc) throws IOException {
+      if (segmentValues.advanceExact(contextDoc)) {
+        int group = (int) segmentValues.longValue();
+        collectDocWithGroup(contextDoc, group);
       } else {
-        ++index;
-        cmap.put(collapseKey, index);
-        testValues.put(index, currentVal);
-        docs.put(index, globalDoc);
-        if (needsScores) {
-          scores.put(index, scorer.score());
-        }
+        collectDocWithNullGroup(contextDoc);
       }
     }
+  }
 
-    @Override
-    public void collapseNullGroup(int contextDoc, int globalDoc) throws IOException {
-      assert NullPolicy.IGNORE.getCode() != this.nullPolicy;
+  /**
+   * Collapses groups on a block using a field that has values unique to that block (example: <code>
+   * _root_</code>) choosing the group head based on a {@link SortSpec} (which can be synthetically
+   * created for min/max group head selectors using {@link #getSort})
+   *
+   * <p>Note that since this collector does a single pass, and unlike other collectors doesn't need
+   * to maintain a large data structure of scores (for all matching docs) when they might be needed
+   * for the response, it has no need to distinguish between the concepts of <code>
+   * needsScores4Collapsing</code> vs </code>needsScores</code>
+   *
+   * @lucene.internal
+   */
+  abstract static class AbstractBlockSortSpecCollector extends AbstractBlockCollector {
 
-      final int currentVal = advanceAndGetCurrentVal(contextDoc);
-      if (this.nullPolicy == NullPolicy.COLLAPSE.getCode()) {
-        if (comp.test(currentVal, nullCompVal)) {
-          nullCompVal = currentVal;
-          nullDoc = globalDoc;
-          if (needsScores) {
-            nullScore = scorer.score();
-          }
-        }
-      } else if (this.nullPolicy == NullPolicy.EXPAND.getCode()) {
-        this.collapsedSet.set(globalDoc);
-        if (needsScores) {
-          nullScores.add(scorer.score());
+    /**
+     * Helper method for extracting a {@link Sort} out of a {@link SortSpec} <em>or</em> creating
+     * one synthetically for "min/max" {@link GroupHeadSelector} against a {@link FunctionQuery}
+     * <em>or</em> simple field name.
+     *
+     * @return appropriate (already re-written) Sort to use with a AbstractBlockSortSpecCollector
+     */
+    public static Sort getSort(
+        final GroupHeadSelector groupHeadSelector,
+        final SortSpec sortSpec,
+        final FunctionQuery funcQuery,
+        final SolrIndexSearcher searcher)
+        throws IOException {
+      if (null != sortSpec) {
+        assert GroupHeadSelectorType.SORT.equals(groupHeadSelector.type);
+
+        // a "feature" of SortSpec is that getSort() is null if we're just using 'score desc'
+        if (null == sortSpec.getSort()) {
+          return Sort.RELEVANCE.rewrite(searcher);
         }
-      }
-    }
-  }
+        return sortSpec.getSort().rewrite(searcher);
+      } // else: min/max on field or value source...
 
-  private static class IntFloatStrategy extends IntFieldValueStrategy {
+      assert GroupHeadSelectorType.MIN_MAX.contains(groupHeadSelector.type);
+      assert !CollapseScore.wantsCScore(groupHeadSelector.selectorText);
 
-    private final String field;
-    private NumericDocValues minMaxVals;
-    private IntFloatDynamicMap testValues;
-    private FloatCompare comp;
-    private float nullCompVal;
+      final boolean reverse = GroupHeadSelectorType.MAX.equals(groupHeadSelector.type);
+      final SortField sf =
+          (null != funcQuery)
+              ? funcQuery.getValueSource().getSortField(reverse)
+              : searcher.getSchema().getField(groupHeadSelector.selectorText).getSortField(reverse);
 
-    private int index = -1;
+      return (new Sort(sf)).rewrite(searcher);
+    }
 
-    public IntFloatStrategy(
-        int maxDoc,
-        int size,
-        String collapseField,
-        int nullPolicy,
-        GroupHeadSelector groupHeadSelector,
-        boolean needsScores,
-        BoostedDocsCollector boostedDocsCollector)
-        throws IOException {
+    private final BlockBasedSortFieldsCompare sortsCompare;
 
-      super(maxDoc, size, collapseField, nullPolicy, needsScores, boostedDocsCollector);
-      this.field = groupHeadSelector.selectorText;
-      this.testValues = new IntFloatDynamicMap(size, 0.0f);
+    public AbstractBlockSortSpecCollector(
+        final String collapseField,
+        final NullPolicy nullPolicy,
+        final IntIntHashMap boostDocsMap,
+        final Sort sort) {
+      super(collapseField, nullPolicy, boostDocsMap, sort.needsScores());
+      this.sortsCompare = new BlockBasedSortFieldsCompare(sort.getSort());
+    }
 
-      assert GroupHeadSelectorType.MIN_MAX.contains(groupHeadSelector.type);
+    @Override
+    public void setScorer(Scorable scorer) throws IOException {
+      super.setScorer(scorer);
+      sortsCompare.setScorer(scorer);
+    }
 
-      if (GroupHeadSelectorType.MAX.equals(groupHeadSelector.type)) {
-        comp = new MaxFloatComp();
-        this.nullCompVal = -Float.MAX_VALUE;
-      } else {
-        comp = new MinFloatComp();
-        this.nullCompVal = Float.MAX_VALUE;
+    private void setCurrentGroupBestMatch(final int contextDocId, final boolean isBoosted)
+        throws IOException {
+      currentGroupState.setBestDocForCurrentGroup(contextDocId, isBoosted);
+      if (scoreMode().needsScores()) {
+        currentGroupState.score = scorer.score();
       }
     }
 
     @Override
-    public void setNextReader(LeafReaderContext context) throws IOException {
-      this.minMaxVals = DocValues.getNumeric(context.reader(), this.field);
+    protected void doSetNextReader(LeafReaderContext context) throws IOException {
+      super.doSetNextReader(context);
+      this.sortsCompare.setNextReader(context);
     }
 
-    private float advanceAndGetCurrentVal(int contextDoc) throws IOException {
-      if (minMaxVals.advanceExact(contextDoc)) {
-        return Float.intBitsToFloat((int) minMaxVals.longValue());
-      } // else...
-      return Float.intBitsToFloat(0);
-    }
+    /**
+     * This method should be called by subclasses for each doc + group encountered
+     *
+     * @param contextDoc a valid doc id relative to the current reader context
+     * @param docGroup some uique identifier for the group - the base class makes no assumptions
+     *     about it's meaning
+     * @see #collectDocWithNullGroup
+     */
+    protected void collectDocWithGroup(int contextDoc, int docGroup) throws IOException {
+      assert 0 <= contextDoc;
 
-    @Override
-    public void collapse(int collapseKey, int contextDoc, int globalDoc) throws IOException {
-      final float currentVal = advanceAndGetCurrentVal(contextDoc);
+      final boolean isBoosted = isBoostedAdvanceExact(contextDoc);
 
-      final int idx;
-      if ((idx = cmap.indexOf(collapseKey)) >= 0) {
-        int pointer = cmap.indexGet(idx);
-        if (comp.test(currentVal, testValues.get(pointer))) {
-          testValues.put(pointer, currentVal);
-          docs.put(pointer, globalDoc);
-          if (needsScores) {
-            scores.put(pointer, scorer.score());
+      if (-1 < currentGroupState.docId && docGroup == currentGroupState.getCurrentGroup()) {
+        // we have an existing group, and contextDoc is in that group.
+
+        if (isBoosted) {
+          // this doc is the best and should be immediately collected regardless of sort values
+          setCurrentGroupBestMatch(contextDoc, isBoosted);
+          delegateCollect();
+
+        } else if (currentGroupState.hasBoostedDocs()) {
+          // No-Op: nothing about this doc matters since we've already collected boosted docs in
+          // this group
+
+          // No-Op
+        } else {
+          // check if it's the new 'best' doc in this group...
+          if (sortsCompare.testAndSetGroupValues(contextDoc)) {
+            setCurrentGroupBestMatch(contextDoc, isBoosted);
           }
         }
+
       } else {
-        ++index;
-        cmap.put(collapseKey, index);
-        testValues.put(index, currentVal);
-        docs.put(index, globalDoc);
-        if (needsScores) {
-          scores.put(index, scorer.score());
-        }
-      }
-    }
+        // We have a document that starts a new group (or may be the first doc+group we've collected
+        // this segmen)
 
-    @Override
-    public void collapseNullGroup(int contextDoc, int globalDoc) throws IOException {
-      assert NullPolicy.IGNORE.getCode() != this.nullPolicy;
-      final float currentVal = advanceAndGetCurrentVal(contextDoc);
-      if (this.nullPolicy == NullPolicy.COLLAPSE.getCode()) {
-        if (comp.test(currentVal, nullCompVal)) {
-          nullCompVal = currentVal;
-          nullDoc = globalDoc;
-          if (needsScores) {
-            nullScore = scorer.score();
-          }
-        }
-      } else if (this.nullPolicy == NullPolicy.EXPAND.getCode()) {
-        this.collapsedSet.set(globalDoc);
-        if (needsScores) {
-          nullScores.add(scorer.score());
+        // first collect the prior group if needed...
+        maybeDelegateCollect();
+
+        // then setup the new group and current best match
+        currentGroupState.resetForNewGroup();
+        currentGroupState.setCurrentGroup(docGroup);
+        sortsCompare.setGroupValues(contextDoc);
+        setCurrentGroupBestMatch(contextDoc, isBoosted);
+
+        if (isBoosted) { // collect immediately
+          delegateCollect();
         }
       }
     }
-  }
-
-  /*
-   *  Strategy for collapsing on a 32 bit numeric field and selecting the group head based
-   *  on the min/max value of a Value Source Function.
-   */
-  private static class IntValueSourceStrategy extends IntFieldValueStrategy {
-
-    private FloatCompare comp;
-    private IntFloatDynamicMap testValues;
-    private float nullCompVal;
 
-    private ValueSource valueSource;
-    private FunctionValues functionValues;
-    private Map<Object, Object> rcontext;
-    private final CollapseScore collapseScore = new CollapseScore();
-    private int index = -1;
-    private boolean needsScores4Collapsing;
-
-    public IntValueSourceStrategy(
-        int maxDoc,
-        int size,
-        String collapseField,
-        int nullPolicy,
-        GroupHeadSelector groupHeadSelector,
-        boolean needsScores4Collapsing,
-        boolean needsScores,
-        BoostedDocsCollector boostedDocsCollector,
-        FunctionQuery funcQuery,
-        IndexSearcher searcher)
-        throws IOException {
-
-      super(maxDoc, size, collapseField, nullPolicy, needsScores, boostedDocsCollector);
+    /**
+     * This method should be called by subclasses for each doc encountered that is not in a group
+     * (ie: null group)
+     *
+     * @param contextDoc a valid doc id relative to the current reader context
+     * @see #collectDocWithGroup
+     */
+    protected void collectDocWithNullGroup(int contextDoc) throws IOException {
+      assert 0 <= contextDoc;
 
-      this.needsScores4Collapsing = needsScores4Collapsing;
-      this.testValues = new IntFloatDynamicMap(size, 0.0f);
+      // NOTE: with 'null group' docs, it doesn't matter if they are boosted since we don't suppor
+      // collapsing nulls
 
-      this.valueSource = funcQuery.getValueSource();
-      this.rcontext = ValueSource.newContext(searcher);
+      // this doc is definitely not part of any prior group, so collect if needed...
+      maybeDelegateCollect();
 
-      assert GroupHeadSelectorType.MIN_MAX.contains(groupHeadSelector.type);
+      if (expandNulls) {
+        // set & immediately collect our current doc...
+        setCurrentGroupBestMatch(contextDoc, false);
+        // NOTE: sort values don't matter
+        delegateCollect();
 
-      if (GroupHeadSelectorType.MAX.equals(groupHeadSelector.type)) {
-        this.nullCompVal = -Float.MAX_VALUE;
-        comp = new MaxFloatComp();
       } else {
-        this.nullCompVal = Float.MAX_VALUE;
-        comp = new MinFloatComp();
+        // we're ignoring nulls, so: No-Op.
       }
 
-      collapseScore.setupIfNeeded(groupHeadSelector, rcontext);
+      // either way re-set for the next doc / group
+      currentGroupState.resetForNewGroup();
     }
+  }
 
-    @Override
-    @SuppressWarnings({"unchecked"})
-    public void setNextReader(LeafReaderContext context) throws IOException {
-      functionValues = this.valueSource.getValues(rcontext, context);
-    }
+  /**
+   * A block based score collector that uses a field's "ord" as the group ids
+   *
+   * @lucene.internal
+   */
+  static class BlockOrdSortSpecCollector extends AbstractBlockSortSpecCollector {
+    private SortedDocValues segmentValues;
 
-    private float computeScoreIfNeeded4Collapse() throws IOException {
-      if (needsScores4Collapsing) {
-        this.collapseScore.score = scorer.score();
-        return this.collapseScore.score;
-      } // else...
-      return 0F;
+    public BlockOrdSortSpecCollector(
+        final String collapseField,
+        final NullPolicy nullPolicy,
+        final IntIntHashMap boostDocsMap,
+        final Sort sort)
+        throws IOException {
+      super(collapseField, nullPolicy, boostDocsMap, sort);
     }
 
     @Override
-    public void collapse(int collapseKey, int contextDoc, int globalDoc) throws IOException {
-
-      float score = computeScoreIfNeeded4Collapse();
-      final float currentVal = functionValues.floatVal(contextDoc);
-
-      final int idx;
-      if ((idx = cmap.indexOf(collapseKey)) >= 0) {
-        int pointer = cmap.indexGet(idx);
-        if (comp.test(currentVal, testValues.get(pointer))) {
-          testValues.put(pointer, currentVal);
-          docs.put(pointer, globalDoc);
-          if (needsScores) {
-            if (!needsScores4Collapsing) {
-              score = scorer.score();
-            }
-            scores.put(pointer, score);
-          }
-        }
-      } else {
-        ++index;
-        cmap.put(collapseKey, index);
-        docs.put(index, globalDoc);
-        testValues.put(index, currentVal);
-        if (needsScores) {
-          if (!needsScores4Collapsing) {
-            score = scorer.score();
-          }
-          scores.put(index, score);
-        }
-      }
+    protected void doSetNextReader(LeafReaderContext context) throws IOException {
+      super.doSetNextReader(context);
+      this.segmentValues = DocValues.getSorted(context.reader(), collapseField);
     }
 
     @Override
-    public void collapseNullGroup(int contextDoc, int globalDoc) throws IOException {
-      assert NullPolicy.IGNORE.getCode() != this.nullPolicy;
-
-      float score = computeScoreIfNeeded4Collapse();
-      final float currentVal = functionValues.floatVal(contextDoc);
-
-      if (this.nullPolicy == NullPolicy.COLLAPSE.getCode()) {
-        if (comp.test(currentVal, nullCompVal)) {
-          nullCompVal = currentVal;
-          nullDoc = globalDoc;
-          if (needsScores) {
-            if (!needsScores4Collapsing) {
-              score = scorer.score();
-            }
-            nullScore = score;
-          }
-        }
-      } else if (this.nullPolicy == NullPolicy.EXPAND.getCode()) {
-        this.collapsedSet.set(globalDoc);
-        if (needsScores) {
-          if (!needsScores4Collapsing) {
-            score = scorer.score();
-          }
-          nullScores.add(score);
-        }
+    public void collect(int contextDoc) throws IOException {
+      if (segmentValues.advanceExact(contextDoc)) {
+        int ord = segmentValues.ordValue();
+        collectDocWithGroup(contextDoc, ord);
+      } else {
+        collectDocWithNullGroup(contextDoc);
       }
     }
   }
 
-  /*
-   * Strategy for collapsing on a 32 bit numeric field and using the first document according
-   * to a complex sort as the group head
+  /**
+   * A block based score collector that uses a field's numeric value as the group ids
+   *
+   * @lucene.internal
    */
-  private static class IntSortSpecStrategy extends IntFieldValueStrategy {
-
-    private final SortFieldsCompare compareState;
-    private final SortSpec sortSpec;
-    private final Sort sort;
+  static class BlockIntSortSpecCollector extends AbstractBlockSortSpecCollector {
+    private NumericDocValues segmentValues;
 
-    private int index = -1;
-    private boolean needsScores4Collapsing;
-
-    public IntSortSpecStrategy(
-        int maxDoc,
-        int size,
-        String collapseField,
-        int nullPolicy,
-        GroupHeadSelector groupHeadSelector,
-        boolean needsScores4Collapsing,
-        boolean needsScores,
-        BoostedDocsCollector boostedDocsCollector,
-        SortSpec sortSpec,
-        IndexSearcher searcher)
+    public BlockIntSortSpecCollector(
+        final String collapseField,
+        final NullPolicy nullPolicy,
+        final IntIntHashMap boostDocsMap,
+        final Sort sort)
         throws IOException {
-
-      super(maxDoc, size, collapseField, nullPolicy, needsScores, boostedDocsCollector);
-      this.needsScores4Collapsing = needsScores4Collapsing;
-
-      assert GroupHeadSelectorType.SORT.equals(groupHeadSelector.type);
-
-      this.sortSpec = sortSpec;
-      this.sort = rewriteSort(sortSpec, searcher);
-      this.compareState = new SortFieldsCompare(sort.getSort(), size);
-    }
-
-    @Override
-    public void setNextReader(LeafReaderContext context) throws IOException {
-      compareState.setNextReader(context);
+      super(collapseField, nullPolicy, boostDocsMap, sort);
     }
 
     @Override
-    public void setScorer(Scorable s) throws IOException {
-      super.setScorer(s);
-      this.compareState.setScorer(s);
-    }
-
-    private float computeScoreIfNeeded4Collapse() throws IOException {
-      return needsScores4Collapsing ? scorer.score() : 0F;
+    protected void doSetNextReader(LeafReaderContext context) throws IOException {
+      super.doSetNextReader(context);
+      this.segmentValues = DocValues.getNumeric(context.reader(), collapseField);
     }
 
     @Override
-    public void collapse(int collapseKey, int contextDoc, int globalDoc) throws IOException {
-      float score = computeScoreIfNeeded4Collapse();
-
-      final int idx;
-      if ((idx = cmap.indexOf(collapseKey)) >= 0) {
-        // we've seen this collapseKey before, test to see if it's a new group leader
-        int pointer = cmap.indexGet(idx);
-        if (compareState.testAndSetGroupValues(pointer, contextDoc)) {
-          docs.put(pointer, globalDoc);
-          if (needsScores) {
-            if (!needsScores4Collapsing) {
-              score = scorer.score();
-            }
-            scores.put(pointer, score);
-          }
-        }
+    public void collect(int contextDoc) throws IOException {
+      if (segmentValues.advanceExact(contextDoc)) {
+        int group = (int) segmentValues.longValue();
+        collectDocWithGroup(contextDoc, group);
       } else {
-        // we've never seen this collapseKey before, treat it as group head for now
-        ++index;
-        cmap.put(collapseKey, index);
-        docs.put(index, globalDoc);
-        compareState.setGroupValues(index, contextDoc);
-        if (needsScores) {
-          if (!needsScores4Collapsing) {
-            score = scorer.score();
-          }
-          scores.put(index, score);
-        }
+        collectDocWithNullGroup(contextDoc);
       }
     }
+  }
 
-    @Override
-    public void collapseNullGroup(int contextDoc, int globalDoc) throws IOException {
-      assert NullPolicy.IGNORE.getCode() != this.nullPolicy;
+  public static final class CollapseScore {
+    /**
+     * Inspects the GroupHeadSelector to determine if this CollapseScore is needed. If it is, then
+     * "this" will be added to the readerContext using the "CSCORE" key, and true will be returned.
+     * If not returns false.
+     */
+    public boolean setupIfNeeded(
+        final GroupHeadSelector groupHeadSelector,
+        final Map<? super String, ? super CollapseScore> readerContext) {
+      // HACK, but not really any better options until/unless we can recursively
+      // ask value sources if they depend on score
+      if (wantsCScore(groupHeadSelector.selectorText)) {
+        readerContext.put("CSCORE", this);
+        return true;
+      }
+      return false;
+    }
 
-      float score = computeScoreIfNeeded4Collapse();
+    /**
+     * Huge HACK, but not really any better options until/unless we can recursively ask value
+     * sources if they depend on score
+     */
+    public static boolean wantsCScore(final String text) {
+      return (text.contains("cscore()"));
+    }
 
-      if (this.nullPolicy == NullPolicy.COLLAPSE.getCode()) {
-        if (-1 == nullDoc) {
-          // we've never seen a doc with null collapse key yet, treat it as the null group head for
-          // now
-          compareState.setNullGroupValues(contextDoc);
-          nullDoc = globalDoc;
-          if (needsScores) {
-            if (!needsScores4Collapsing) {
-              score = scorer.score();
-            }
-            nullScore = score;
-          }
-        } else {
-          // test this doc to see if it's the new null leader
-          if (compareState.testAndSetNullGroupValues(contextDoc)) {
-            nullDoc = globalDoc;
-            if (needsScores) {
-              if (!needsScores4Collapsing) {
-                score = scorer.score();
-              }
-              nullScore = score;
-            }
-          }
-        }
-      } else if (this.nullPolicy == NullPolicy.EXPAND.getCode()) {
-        this.collapsedSet.set(globalDoc);
-        if (needsScores) {
-          if (!needsScores4Collapsing) {
-            score = scorer.score();
-          }
-          nullScores.add(score);
-        }
-      }
+    private CollapseScore() {
+      // No-Op
     }
+
+    public float score;
   }
 
   /**
@@ -3355,14 +2796,13 @@ public class CollapsingQParserPlugin extends QParserPlugin {
    *
    * <p>NOTE: collect methods must be called in increasing globalDoc order
    */
-  private static class BoostedDocsCollector {
-    private final IntIntHashMap boostDocsMap;
+  protected static class BoostedDocsCollector {
     private final int[] sortedGlobalDocIds;
     private final boolean hasBoosts;
 
     private final IntArrayList boostedKeys = new IntArrayList();
     private final IntArrayList boostedDocs = new IntArrayList();
-    ;
+
     private boolean boostedNullGroup = false;
     private final MergeBoost boostedDocsIdsIter;
 
@@ -3382,17 +2822,10 @@ public class CollapsingQParserPlugin extends QParserPlugin {
         public boolean collectInNullGroupIfBoosted(int globalDoc) {
           return false;
         }
-
-        @Override
-        public void purgeGroupsThatHaveBoostedDocs(
-            final FixedBitSet collapsedSet,
-            final IntProcedure removeGroupKey,
-            final Runnable resetNullGroupHead) {}
       };
     }
 
     private BoostedDocsCollector(final IntIntHashMap boostDocsMap) {
-      this.boostDocsMap = boostDocsMap;
       this.hasBoosts = !boostDocsMap.isEmpty();
       sortedGlobalDocIds = new int[boostDocsMap.size()];
       Iterator<IntIntCursor> it = boostDocsMap.iterator();
@@ -3440,37 +2873,29 @@ public class CollapsingQParserPlugin extends QParserPlugin {
       return false;
     }
 
+    // REMAINING METHODS ARE USED IN COMPLETE() TO CONSUME
+
+    /** Add all collected boosted docs to the collapsed set. */
+    public void addBoostedDocsTo(DocIdSetBuilder collapsedSet) {
+      DocIdSetBuilder.BulkAdder adder = collapsedSet.grow(boostedDocs.size());
+      boostedDocs.forEach((IntProcedure) adder::add);
+    }
+
+    /** Visit group keys that have boosted docs */
+    public void visitBoostedGroupKeys(IntProcedure procedure) {
+      boostedKeys.forEach(procedure);
+    }
+
     /**
-     * Kludgy API neccessary to deal with diff collectors/strategies using diff data structs for
-     * tracking collapse keys...
+     * Whether a boosted doc was collected in the null group. If true, the null group head should be
+     * reset so the boosted doc takes precedence.
      */
-    public void purgeGroupsThatHaveBoostedDocs(
-        final FixedBitSet collapsedSet,
-        final IntProcedure removeGroupKey,
-        final Runnable resetNullGroupHead) {
-      // Add the (collected) boosted docs to the collapsedSet
-      boostedDocs.forEach(
-          new IntProcedure() {
-            @Override
-            public void apply(int globalDoc) {
-              collapsedSet.set(globalDoc);
-            }
-          });
-      // Remove any group heads that are in the same groups as (collected) boosted documents.
-      boostedKeys.forEach(removeGroupKey);
-      if (boostedNullGroup) {
-        // If we're using IGNORE then no (matching) null docs were collected (by caller)
-        // If we're using EXPAND then all (matching) null docs were already collected (by us)
-        //   ...and that's *good* because each is treated like it's own group, our boosts don't
-        // matter
-        // We only have to worry about removing null docs when using COLLAPSE, in which case any
-        // boosted null doc means we clear the group head of the null group..
-        resetNullGroupHead.run();
-      }
+    public boolean isBoostedNullGroup() {
+      return boostedNullGroup;
     }
   }
 
-  static class MergeBoost {
+  protected static class MergeBoost {
 
     private int[] boostDocs;
     private int index = 0;
diff --git a/solr/core/src/java/org/apache/solr/util/DynamicMap.java b/solr/core/src/java/org/apache/solr/util/DynamicMap.java
index eac7c3f6d20..a3eb135ce6a 100644
--- a/solr/core/src/java/org/apache/solr/util/DynamicMap.java
+++ b/solr/core/src/java/org/apache/solr/util/DynamicMap.java
@@ -51,4 +51,7 @@ public interface DynamicMap {
     // +2 let's us not to worry about which comparison operator to choose
     return threshold(expectedKeyMax) + 2;
   }
+
+  /** The number of entries in this map. */
+  int size();
 }
diff --git a/solr/core/src/java/org/apache/solr/util/IntFloatDynamicMap.java b/solr/core/src/java/org/apache/solr/util/IntFloatDynamicMap.java
index 07b2d98dde8..3f9318b677f 100644
--- a/solr/core/src/java/org/apache/solr/util/IntFloatDynamicMap.java
+++ b/solr/core/src/java/org/apache/solr/util/IntFloatDynamicMap.java
@@ -29,6 +29,7 @@ public class IntFloatDynamicMap implements DynamicMap {
   private float[] keyValues;
   private float emptyValue;
   private int threshold;
+  private int keyValuesSize;
 
   /**
    * Create map with expected max value of key. Although the map will automatically do resizing to
@@ -52,6 +53,7 @@ public class IntFloatDynamicMap implements DynamicMap {
       Arrays.fill(keyValues, emptyValue);
     }
     if (hashMap != null) {
+      keyValuesSize = hashMap.size();
       hashMap.forEach((IntFloatProcedure) (key, value) -> keyValues[key] = value);
       hashMap = null;
     }
@@ -73,7 +75,12 @@ public class IntFloatDynamicMap implements DynamicMap {
       if (key >= keyValues.length) {
         growBuffer(key + 1);
       }
-      keyValues[key] = value;
+      if (keyValues[key] != value) {
+        if (keyValues[key] == emptyValue) {
+          keyValuesSize++;
+        }
+        keyValues[key] = value;
+      }
     } else {
       this.hashMap.put(key, value);
       this.maxSize = Math.max(key + 1, maxSize);
@@ -108,9 +115,17 @@ public class IntFloatDynamicMap implements DynamicMap {
 
   public void remove(int key) {
     if (keyValues != null) {
-      if (key < keyValues.length) keyValues[key] = emptyValue;
+      if (key < keyValues.length && keyValues[key] != emptyValue) {
+        keyValues[key] = emptyValue;
+        keyValuesSize--;
+      }
     } else {
       hashMap.remove(key);
     }
   }
+
+  @Override
+  public int size() {
+    return keyValues != null ? keyValuesSize : hashMap.size();
+  }
 }
diff --git a/solr/core/src/java/org/apache/solr/util/IntIntDynamicMap.java b/solr/core/src/java/org/apache/solr/util/IntIntDynamicMap.java
index aa498f39b18..09d384869e1 100644
--- a/solr/core/src/java/org/apache/solr/util/IntIntDynamicMap.java
+++ b/solr/core/src/java/org/apache/solr/util/IntIntDynamicMap.java
@@ -30,6 +30,7 @@ public class IntIntDynamicMap implements DynamicMap {
   private int[] keyValues;
   private int emptyValue;
   private int threshold;
+  private int keyValuesSize;
 
   /**
    * Create map with expected max value of key. Although the map will automatically do resizing to
@@ -53,6 +54,7 @@ public class IntIntDynamicMap implements DynamicMap {
       Arrays.fill(keyValues, emptyValue);
     }
     if (hashMap != null) {
+      keyValuesSize = hashMap.size();
       hashMap.forEach((IntIntProcedure) (key, value) -> keyValues[key] = value);
       hashMap = null;
     }
@@ -74,7 +76,12 @@ public class IntIntDynamicMap implements DynamicMap {
       if (key >= keyValues.length) {
         growBuffer(key + 1);
       }
-      keyValues[key] = value;
+      if (keyValues[key] != value) {
+        if (keyValues[key] == emptyValue) {
+          keyValuesSize++;
+        }
+        keyValues[key] = value;
+      }
     } else {
       this.maxSize = Math.max(key + 1, maxSize);
       this.hashMap.put(key, value);
@@ -109,9 +116,17 @@ public class IntIntDynamicMap implements DynamicMap {
 
   public void remove(int key) {
     if (keyValues != null) {
-      if (key < keyValues.length) keyValues[key] = emptyValue;
+      if (key < keyValues.length && keyValues[key] != emptyValue) {
+        keyValues[key] = emptyValue;
+        keyValuesSize--;
+      }
     } else {
       hashMap.remove(key);
     }
   }
+
+  @Override
+  public int size() {
+    return keyValues != null ? keyValuesSize : hashMap.size();
+  }
 }
diff --git a/solr/core/src/java/org/apache/solr/util/IntLongDynamicMap.java b/solr/core/src/java/org/apache/solr/util/IntLongDynamicMap.java
index f9fcbabe333..141e091f61c 100644
--- a/solr/core/src/java/org/apache/solr/util/IntLongDynamicMap.java
+++ b/solr/core/src/java/org/apache/solr/util/IntLongDynamicMap.java
@@ -30,6 +30,7 @@ public class IntLongDynamicMap implements DynamicMap {
   private long[] keyValues;
   private long emptyValue;
   private int threshold;
+  private int keyValuesSize;
 
   /**
    * Create map with expected max value of key. Although the map will automatically do resizing to
@@ -53,6 +54,7 @@ public class IntLongDynamicMap implements DynamicMap {
       Arrays.fill(keyValues, emptyValue);
     }
     if (hashMap != null) {
+      keyValuesSize = hashMap.size();
       hashMap.forEach((IntLongProcedure) (key, value) -> keyValues[key] = value);
       hashMap = null;
     }
@@ -74,7 +76,12 @@ public class IntLongDynamicMap implements DynamicMap {
       if (key >= keyValues.length) {
         growBuffer(key + 1);
       }
-      keyValues[key] = value;
+      if (keyValues[key] != value) {
+        if (keyValues[key] == emptyValue) {
+          keyValuesSize++;
+        }
+        keyValues[key] = value;
+      }
     } else {
       this.maxSize = Math.max(key + 1, maxSize);
       this.hashMap.put(key, value);
@@ -109,9 +116,17 @@ public class IntLongDynamicMap implements DynamicMap {
 
   public void remove(int key) {
     if (keyValues != null) {
-      if (key < keyValues.length) keyValues[key] = emptyValue;
+      if (key < keyValues.length && keyValues[key] != emptyValue) {
+        keyValues[key] = emptyValue;
+        keyValuesSize--;
+      }
     } else {
       hashMap.remove(key);
     }
   }
+
+  @Override
+  public int size() {
+    return keyValues != null ? keyValuesSize : hashMap.size();
+  }
 }
diff --git a/solr/core/src/test/org/apache/solr/search/TestCollapseQParserPlugin.java b/solr/core/src/test/org/apache/solr/search/TestCollapseQParserPlugin.java
index 7c193f87a73..5b674fd4cc7 100644
--- a/solr/core/src/test/org/apache/solr/search/TestCollapseQParserPlugin.java
+++ b/solr/core/src/test/org/apache/solr/search/TestCollapseQParserPlugin.java
@@ -1124,23 +1124,23 @@ public class TestCollapseQParserPlugin extends SolrTestCaseJ4 {
         () -> GroupHeadSelector.build(params("sort", "foo_s asc", "min", "bar_s")));
 
     s = GroupHeadSelector.build(params("min", "foo_s"));
-    assertEquals(GroupHeadSelectorType.MIN, s.type);
-    assertEquals("foo_s", s.selectorText);
+    assertEquals(GroupHeadSelectorType.MIN, s.type());
+    assertEquals("foo_s", s.selectorText());
 
     s = GroupHeadSelector.build(params("max", "foo_s"));
-    assertEquals(GroupHeadSelectorType.MAX, s.type);
-    assertEquals("foo_s", s.selectorText);
+    assertEquals(GroupHeadSelectorType.MAX, s.type());
+    assertEquals("foo_s", s.selectorText());
     assertNotEquals(s, GroupHeadSelector.build(params("min", "foo_s", "other", "stuff")));
 
     s = GroupHeadSelector.build(params());
-    assertEquals(GroupHeadSelectorType.SCORE, s.type);
-    assertNotNull(s.selectorText);
+    assertEquals(GroupHeadSelectorType.SCORE, s.type());
+    assertNotNull(s.selectorText());
     assertEquals(GroupHeadSelector.build(params()), s);
     assertNotEquals(s, GroupHeadSelector.build(params("min", "BAR_s")));
 
     s = GroupHeadSelector.build(params("sort", "foo_s asc"));
-    assertEquals(GroupHeadSelectorType.SORT, s.type);
-    assertEquals("foo_s asc", s.selectorText);
+    assertEquals(GroupHeadSelectorType.SORT, s.type());
+    assertEquals("foo_s asc", s.selectorText());
     assertEquals(GroupHeadSelector.build(params("sort", "foo_s asc")), s);
     assertNotEquals(s, GroupHeadSelector.build(params("sort", "BAR_s asc")));
     assertNotEquals(s, GroupHeadSelector.build(params("min", "BAR_s")));
diff --git a/solr/core/src/test/org/apache/solr/search/TestRandomCollapseQParserPlugin.java b/solr/core/src/test/org/apache/solr/search/TestRandomCollapseQParserPlugin.java
index ad4d7ac5b22..ead637f7561 100644
--- a/solr/core/src/test/org/apache/solr/search/TestRandomCollapseQParserPlugin.java
+++ b/solr/core/src/test/org/apache/solr/search/TestRandomCollapseQParserPlugin.java
@@ -267,10 +267,9 @@ public class TestRandomCollapseQParserPlugin extends SolrTestCaseJ4 {
         "CollapsingPostFilter(CollapsingPostFilter(field=id, "
             + "nullPolicy="
             + nullPolicy
-            + ", GroupHeadSelector(selectorText="
+            + ", GroupHeadSelector[type=SORT, selectorText="
             + groupHeadSort.substring(1, groupHeadSort.length() - 1)
-            + ", type=SORT"
-            + "), hint="
+            + "], hint="
             + collapseHint
             + ", size="
             + collapseSize
diff --git a/solr/solr-ref-guide/modules/query-guide/pages/collapse-and-expand-results.adoc b/solr/solr-ref-guide/modules/query-guide/pages/collapse-and-expand-results.adoc
index a2e493cacfa..f611e60543b 100644
--- a/solr/solr-ref-guide/modules/query-guide/pages/collapse-and-expand-results.adoc
+++ b/solr/solr-ref-guide/modules/query-guide/pages/collapse-and-expand-results.adoc
@@ -18,25 +18,24 @@
 
 The Collapsing query parser and the Expand component combine to form an approach to grouping documents for field collapsing in search results.
 
-The Collapsing query parser groups documents (collapsing the result set) according to your parameters, while the Expand component provides access to documents in the collapsed group for use in results display or other processing by a client application.
+The Collapsing query parser groups documents (collapsing the result set) according to your parameters, while the Expand component provides access to other documents in the collapsed group for use in results display or other processing by a client application.
 Collapse & Expand can together do what the older xref:result-grouping.adoc[] (`group=true`) does for _most_ use-cases but not all.
 Collapse and Expand are not supported when Result Grouping is enabled.
 Generally, you should prefer Collapse & Expand.
 
 [IMPORTANT]
 ====
-In order to use these features with SolrCloud, the documents must be located on the same shard.
-To ensure document co-location, you can define the `router.name` parameter as `compositeId` when creating the collection.
-For more information on this option, see the section xref:deployment-guide:solrcloud-shards-indexing.adoc#document-routing[Document Routing].
+Collapsing happens on each core/shard, not in a distributed sense.
+Consequently, it's typically necessary to co-locate documents by collapsibility somehow.  See xref:deployment-guide:solrcloud-shards-indexing.adoc#document-routing[Document Routing].
+Result Grouping doesn't have this limitation.
 ====
 
 == Collapsing Query Parser
 
-The `CollapsingQParser` is really a _post filter_ that provides more performant field collapsing than Solr's standard approach when the number of distinct groups in the result set is high.
-This parser collapses the result set to a single document per group before it forwards the result set to the rest of the search components.
-So all downstream components (faceting, highlighting, etc.) will work with the collapsed result set.
-
-The CollapsingQParserPlugin fully supports the QueryElevationComponent.
+The `CollapsingQParser` produces a special type of query called a "post filter" that operates on the result set following the `q` and `fq` queries.
+Given a configured group field that matches multiple documents, it will "collapse" a group to just one of those documents.
+Other Solr components (faceting, highlighting, query elevation, etc.) are downstream of this, and thus will work with only the collapsed result set.
+Unlike Result Grouping, Solr's response structure is completely normal, showing no indication of the collapsing behavior.
 
 === Collapsing Query Parser Options
 


(solr) 06/13: SOLR-18313: drop the changelog entry (#4682)

Posted by ds...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

dsmiley pushed a commit to branch branch_10x
in repository https://gitbox.apache.org/repos/asf/solr.git

commit 1864907dd5ee184e0227e424d78e4ef3166deaef
Author: Serhiy Bzhezytskyy <me...@serhiy-bzhezytskyy.com>
AuthorDate: Thu Jul 30 15:46:35 2026 +0300

    SOLR-18313: drop the changelog entry (#4682)
    
    (cherry picked from commit 66d2a8971b8ea70bdda84f5319bc5746604c3ff4)
---
 changelog/unreleased/SOLR-18313-prep-for-lucene-11.yml | 10 ----------
 1 file changed, 10 deletions(-)

diff --git a/changelog/unreleased/SOLR-18313-prep-for-lucene-11.yml b/changelog/unreleased/SOLR-18313-prep-for-lucene-11.yml
deleted file mode 100644
index 2ce54549879..00000000000
--- a/changelog/unreleased/SOLR-18313-prep-for-lucene-11.yml
+++ /dev/null
@@ -1,10 +0,0 @@
-# See https://github.com/apache/solr/blob/main/dev-docs/changelog.adoc
-title: >
-  Prep for Lucene 11: switch two internal call sites (sort missing-value handling and automaton
-  concatenation) to the newer Lucene API forms that already exist in Lucene 10.4. No behavior change.
-type: changed
-authors:
-  - name: Serhiy Bzhezytskyy
-links:
-  - name: SOLR-18313
-    url: https://issues.apache.org/jira/browse/SOLR-18313


(solr) 12/13: Simplify SolrRequest path usage: prefer ctor not setPath (#4689)

Posted by ds...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

dsmiley pushed a commit to branch branch_10x
in repository https://gitbox.apache.org/repos/asf/solr.git

commit 9ad63cc534c8befd4290278636e3c6ef4cb751f8
Author: David Smiley <ds...@apache.org>
AuthorDate: Sat Aug 1 12:59:41 2026 -0400

    Simplify SolrRequest path usage: prefer ctor not setPath (#4689)
    
    (mostly tests)
    Also switched some inappropriate usages of QueryRequest to GenericSolrRequest.
    
    (cherry picked from commit b47aacaec82be9bef6e97643503dff45122321ba)
---
 .../apache/solr/cloud/BasicDistributedZkTest.java  |  7 +++++--
 .../apache/solr/cloud/MultiThreadedOCPTest.java    |  8 +++++---
 .../org/apache/solr/cloud/SSLMigrationTest.java    |  8 +++++---
 .../TestCloudPhrasesIdentificationComponent.java   |  6 ++----
 .../solr/cloud/TestGracefulJettyShutdown.java      |  3 +--
 .../solr/cloud/api/collections/ShardSplitTest.java |  8 +++++---
 .../TestRequestStatusCollectionAPI.java            |  8 +++++---
 .../solr/response/TestErrorResponseStackTrace.java |  4 ++--
 .../apache/solr/schema/TestCloudManagedSchema.java |  7 ++++---
 .../org/apache/solr/search/TestSmileRequest.java   |  4 ----
 .../apache/solr/update/UuidAtomicUpdateTest.java   |  3 +--
 .../update/processor/AtomicUpdateJavabinTest.java  |  3 +--
 .../solr/ltr/TestLTRReRankCutoffOnSolrCloud.java   |  9 +++------
 .../TermComponentRefGuideExamplesTest.java         |  3 +--
 .../client/solrj/io/stream/JSONTupleStream.java    | 11 +----------
 .../solr/client/solrj/io/stream/SolrStream.java    | 23 ++++------------------
 .../client/solrj/io/graph/GraphExpressionTest.java |  3 +--
 .../solr/client/solrj/request/UpdateRequest.java   |  7 +++----
 .../apache/solr/client/solrj/SolrExampleTests.java |  3 +--
 .../solr/client/solrj/request/TestCoreAdmin.java   |  6 ++++--
 .../src/java/org/apache/solr/SolrTestCaseHS.java   |  5 -----
 .../solr/cloud/AbstractFullDistribZkTestBase.java  |  1 -
 22 files changed, 54 insertions(+), 86 deletions(-)

diff --git a/solr/core/src/test/org/apache/solr/cloud/BasicDistributedZkTest.java b/solr/core/src/test/org/apache/solr/cloud/BasicDistributedZkTest.java
index 16031370fc3..b82625c6202 100644
--- a/solr/core/src/test/org/apache/solr/cloud/BasicDistributedZkTest.java
+++ b/solr/core/src/test/org/apache/solr/cloud/BasicDistributedZkTest.java
@@ -43,12 +43,15 @@ import org.apache.lucene.util.IOUtils;
 import org.apache.solr.JSONTestUtil;
 import org.apache.solr.SolrTestCaseJ4.SuppressSSL;
 import org.apache.solr.client.solrj.SolrClient;
+import org.apache.solr.client.solrj.SolrRequest.METHOD;
+import org.apache.solr.client.solrj.SolrRequest.SolrRequestType;
 import org.apache.solr.client.solrj.SolrServerException;
 import org.apache.solr.client.solrj.impl.HttpSolrClient;
 import org.apache.solr.client.solrj.request.AbstractUpdateRequest;
 import org.apache.solr.client.solrj.request.CollectionAdminRequest;
 import org.apache.solr.client.solrj.request.CoreAdminRequest.Create;
 import org.apache.solr.client.solrj.request.CoreAdminRequest.Unload;
+import org.apache.solr.client.solrj.request.GenericSolrRequest;
 import org.apache.solr.client.solrj.request.MetricsRequest;
 import org.apache.solr.client.solrj.request.QueryRequest;
 import org.apache.solr.client.solrj.request.SolrQuery;
@@ -1143,8 +1146,8 @@ public class BasicDistributedZkTest extends AbstractFullDistribZkTestBase {
     }
     params.set("name", collectionName);
     params.set("collection.configName", configSetName);
-    QueryRequest request = new QueryRequest(params);
-    request.setPath("/admin/collections");
+    var request =
+        new GenericSolrRequest(METHOD.POST, "/admin/collections", SolrRequestType.ADMIN, params);
 
     CollectionAdminResponse res = new CollectionAdminResponse();
     if (client == null) {
diff --git a/solr/core/src/test/org/apache/solr/cloud/MultiThreadedOCPTest.java b/solr/core/src/test/org/apache/solr/cloud/MultiThreadedOCPTest.java
index 37a26488c2d..2ce7dec37aa 100644
--- a/solr/core/src/test/org/apache/solr/cloud/MultiThreadedOCPTest.java
+++ b/solr/core/src/test/org/apache/solr/cloud/MultiThreadedOCPTest.java
@@ -23,11 +23,13 @@ import java.lang.invoke.MethodHandles;
 import java.util.Random;
 import org.apache.solr.client.solrj.RemoteSolrException;
 import org.apache.solr.client.solrj.SolrClient;
+import org.apache.solr.client.solrj.SolrRequest.METHOD;
+import org.apache.solr.client.solrj.SolrRequest.SolrRequestType;
 import org.apache.solr.client.solrj.SolrServerException;
 import org.apache.solr.client.solrj.request.CollectionAdminRequest;
 import org.apache.solr.client.solrj.request.CollectionAdminRequest.Create;
 import org.apache.solr.client.solrj.request.CollectionAdminRequest.SplitShard;
-import org.apache.solr.client.solrj.request.QueryRequest;
+import org.apache.solr.client.solrj.request.GenericSolrRequest;
 import org.apache.solr.client.solrj.response.RequestStatusState;
 import org.apache.solr.common.params.CollectionParams;
 import org.apache.solr.common.params.ModifiableSolrParams;
@@ -322,8 +324,8 @@ public class MultiThreadedOCPTest extends AbstractFullDistribZkTestBase {
       ModifiableSolrParams params = new ModifiableSolrParams();
       params.set("action", CollectionParams.CollectionAction.CLUSTERSTATUS.toString());
       params.set("collection", "collection1");
-      QueryRequest request = new QueryRequest(params);
-      request.setPath("/admin/collections");
+      var request =
+          new GenericSolrRequest(METHOD.GET, "/admin/collections", SolrRequestType.ADMIN, params);
 
       client.request(request);
 
diff --git a/solr/core/src/test/org/apache/solr/cloud/SSLMigrationTest.java b/solr/core/src/test/org/apache/solr/cloud/SSLMigrationTest.java
index b0e329f0836..c168cceae47 100644
--- a/solr/core/src/test/org/apache/solr/cloud/SSLMigrationTest.java
+++ b/solr/core/src/test/org/apache/solr/cloud/SSLMigrationTest.java
@@ -23,9 +23,11 @@ import java.util.Map;
 import java.util.Properties;
 import org.apache.lucene.tests.util.LuceneTestCase.AwaitsFix;
 import org.apache.solr.SolrTestCaseJ4.SuppressSSL;
+import org.apache.solr.client.solrj.SolrRequest.METHOD;
+import org.apache.solr.client.solrj.SolrRequest.SolrRequestType;
 import org.apache.solr.client.solrj.impl.LBSolrClient;
 import org.apache.solr.client.solrj.jetty.LBJettySolrClient;
-import org.apache.solr.client.solrj.request.QueryRequest;
+import org.apache.solr.client.solrj.request.GenericSolrRequest;
 import org.apache.solr.common.cloud.DocCollection;
 import org.apache.solr.common.cloud.Replica;
 import org.apache.solr.common.cloud.Slice;
@@ -116,8 +118,8 @@ public class SSLMigrationTest extends AbstractFullDistribZkTestBase {
             "val",
             value);
     SolrParams params = new MapSolrParams(m);
-    QueryRequest request = new QueryRequest(params);
-    request.setPath("/admin/collections");
+    var request =
+        new GenericSolrRequest(METHOD.POST, "/admin/collections", SolrRequestType.ADMIN, params);
 
     LBSolrClient.Endpoint[] urls =
         getReplicas().stream()
diff --git a/solr/core/src/test/org/apache/solr/cloud/TestCloudPhrasesIdentificationComponent.java b/solr/core/src/test/org/apache/solr/cloud/TestCloudPhrasesIdentificationComponent.java
index 1bd20b5db22..2a979299698 100644
--- a/solr/core/src/test/org/apache/solr/cloud/TestCloudPhrasesIdentificationComponent.java
+++ b/solr/core/src/test/org/apache/solr/cloud/TestCloudPhrasesIdentificationComponent.java
@@ -133,8 +133,7 @@ public class TestCloudPhrasesIdentificationComponent extends SolrCloudTestCase {
               params("q", input, "phrases", "true"),
               params("q", "*:*", "phrases.q", input, "phrases", "true"),
               params("q", "-*:*", "phrases.q", input, "phrases", "true"))) {
-        final QueryRequest req = new QueryRequest(p);
-        req.setPath(path);
+        final QueryRequest req = new QueryRequest(path, p);
         final QueryResponse rsp = req.process(getRandClient(random()));
         try {
           @SuppressWarnings({"unchecked"})
@@ -169,8 +168,7 @@ public class TestCloudPhrasesIdentificationComponent extends SolrCloudTestCase {
           Arrays.asList(
               params("q", "*:*", "phrases.q", input, "phrases", "true"),
               params("q", "-*:*", "phrases.q", input, "phrases", "true"))) {
-        final QueryRequest req = new QueryRequest(p);
-        req.setPath("/phrases");
+        final QueryRequest req = new QueryRequest("/phrases", p);
         final QueryResponse rsp = req.process(getRandClient(random()));
         try {
           @SuppressWarnings({"unchecked"})
diff --git a/solr/core/src/test/org/apache/solr/cloud/TestGracefulJettyShutdown.java b/solr/core/src/test/org/apache/solr/cloud/TestGracefulJettyShutdown.java
index 8c0689585d2..c0cc72fb206 100644
--- a/solr/core/src/test/org/apache/solr/cloud/TestGracefulJettyShutdown.java
+++ b/solr/core/src/test/org/apache/solr/cloud/TestGracefulJettyShutdown.java
@@ -85,8 +85,7 @@ public class TestGracefulJettyShutdown extends SolrTestCaseJ4 {
       final List<Future<QueryResponse>> results = new ArrayList<>(13);
 
       try (SolrClient jettyClient = nodeToStop.newClient()) {
-        final QueryRequest req = new QueryRequest(params("q", "foo_s:aaa"));
-        req.setPath(handler);
+        final QueryRequest req = new QueryRequest(handler, params("q", "foo_s:aaa"));
 
         // check inflight requests using both clients...
         for (SolrClient client : Arrays.asList(cloudClient, jettyClient)) {
diff --git a/solr/core/src/test/org/apache/solr/cloud/api/collections/ShardSplitTest.java b/solr/core/src/test/org/apache/solr/cloud/api/collections/ShardSplitTest.java
index 9b7053adda5..c55843dab9d 100644
--- a/solr/core/src/test/org/apache/solr/cloud/api/collections/ShardSplitTest.java
+++ b/solr/core/src/test/org/apache/solr/cloud/api/collections/ShardSplitTest.java
@@ -39,10 +39,12 @@ import java.util.concurrent.atomic.AtomicInteger;
 import java.util.concurrent.atomic.AtomicReference;
 import org.apache.solr.client.solrj.RemoteSolrException;
 import org.apache.solr.client.solrj.SolrClient;
+import org.apache.solr.client.solrj.SolrRequest.METHOD;
+import org.apache.solr.client.solrj.SolrRequest.SolrRequestType;
 import org.apache.solr.client.solrj.SolrServerException;
 import org.apache.solr.client.solrj.impl.CloudSolrClient;
 import org.apache.solr.client.solrj.request.CollectionAdminRequest;
-import org.apache.solr.client.solrj.request.QueryRequest;
+import org.apache.solr.client.solrj.request.GenericSolrRequest;
 import org.apache.solr.client.solrj.request.SolrQuery;
 import org.apache.solr.client.solrj.response.CollectionAdminResponse;
 import org.apache.solr.client.solrj.response.QueryResponse;
@@ -1269,8 +1271,8 @@ public class ShardSplitTest extends BasicDistributedZkTest {
     if (splitKey != null) {
       params.set("split.key", splitKey);
     }
-    QueryRequest request = new QueryRequest(params);
-    request.setPath("/admin/collections");
+    var request =
+        new GenericSolrRequest(METHOD.POST, "/admin/collections", SolrRequestType.ADMIN, params);
 
     JettySolrRunner jetty = shardToJetty.get(SHARD1).getFirst().jetty;
     try (SolrClient baseServer = jetty.newClient(30_000, 300_000)) {
diff --git a/solr/core/src/test/org/apache/solr/cloud/api/collections/TestRequestStatusCollectionAPI.java b/solr/core/src/test/org/apache/solr/cloud/api/collections/TestRequestStatusCollectionAPI.java
index 5f93ef71768..ba03a7c42ea 100644
--- a/solr/core/src/test/org/apache/solr/cloud/api/collections/TestRequestStatusCollectionAPI.java
+++ b/solr/core/src/test/org/apache/solr/cloud/api/collections/TestRequestStatusCollectionAPI.java
@@ -24,8 +24,10 @@ import java.util.Arrays;
 import java.util.List;
 import java.util.Map;
 import org.apache.solr.client.solrj.RemoteSolrException;
+import org.apache.solr.client.solrj.SolrRequest.METHOD;
+import org.apache.solr.client.solrj.SolrRequest.SolrRequestType;
 import org.apache.solr.client.solrj.SolrServerException;
-import org.apache.solr.client.solrj.request.QueryRequest;
+import org.apache.solr.client.solrj.request.GenericSolrRequest;
 import org.apache.solr.client.solrj.response.RequestStatusState;
 import org.apache.solr.cloud.BasicDistributedZkTest;
 import org.apache.solr.common.params.CollectionParams;
@@ -225,8 +227,8 @@ public class TestRequestStatusCollectionAPI extends BasicDistributedZkTest {
 
   protected NamedList<Object> sendRequest(ModifiableSolrParams params)
       throws SolrServerException, IOException {
-    QueryRequest request = new QueryRequest(params);
-    request.setPath("/admin/collections");
+    var request =
+        new GenericSolrRequest(METHOD.GET, "/admin/collections", SolrRequestType.ADMIN, params);
 
     return shardToJetty.get(SHARD1).getFirst().jetty.getSolrClient().request(request);
   }
diff --git a/solr/core/src/test/org/apache/solr/response/TestErrorResponseStackTrace.java b/solr/core/src/test/org/apache/solr/response/TestErrorResponseStackTrace.java
index 5271a4e502c..875bfcde1df 100644
--- a/solr/core/src/test/org/apache/solr/response/TestErrorResponseStackTrace.java
+++ b/solr/core/src/test/org/apache/solr/response/TestErrorResponseStackTrace.java
@@ -99,8 +99,8 @@ public class TestErrorResponseStackTrace extends SolrTestCaseJ4 {
   public void testRemoteSolrException() {
     var client = solrTestRule.getSolrClient("collection1");
     QueryRequest queryRequest =
-        new QueryRequest(new ModifiableSolrParams().set("q", "*:*").set("wt", "json"));
-    queryRequest.setPath("/withError");
+        new QueryRequest(
+            "/withError", new ModifiableSolrParams().set("q", "*:*").set("wt", "json"));
     RemoteSolrException exception =
         expectThrows(RemoteSolrException.class, () -> queryRequest.process(client, "collection1"));
     assertTrue(exception.getRemoteErrorObject() instanceof NamedList);
diff --git a/solr/core/src/test/org/apache/solr/schema/TestCloudManagedSchema.java b/solr/core/src/test/org/apache/solr/schema/TestCloudManagedSchema.java
index 6a584ddb165..fd98948df1d 100644
--- a/solr/core/src/test/org/apache/solr/schema/TestCloudManagedSchema.java
+++ b/solr/core/src/test/org/apache/solr/schema/TestCloudManagedSchema.java
@@ -22,7 +22,9 @@ import java.util.List;
 import java.util.Map;
 import java.util.concurrent.TimeUnit;
 import org.apache.solr.client.api.model.CoreStatusResponse;
-import org.apache.solr.client.solrj.request.QueryRequest;
+import org.apache.solr.client.solrj.SolrRequest.METHOD;
+import org.apache.solr.client.solrj.SolrRequest.SolrRequestType;
+import org.apache.solr.client.solrj.request.GenericSolrRequest;
 import org.apache.solr.client.solrj.request.json.JacksonContentWriter;
 import org.apache.solr.cloud.AbstractFullDistribZkTestBase;
 import org.apache.solr.common.cloud.SolrZkClient;
@@ -54,8 +56,7 @@ public class TestCloudManagedSchema extends AbstractFullDistribZkTestBase {
   public void test() throws Exception {
     ModifiableSolrParams params = new ModifiableSolrParams();
     params.set(CoreAdminParams.ACTION, CoreAdminParams.CoreAdminAction.STATUS.toString());
-    QueryRequest request = new QueryRequest(params);
-    request.setPath("/admin/cores");
+    var request = new GenericSolrRequest(METHOD.GET, "/admin/cores", SolrRequestType.ADMIN, params);
     int which = r.nextInt(clients.size());
 
     // use a client that does not have the /collection1 as part of the URL.
diff --git a/solr/core/src/test/org/apache/solr/search/TestSmileRequest.java b/solr/core/src/test/org/apache/solr/search/TestSmileRequest.java
index a3bb792496b..d121c46dd5e 100644
--- a/solr/core/src/test/org/apache/solr/search/TestSmileRequest.java
+++ b/solr/core/src/test/org/apache/solr/search/TestSmileRequest.java
@@ -74,10 +74,6 @@ public class TestSmileRequest extends SolrTestCaseJ4 {
               throws Exception {
             QueryRequest query = new QueryRequest(args);
             query.setResponseParser(new SmileResponseParser());
-            String path = args.get("qt");
-            if (path != null) {
-              query.setPath(path);
-            }
             NamedList<Object> rsp = client.request(query);
             @SuppressWarnings({"rawtypes"})
             Map m = rsp.asMap(5);
diff --git a/solr/core/src/test/org/apache/solr/update/UuidAtomicUpdateTest.java b/solr/core/src/test/org/apache/solr/update/UuidAtomicUpdateTest.java
index 44ed53bdc70..5db7ef75430 100644
--- a/solr/core/src/test/org/apache/solr/update/UuidAtomicUpdateTest.java
+++ b/solr/core/src/test/org/apache/solr/update/UuidAtomicUpdateTest.java
@@ -126,8 +126,7 @@ public class UuidAtomicUpdateTest extends SolrCloudTestCase {
       final ModifiableSolrParams solrParams = new ModifiableSolrParams();
       solrParams.set("id", identifyingDocId);
       solrParams.set("shards.preference", "replica.leader:" + tf);
-      QueryRequest request = new QueryRequest(solrParams);
-      request.setPath("/get");
+      QueryRequest request = new QueryRequest("/get", solrParams);
       final QueryResponse response = request.process(cluster.getSolrClient(), COLLECTION);
 
       final NamedList<Object> rawResponse = response.getResponse();
diff --git a/solr/core/src/test/org/apache/solr/update/processor/AtomicUpdateJavabinTest.java b/solr/core/src/test/org/apache/solr/update/processor/AtomicUpdateJavabinTest.java
index 363dbe14945..ad1376441a6 100644
--- a/solr/core/src/test/org/apache/solr/update/processor/AtomicUpdateJavabinTest.java
+++ b/solr/core/src/test/org/apache/solr/update/processor/AtomicUpdateJavabinTest.java
@@ -419,8 +419,7 @@ public class AtomicUpdateJavabinTest extends SolrCloudTestCase {
       String identifyingDocId, String fieldName, Object... expectedValues) throws Exception {
     final ModifiableSolrParams solrParams = new ModifiableSolrParams();
     solrParams.set("id", identifyingDocId);
-    QueryRequest request = new QueryRequest(solrParams);
-    request.setPath("/get");
+    QueryRequest request = new QueryRequest("/get", solrParams);
     final QueryResponse response = request.process(cluster.getSolrClient(), COLLECTION);
 
     final NamedList<Object> rawResponse = response.getResponse();
diff --git a/solr/modules/ltr/src/test/org/apache/solr/ltr/TestLTRReRankCutoffOnSolrCloud.java b/solr/modules/ltr/src/test/org/apache/solr/ltr/TestLTRReRankCutoffOnSolrCloud.java
index 71367bef542..4fa4ce55eba 100644
--- a/solr/modules/ltr/src/test/org/apache/solr/ltr/TestLTRReRankCutoffOnSolrCloud.java
+++ b/solr/modules/ltr/src/test/org/apache/solr/ltr/TestLTRReRankCutoffOnSolrCloud.java
@@ -46,8 +46,7 @@ public class TestLTRReRankCutoffOnSolrCloud extends AbstractLTRSolrCloudTestBase
     final SolrQuery query = newBaseRerankQuery();
     query.add("rq", "{!ltr model=powpularityS-model reRankDocs=3 echoReRankCutoff=true}");
 
-    final QueryRequest queryRequest = new QueryRequest(query);
-    queryRequest.setPath("/query");
+    final QueryRequest queryRequest = new QueryRequest("/query", query);
     final QueryResponse queryResponse =
         queryRequest.process(solrCluster.getSolrClient(), COLLECTION);
 
@@ -72,8 +71,7 @@ public class TestLTRReRankCutoffOnSolrCloud extends AbstractLTRSolrCloudTestBase
     final SolrQuery query = newBaseRerankQuery();
     query.add("rq", "{!ltr model=powpularityS-model reRankDocs=3}");
 
-    final QueryRequest queryRequest = new QueryRequest(query);
-    queryRequest.setPath("/query");
+    final QueryRequest queryRequest = new QueryRequest("/query", query);
     final QueryResponse queryResponse =
         queryRequest.process(solrCluster.getSolrClient(), COLLECTION);
     assertNull(
@@ -87,8 +85,7 @@ public class TestLTRReRankCutoffOnSolrCloud extends AbstractLTRSolrCloudTestBase
     final SolrQuery query = newBaseRerankQuery();
     query.add("rq", "{!ltr model=powpularityS-model reRankDocs=3 echoReRankCutoff=false}");
 
-    final QueryRequest queryRequest = new QueryRequest(query);
-    queryRequest.setPath("/query");
+    final QueryRequest queryRequest = new QueryRequest("/query", query);
     final QueryResponse queryResponse =
         queryRequest.process(solrCluster.getSolrClient(), COLLECTION);
     assertNull(
diff --git a/solr/solr-ref-guide/modules/query-guide/examples/TermComponentRefGuideExamplesTest.java b/solr/solr-ref-guide/modules/query-guide/examples/TermComponentRefGuideExamplesTest.java
index 1bab1a0fe33..8ce97f5a7ab 100644
--- a/solr/solr-ref-guide/modules/query-guide/examples/TermComponentRefGuideExamplesTest.java
+++ b/solr/solr-ref-guide/modules/query-guide/examples/TermComponentRefGuideExamplesTest.java
@@ -87,8 +87,7 @@ public class TermComponentRefGuideExamplesTest extends SolrCloudTestCase {
     termsQuery.addTermsField("name");
     termsQuery.setTermsMinCount(1);
 
-    final QueryRequest request = new QueryRequest(termsQuery);
-    request.setPath("/terms");
+    final QueryRequest request = new QueryRequest("/terms", termsQuery);
     final List<Term> terms =
         request
             .process(cluster.getSolrClient(), COLLECTION_NAME)
diff --git a/solr/solrj-streaming/src/java/org/apache/solr/client/solrj/io/stream/JSONTupleStream.java b/solr/solrj-streaming/src/java/org/apache/solr/client/solrj/io/stream/JSONTupleStream.java
index ae7b895498f..98f02cd274c 100644
--- a/solr/solrj-streaming/src/java/org/apache/solr/client/solrj/io/stream/JSONTupleStream.java
+++ b/solr/solrj-streaming/src/java/org/apache/solr/client/solrj/io/stream/JSONTupleStream.java
@@ -28,7 +28,6 @@ import org.apache.solr.client.solrj.SolrRequest;
 import org.apache.solr.client.solrj.SolrServerException;
 import org.apache.solr.client.solrj.request.QueryRequest;
 import org.apache.solr.client.solrj.response.InputStreamResponseParser;
-import org.apache.solr.common.params.ModifiableSolrParams;
 import org.apache.solr.common.params.SolrParams;
 import org.apache.solr.common.util.NamedList;
 import org.noggit.JSONParser;
@@ -53,16 +52,8 @@ public class JSONTupleStream implements TupleStreamParser {
   // temporary...
   public static JSONTupleStream create(SolrClient server, SolrParams requestParams)
       throws IOException, SolrServerException {
-    String p = requestParams.get("qt");
-    if (p != null) {
-      ModifiableSolrParams modifiableSolrParams = (ModifiableSolrParams) requestParams;
-      modifiableSolrParams.remove("qt");
-    }
-
-    QueryRequest query = new QueryRequest(requestParams);
-    query.setPath(p);
+    QueryRequest query = new QueryRequest(requestParams, SolrRequest.METHOD.POST);
     query.setResponseParser(new InputStreamResponseParser("json"));
-    query.setMethod(SolrRequest.METHOD.POST);
     NamedList<Object> genericResponse = server.request(query);
     InputStream stream = (InputStream) genericResponse.get(InputStreamResponseParser.STREAM_KEY);
     InputStreamReader reader = new InputStreamReader(stream, StandardCharsets.UTF_8);
diff --git a/solr/solrj-streaming/src/java/org/apache/solr/client/solrj/io/stream/SolrStream.java b/solr/solrj-streaming/src/java/org/apache/solr/client/solrj/io/stream/SolrStream.java
index 1102f4518fb..7520fe2c468 100644
--- a/solr/solrj-streaming/src/java/org/apache/solr/client/solrj/io/stream/SolrStream.java
+++ b/solr/solrj-streaming/src/java/org/apache/solr/client/solrj/io/stream/SolrStream.java
@@ -270,34 +270,19 @@ public class SolrStream extends TupleStream {
 
   private TupleStreamParser constructParser(SolrParams requestParams)
       throws IOException, SolrServerException {
-    String p = requestParams.get("qt");
-    if (p != null) {
-      ModifiableSolrParams modifiableSolrParams = (ModifiableSolrParams) requestParams;
-      modifiableSolrParams.remove("qt");
-      // performance optimization - remove extra whitespace by default when streaming
-      modifiableSolrParams.set("indent", modifiableSolrParams.get("indent", "off"));
-    }
+    // performance optimization - remove extra whitespace when streaming
+    requestParams = SolrParams.wrapDefaults(requestParams, SolrParams.of("indent", "off"));
 
+    QueryRequest query = new QueryRequest(requestParams, SolrRequest.METHOD.POST);
     String wt = requestParams.get(CommonParams.WT, "json");
-    QueryRequest query = new QueryRequest(requestParams);
-
-    // in order to reuse HttpSolrClient objects per node, we need to cache them without the core
-    // name in the URL
-    if (core != null) {
-      query.setPath("/" + core + (p != null ? p : "/select"));
-    } else {
-      query.setPath(p);
-    }
-
     query.setResponseParser(new InputStreamResponseParser(wt));
-    query.setMethod(SolrRequest.METHOD.POST);
 
     if (user != null && password != null) {
       query.setBasicAuthCredentials(user, password);
     }
 
     var client = clientCache.getHttpSolrClient(baseUrl);
-    NamedList<Object> genericResponse = client.request(query);
+    NamedList<Object> genericResponse = client.request(query, core);
     InputStream stream = (InputStream) genericResponse.get(InputStreamResponseParser.STREAM_KEY);
     // since 9.4 the updated format has a dedicated status field
     final Integer statusCode = (Integer) genericResponse.get("responseStatus");
diff --git a/solr/solrj-streaming/src/test/org/apache/solr/client/solrj/io/graph/GraphExpressionTest.java b/solr/solrj-streaming/src/test/org/apache/solr/client/solrj/io/graph/GraphExpressionTest.java
index 4dfcbf3d0d7..9aecfd9f6be 100644
--- a/solr/solrj-streaming/src/test/org/apache/solr/client/solrj/io/graph/GraphExpressionTest.java
+++ b/solr/solrj-streaming/src/test/org/apache/solr/client/solrj/io/graph/GraphExpressionTest.java
@@ -1244,8 +1244,7 @@ public class GraphExpressionTest extends SolrCloudTestCase {
             + "gather=\"to_s\"))";
 
     params.add("expr", expr);
-    QueryRequest query = new QueryRequest(params);
-    query.setPath("/collection1/graph");
+    QueryRequest query = new QueryRequest("/collection1/graph", params);
 
     query.setResponseParser(new InputStreamResponseParser("xml"));
     query.setMethod(SolrRequest.METHOD.POST);
diff --git a/solr/solrj/src/java/org/apache/solr/client/solrj/request/UpdateRequest.java b/solr/solrj/src/java/org/apache/solr/client/solrj/request/UpdateRequest.java
index 2d4e4e011d4..4eac12b652e 100644
--- a/solr/solrj/src/java/org/apache/solr/client/solrj/request/UpdateRequest.java
+++ b/solr/solrj/src/java/org/apache/solr/client/solrj/request/UpdateRequest.java
@@ -63,8 +63,8 @@ public class UpdateRequest extends AbstractUpdateRequest {
     super(METHOD.POST, "/update");
   }
 
-  public UpdateRequest(String url) {
-    super(METHOD.POST, url);
+  public UpdateRequest(String path) {
+    super(METHOD.POST, path);
   }
 
   /** clear the pending documents and delete commands */
@@ -250,11 +250,10 @@ public class UpdateRequest extends AbstractUpdateRequest {
         String leaderUrl = urls.get(0);
         LBSolrClient.Req request = routes.get(leaderUrl);
         if (request == null) {
-          UpdateRequest updateRequest = new UpdateRequest();
+          UpdateRequest updateRequest = new UpdateRequest(getPath());
           updateRequest.setMethod(getMethod());
           updateRequest.setCommitWithin(getCommitWithin());
           updateRequest.setParams(params);
-          updateRequest.setPath(getPath());
           updateRequest.setBasicAuthCredentials(getBasicAuthUser(), getBasicAuthPassword());
           updateRequest.setResponseParser(getResponseParser());
           updateRequest.addHeaders(getHeaders());
diff --git a/solr/solrj/src/test/org/apache/solr/client/solrj/SolrExampleTests.java b/solr/solrj/src/test/org/apache/solr/client/solrj/SolrExampleTests.java
index 64090fb8e17..adf572c2902 100644
--- a/solr/solrj/src/test/org/apache/solr/client/solrj/SolrExampleTests.java
+++ b/solr/solrj/src/test/org/apache/solr/client/solrj/SolrExampleTests.java
@@ -2337,8 +2337,7 @@ public abstract class SolrExampleTests extends SolrExampleTestsBase {
     q.set("fl", "id,name,aaa:[value v=aaa]");
 
     // First Try with the BinaryResponseParser
-    QueryRequest req = new QueryRequest(q);
-    req.setPath("/get");
+    QueryRequest req = new QueryRequest("/get", q);
     req.setResponseParser(new JavaBinResponseParser());
     QueryResponse rsp = req.process(client);
     SolrDocument out = (SolrDocument) rsp.getResponse().get("doc");
diff --git a/solr/solrj/src/test/org/apache/solr/client/solrj/request/TestCoreAdmin.java b/solr/solrj/src/test/org/apache/solr/client/solrj/request/TestCoreAdmin.java
index 7c572275b10..d4b7beece42 100644
--- a/solr/solrj/src/test/org/apache/solr/client/solrj/request/TestCoreAdmin.java
+++ b/solr/solrj/src/test/org/apache/solr/client/solrj/request/TestCoreAdmin.java
@@ -26,6 +26,8 @@ import java.util.Collection;
 import org.apache.commons.io.file.PathUtils;
 import org.apache.lucene.tests.util.LuceneTestCase;
 import org.apache.solr.client.solrj.SolrClient;
+import org.apache.solr.client.solrj.SolrRequest.METHOD;
+import org.apache.solr.client.solrj.SolrRequest.SolrRequestType;
 import org.apache.solr.client.solrj.embedded.AbstractEmbeddedSolrServerTestCase;
 import org.apache.solr.client.solrj.request.CoreAdminRequest.Create;
 import org.apache.solr.client.solrj.request.CoreAdminRequest.RequestRecovery;
@@ -110,8 +112,8 @@ public class TestCoreAdmin extends AbstractEmbeddedSolrServerTestCase {
     params.set("action", "BADACTION");
     String collectionName = "badactioncollection";
     params.set("name", collectionName);
-    QueryRequest request = new QueryRequest(params);
-    request.setPath("/admin/cores");
+    var request =
+        new GenericSolrRequest(METHOD.POST, "/admin/cores", SolrRequestType.ADMIN, params);
     expectThrows(SolrException.class, () -> getSolrAdmin().request(request));
   }
 
diff --git a/solr/test-framework/src/java/org/apache/solr/SolrTestCaseHS.java b/solr/test-framework/src/java/org/apache/solr/SolrTestCaseHS.java
index e27708c5381..160da2b1a85 100644
--- a/solr/test-framework/src/java/org/apache/solr/SolrTestCaseHS.java
+++ b/solr/test-framework/src/java/org/apache/solr/SolrTestCaseHS.java
@@ -163,14 +163,9 @@ public class SolrTestCaseHS extends SolrTestCaseJ4 {
     }
     ModifiableSolrParams p = new ModifiableSolrParams(params);
     p.set("wt", wt);
-    String path = p.get("qt");
-    p.remove("qt");
     p.set("indent", "true");
 
     QueryRequest query = new QueryRequest(p);
-    if (path != null) {
-      query.setPath(path);
-    }
 
     if ("json".equals(wt)) {
       query.setResponseParser(new JsonMapResponseParser());
diff --git a/solr/test-framework/src/java/org/apache/solr/cloud/AbstractFullDistribZkTestBase.java b/solr/test-framework/src/java/org/apache/solr/cloud/AbstractFullDistribZkTestBase.java
index ef9159a38d5..ae0b250a3d5 100644
--- a/solr/test-framework/src/java/org/apache/solr/cloud/AbstractFullDistribZkTestBase.java
+++ b/solr/test-framework/src/java/org/apache/solr/cloud/AbstractFullDistribZkTestBase.java
@@ -2837,7 +2837,6 @@ public abstract class AbstractFullDistribZkTestBase extends BaseDistributedSearc
       params.set("name", testCollectionName);
       var request =
           new GenericSolrRequest(METHOD.GET, "/admin/collections", SolrRequestType.ADMIN, params);
-      request.setPath("/admin/collections");
       client.request(request);
       Thread.sleep(2000); // reload can take a short while
 


(solr) 04/13: SOLR-18313: Prep for Lucene 11: use newer Lucene API forms (#4651)

Posted by ds...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

dsmiley pushed a commit to branch branch_10x
in repository https://gitbox.apache.org/repos/asf/solr.git

commit 5747b366992c4db4f9f918fe59797b671cb620c4
Author: Serhiy Bzhezytskyy <me...@serhiy-bzhezytskyy.com>
AuthorDate: Thu Jul 30 04:44:45 2026 +0300

    SOLR-18313: Prep for Lucene 11: use newer Lucene API forms (#4651)
    
    * Sort "missing value" (where docs without a value in the sort field are placed)
    * Automaton concatenation in the reverse-wildcard query path.
    
    Co-authored-by: Serhiy Bzhezytskyy <se...@gmail.com>
    (cherry picked from commit bd6df9214eeff4a959970cbd0ef58fb1f951dd76)
---
 .../unreleased/SOLR-18313-prep-for-lucene-11.yml   | 10 ++++++
 .../apache/solr/parser/SolrQueryParserBase.java    |  5 +--
 .../java/org/apache/solr/schema/EnumFieldType.java | 12 ++++++-
 .../src/java/org/apache/solr/schema/FieldType.java | 37 +++++++++++-----------
 4 files changed, 43 insertions(+), 21 deletions(-)

diff --git a/changelog/unreleased/SOLR-18313-prep-for-lucene-11.yml b/changelog/unreleased/SOLR-18313-prep-for-lucene-11.yml
new file mode 100644
index 00000000000..2ce54549879
--- /dev/null
+++ b/changelog/unreleased/SOLR-18313-prep-for-lucene-11.yml
@@ -0,0 +1,10 @@
+# See https://github.com/apache/solr/blob/main/dev-docs/changelog.adoc
+title: >
+  Prep for Lucene 11: switch two internal call sites (sort missing-value handling and automaton
+  concatenation) to the newer Lucene API forms that already exist in Lucene 10.4. No behavior change.
+type: changed
+authors:
+  - name: Serhiy Bzhezytskyy
+links:
+  - name: SOLR-18313
+    url: https://issues.apache.org/jira/browse/SOLR-18313
diff --git a/solr/core/src/java/org/apache/solr/parser/SolrQueryParserBase.java b/solr/core/src/java/org/apache/solr/parser/SolrQueryParserBase.java
index 42cedf82979..e1202a5c249 100644
--- a/solr/core/src/java/org/apache/solr/parser/SolrQueryParserBase.java
+++ b/solr/core/src/java/org/apache/solr/parser/SolrQueryParserBase.java
@@ -1296,14 +1296,15 @@ public abstract class SolrQueryParserBase extends QueryBuilder {
           WildcardQuery.toAutomaton(term, Operations.DEFAULT_DETERMINIZE_WORK_LIMIT);
       // TODO: we should likely use the automaton to calculate shouldReverse, too.
       if (factory.shouldReverse(termStr)) {
-        automaton = Operations.concatenate(automaton, Automata.makeChar(factory.getMarkerChar()));
+        automaton =
+            Operations.concatenate(List.of(automaton, Automata.makeChar(factory.getMarkerChar())));
         automaton = Operations.reverse(automaton);
       } else {
         // reverse wildcardfilter is active: remove false positives
         // fsa representing false positives (markerChar*)
         Automaton falsePositives =
             Operations.concatenate(
-                Automata.makeChar(factory.getMarkerChar()), Automata.makeAnyString());
+                List.of(Automata.makeChar(factory.getMarkerChar()), Automata.makeAnyString()));
         // subtract these away
         automaton =
             Operations.minus(automaton, falsePositives, Operations.DEFAULT_DETERMINIZE_WORK_LIMIT);
diff --git a/solr/core/src/java/org/apache/solr/schema/EnumFieldType.java b/solr/core/src/java/org/apache/solr/schema/EnumFieldType.java
index 47aaf472d46..2dc89f73a57 100644
--- a/solr/core/src/java/org/apache/solr/schema/EnumFieldType.java
+++ b/solr/core/src/java/org/apache/solr/schema/EnumFieldType.java
@@ -41,6 +41,7 @@ import org.apache.lucene.search.ConstantScoreQuery;
 import org.apache.lucene.search.Query;
 import org.apache.lucene.search.SortField;
 import org.apache.lucene.search.SortedNumericSelector;
+import org.apache.lucene.search.SortedNumericSortField;
 import org.apache.lucene.search.TermRangeQuery;
 import org.apache.lucene.util.BytesRef;
 import org.apache.lucene.util.BytesRefBuilder;
@@ -452,7 +453,16 @@ public class EnumFieldType extends PrimitiveFieldType {
     final SortField result = getNumericSort(field, NumberType.INTEGER, top);
     if (null == result.getMissingValue()) {
       // special case 'enum' default behavior: assume missing values are "below" all enum values
-      result.setMissingValue(Integer.MIN_VALUE);
+      if (result instanceof SortedNumericSortField snsf) {
+        return new SortedNumericSortField(
+            snsf.getField(),
+            snsf.getNumericType(),
+            snsf.getReverse(),
+            snsf.getSelector(),
+            Integer.MIN_VALUE);
+      }
+      return new SortField(
+          result.getField(), result.getType(), result.getReverse(), Integer.MIN_VALUE);
     }
     return result;
   }
diff --git a/solr/core/src/java/org/apache/solr/schema/FieldType.java b/solr/core/src/java/org/apache/solr/schema/FieldType.java
index 1452233beee..14a7b274b4a 100644
--- a/solr/core/src/java/org/apache/solr/schema/FieldType.java
+++ b/solr/core/src/java/org/apache/solr/schema/FieldType.java
@@ -778,10 +778,8 @@ public abstract class FieldType extends FieldProperties {
       Object missingHigh) {
     field.checkSortability();
 
-    SortField sf = new SortField(field.getName(), sortType, reverse);
-    applySetMissingValue(field, sf, missingLow, missingHigh);
-
-    return sf;
+    return new SortField(
+        field.getName(), sortType, reverse, missingValue(field, reverse, missingLow, missingHigh));
   }
 
   /** Same as {@link #getSortField} but using {@link SortedSetSortField} */
@@ -793,10 +791,8 @@ public abstract class FieldType extends FieldProperties {
       Object missingHigh) {
 
     field.checkSortability();
-    SortField sf = new SortedSetSortField(field.getName(), reverse, selector);
-    applySetMissingValue(field, sf, missingLow, missingHigh);
-
-    return sf;
+    return new SortedSetSortField(
+        field.getName(), reverse, selector, missingValue(field, reverse, missingLow, missingHigh));
   }
 
   /** Same as {@link #getSortField} but using {@link SortedNumericSortField}. */
@@ -809,25 +805,30 @@ public abstract class FieldType extends FieldProperties {
       Object missingHigh) {
 
     field.checkSortability();
-    SortField sf = new SortedNumericSortField(field.getName(), sortType, reverse, selector);
-    applySetMissingValue(field, sf, missingLow, missingHigh);
-
-    return sf;
+    return new SortedNumericSortField(
+        field.getName(),
+        sortType,
+        reverse,
+        selector,
+        missingValue(field, reverse, missingLow, missingHigh));
   }
 
   /**
+   * Computes the sort {@code missingValue} to pass to a {@link SortField} constructor based on the
+   * field's {@code sortMissingFirst}/{@code sortMissingLast} properties and the sort direction.
+   * Returns {@code null} when neither property is set.
+   *
    * @see #getSortField
    * @see #getSortedSetSortField
    */
-  private static void applySetMissingValue(
-      SchemaField field, SortField sortField, Object missingLow, Object missingHigh) {
-    final boolean reverse = sortField.getReverse();
-
+  private static Object missingValue(
+      SchemaField field, boolean reverse, Object missingLow, Object missingHigh) {
     if (field.sortMissingLast()) {
-      sortField.setMissingValue(reverse ? missingLow : missingHigh);
+      return reverse ? missingLow : missingHigh;
     } else if (field.sortMissingFirst()) {
-      sortField.setMissingValue(reverse ? missingHigh : missingLow);
+      return reverse ? missingHigh : missingLow;
     }
+    return null;
   }
 
   /**


(solr) 11/13: build: centralize maven repo declarations (#4677)

Posted by ds...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

dsmiley pushed a commit to branch branch_10x
in repository https://gitbox.apache.org/repos/asf/solr.git

commit 81e57446ce697fb9adfc8185f3229f7417d5afad
Author: David Smiley <ds...@apache.org>
AuthorDate: Sat Aug 1 12:45:50 2026 -0400

    build: centralize maven repo declarations (#4677)
    
    (cherry picked from commit 54758e81b4012796c03bca0b14d403e1d10204ca)
---
 build-tools/build-infra/build.gradle               |  4 +--
 .../build-infra/declare-repositories.gradle        | 42 ++++++++++++++++++++++
 build-tools/build-infra/settings.gradle            |  4 +++
 build-tools/missing-doclet/build.gradle            |  4 +--
 build-tools/missing-doclet/settings.gradle         |  4 +++
 .../PR#4677-buildCentralizeRepoDeclaration.yml     |  8 +++++
 gradle/documentation/markdown.gradle               | 26 +++++++-------
 gradle/globals.gradle                              | 13 +------
 gradle/testing/randomization.gradle                |  6 ++--
 gradle/validation/git-status.gradle                | 15 ++++----
 gradle/validation/jar-checks.gradle                |  4 +--
 gradle/validation/rat-sources.gradle               |  4 +--
 settings.gradle                                    |  5 +--
 solr/docker/build.gradle                           |  8 ++---
 solr/ui/build.gradle.kts                           |  3 +-
 15 files changed, 90 insertions(+), 60 deletions(-)

diff --git a/build-tools/build-infra/build.gradle b/build-tools/build-infra/build.gradle
index 9b5ff387488..bd1a4c04216 100644
--- a/build-tools/build-infra/build.gradle
+++ b/build-tools/build-infra/build.gradle
@@ -20,9 +20,7 @@ plugins {
   alias(libs.plugins.diffplug.spotless) apply false
 }
 
-repositories {
-  mavenCentral()
-}
+apply from: file("declare-repositories.gradle")
 
 group = "org.apache"
 
diff --git a/build-tools/build-infra/declare-repositories.gradle b/build-tools/build-infra/declare-repositories.gradle
new file mode 100644
index 00000000000..111ff365b09
--- /dev/null
+++ b/build-tools/build-infra/declare-repositories.gradle
@@ -0,0 +1,42 @@
+/*
+ * 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.
+ */
+
+// Central repository declarations for every consumption scope: plugin resolution
+// (pluginManagement), project dependencies, buildscript classpath, and the
+// build-infra / missing-doclet included builds. Applied via
+// `apply from: <this>, to: <handler>` onto whichever object owns the repositories.
+//
+// Your enterprise mirror: set the `solr.maven.repo.url` system property (via
+// -Dsolr.maven.repo.url=..., or systemProp.solr.maven.repo.url=... in gradle.properties) or
+// the equivalent SOLR_MAVEN_REPO_URL environment variable to route every scope through a
+// single internal mirror (e.g. Artifactory/Nexus) instead of public repositories. System
+// properties and environment variables are inherited by the included builds, so one setting
+// covers the entire build.
+
+def mirrorUrl = System.getProperty('solr.maven.repo.url') ?: System.getenv('SOLR_MAVEN_REPO_URL')
+
+repositories {
+  if (mirrorUrl) {
+    maven {
+      // name = 'yourEnterpriseMirror'
+      url = mirrorUrl
+    }
+  } else {
+    mavenCentral()
+    gradlePluginPortal()
+  }
+}
diff --git a/build-tools/build-infra/settings.gradle b/build-tools/build-infra/settings.gradle
index c03775cb0b9..4e51e03a47a 100644
--- a/build-tools/build-infra/settings.gradle
+++ b/build-tools/build-infra/settings.gradle
@@ -15,6 +15,10 @@
  * limitations under the License.
  */
 
+pluginManagement {
+  apply from: file("declare-repositories.gradle"), to: delegate
+}
+
 rootProject.name = 'build-infra'
 
 // Use project's version catalog for centralized dependency management
diff --git a/build-tools/missing-doclet/build.gradle b/build-tools/missing-doclet/build.gradle
index 11a7fc6e2a8..e973631ba2b 100644
--- a/build-tools/missing-doclet/build.gradle
+++ b/build-tools/missing-doclet/build.gradle
@@ -20,9 +20,7 @@ plugins {
   alias(libs.plugins.diffplug.spotless) apply false
 }
 
-repositories {
-  mavenCentral()
-}
+apply from: file("../build-infra/declare-repositories.gradle")
 
 group = "org.apache.solr.tools"
 description = 'Doclet-based javadoc validation'
diff --git a/build-tools/missing-doclet/settings.gradle b/build-tools/missing-doclet/settings.gradle
index c8abe2fa87f..e32c65d3722 100644
--- a/build-tools/missing-doclet/settings.gradle
+++ b/build-tools/missing-doclet/settings.gradle
@@ -15,6 +15,10 @@
  * limitations under the License.
  */
 
+pluginManagement {
+  apply from: file("../build-infra/declare-repositories.gradle"), to: delegate
+}
+
 rootProject.name = "missing-doclet"
 
 // Use project's version catalog for centralized dependency management
diff --git a/changelog/unreleased/PR#4677-buildCentralizeRepoDeclaration.yml b/changelog/unreleased/PR#4677-buildCentralizeRepoDeclaration.yml
new file mode 100644
index 00000000000..b40fb37d0f7
--- /dev/null
+++ b/changelog/unreleased/PR#4677-buildCentralizeRepoDeclaration.yml
@@ -0,0 +1,8 @@
+title: >
+  Centralize Maven repository declarations for the build.  Can customize with SOLR_MAVEN_REPO_URL.
+type: other
+authors:
+  - name: David Smiley
+links:
+  - name: PR#4677
+    url: https://github.com/apache/solr/pull/4677
diff --git a/gradle/documentation/markdown.gradle b/gradle/documentation/markdown.gradle
index eb9458bdb9c..ee3926a2cdf 100644
--- a/gradle/documentation/markdown.gradle
+++ b/gradle/documentation/markdown.gradle
@@ -15,22 +15,20 @@
  * limitations under the License.
  */
 
-import com.vladsch.flexmark.ast.Heading;
-import com.vladsch.flexmark.ext.abbreviation.AbbreviationExtension;
-import com.vladsch.flexmark.ext.attributes.AttributesExtension;
-import com.vladsch.flexmark.ext.autolink.AutolinkExtension;
-import com.vladsch.flexmark.html.HtmlRenderer;
-import com.vladsch.flexmark.parser.Parser;
-import com.vladsch.flexmark.parser.ParserEmulationProfile;
-import com.vladsch.flexmark.util.ast.Document;
-import com.vladsch.flexmark.util.data.MutableDataSet;
-import com.vladsch.flexmark.util.sequence.Escaping;
-import groovy.text.SimpleTemplateEngine;
+import com.vladsch.flexmark.ast.Heading
+import com.vladsch.flexmark.ext.abbreviation.AbbreviationExtension
+import com.vladsch.flexmark.ext.attributes.AttributesExtension
+import com.vladsch.flexmark.ext.autolink.AutolinkExtension
+import com.vladsch.flexmark.html.HtmlRenderer
+import com.vladsch.flexmark.parser.Parser
+import com.vladsch.flexmark.parser.ParserEmulationProfile
+import com.vladsch.flexmark.util.ast.Document
+import com.vladsch.flexmark.util.data.MutableDataSet
+import com.vladsch.flexmark.util.sequence.Escaping
+import groovy.text.SimpleTemplateEngine
 
 buildscript {
-  repositories {
-    mavenCentral()
-  }
+  apply from: rootProject.file('build-tools/build-infra/declare-repositories.gradle'), to: delegate
 
   dependencies {
     classpath libs.flexmark.flexmark
diff --git a/gradle/globals.gradle b/gradle/globals.gradle
index 38bf41e9a6b..a9e9efe57d3 100644
--- a/gradle/globals.gradle
+++ b/gradle/globals.gradle
@@ -16,7 +16,6 @@
  */
 
 import javax.inject.Inject
-import org.gradle.process.ExecOperations
 
 interface ExecOperationsHolder {
   @Inject
@@ -28,18 +27,8 @@ allprojects {
 
   group "org.apache"
 
-  // def lucenePrereleaseBuild = '9'
-
   // Repositories to fetch dependencies from.
-  repositories {
-    mavenCentral()
-    /* Reenable this if we need it again in future
-    maven {
-      name "LucenePrerelease${lucenePrereleaseBuild}"
-      url "https://nightlies.apache.org/solr/lucene-prereleases/${lucenePrereleaseBuild}/"
-    }
-    */
-  }
+  apply from: rootProject.file('build-tools/build-infra/declare-repositories.gradle'), to: delegate
 
   // Artifacts will have names after full gradle project path
   // so :solr:core will have solr-core.jar, etc.
diff --git a/gradle/testing/randomization.gradle b/gradle/testing/randomization.gradle
index 98787442cc2..d51eac1f9c5 100644
--- a/gradle/testing/randomization.gradle
+++ b/gradle/testing/randomization.gradle
@@ -19,15 +19,13 @@
 // Configure test randomization seeds and derived test properties.
 //
 
-import java.nio.file.*
 import com.carrotsearch.randomizedtesting.SeedUtils
 import com.carrotsearch.randomizedtesting.generators.RandomPicks
+import java.nio.file.Path
 import org.apache.tools.ant.types.Commandline
 
 buildscript {
-  repositories {
-    mavenCentral()
-  }
+  apply from: rootProject.file('build-tools/build-infra/declare-repositories.gradle'), to: delegate
 
   dependencies {
     classpath libs.carrotsearch.randomizedtesting.runner
diff --git a/gradle/validation/git-status.gradle b/gradle/validation/git-status.gradle
index 8893ff7b552..17fa3527511 100644
--- a/gradle/validation/git-status.gradle
+++ b/gradle/validation/git-status.gradle
@@ -17,20 +17,19 @@
 
 // This verifies local git repository's status.
 
-import org.eclipse.jgit.api.*
-import org.eclipse.jgit.storage.file.FileRepositoryBuilder
-import org.eclipse.jgit.errors.*
-
 import java.nio.file.FileVisitResult
 import java.nio.file.Files
-import java.nio.file.SimpleFileVisitor
 import java.nio.file.Path
+import java.nio.file.SimpleFileVisitor
 import java.nio.file.attribute.BasicFileAttributes
+import org.eclipse.jgit.api.Git
+import org.eclipse.jgit.errors.NoWorkTreeException
+import org.eclipse.jgit.errors.NotSupportedException
+import org.eclipse.jgit.errors.RepositoryNotFoundException
+import org.eclipse.jgit.storage.file.FileRepositoryBuilder
 
 buildscript {
-  repositories {
-    mavenCentral()
-  }
+  apply from: rootProject.file('build-tools/build-infra/declare-repositories.gradle'), to: delegate
 
   dependencies {
     classpath libs.eclipse.jgit.jgit
diff --git a/gradle/validation/jar-checks.gradle b/gradle/validation/jar-checks.gradle
index 2dfd434098a..8000ff20b94 100644
--- a/gradle/validation/jar-checks.gradle
+++ b/gradle/validation/jar-checks.gradle
@@ -31,9 +31,7 @@ def failOnError = true
 
 // We're using commons-codec for computing checksums.
 buildscript {
-  repositories {
-    mavenCentral()
-  }
+  apply from: rootProject.file('build-tools/build-infra/declare-repositories.gradle'), to: delegate
 
   dependencies {
     classpath libs.commonscodec.commonscodec
diff --git a/gradle/validation/rat-sources.gradle b/gradle/validation/rat-sources.gradle
index dce061407ca..27c00a4ddf1 100644
--- a/gradle/validation/rat-sources.gradle
+++ b/gradle/validation/rat-sources.gradle
@@ -19,9 +19,7 @@ import groovy.xml.XmlSlurper
 import org.eclipse.jgit.storage.file.FileRepositoryBuilder
 
 buildscript {
-  repositories {
-    mavenCentral()
-  }
+  apply from: rootProject.file('build-tools/build-infra/declare-repositories.gradle'), to: delegate
 
   dependencies {
     classpath libs.eclipse.jgit.jgit
diff --git a/settings.gradle b/settings.gradle
index be01caa7fd7..c942d5857a2 100644
--- a/settings.gradle
+++ b/settings.gradle
@@ -16,10 +16,7 @@
  */
 
 pluginManagement {
-  repositories {
-    mavenCentral()
-    gradlePluginPortal()
-  }
+  apply from: file("build-tools/build-infra/declare-repositories.gradle"), to: delegate
 
   includeBuild("build-tools/build-infra")
 }
diff --git a/solr/docker/build.gradle b/solr/docker/build.gradle
index 2674921038d..05fa30e3e45 100644
--- a/solr/docker/build.gradle
+++ b/solr/docker/build.gradle
@@ -17,9 +17,8 @@
 
 import java.util.regex.Matcher
 import java.util.regex.Pattern
-import org.apache.commons.codec.digest.DigestUtils
-import org.gradle.process.ExecOperations
 import javax.inject.Inject
+import org.apache.commons.codec.digest.DigestUtils
 
 description = 'Solr Docker image'
 
@@ -140,9 +139,8 @@ dependencies {
 
 // We're using commons-codec for computing checksums.
 buildscript {
-  repositories {
-    mavenCentral()
-  }
+  apply from: rootProject.file('build-tools/build-infra/declare-repositories.gradle'), to: delegate
+
   dependencies {
     classpath libs.commonscodec.commonscodec
   }
diff --git a/solr/ui/build.gradle.kts b/solr/ui/build.gradle.kts
index 2fee97f06b4..ec95251b64a 100644
--- a/solr/ui/build.gradle.kts
+++ b/solr/ui/build.gradle.kts
@@ -27,8 +27,9 @@ repositories {
             includeGroupAndSubgroups("com.google")
         }
     }
-    mavenCentral()
 }
+// mavenCentral / enterprise mirror, shared with the rest of the build.
+apply(from = rootProject.file("build-tools/build-infra/declare-repositories.gradle"))
 
 plugins {
     alias(libs.plugins.kotlin.multiplatform)


(solr) 07/13: Extract CLIUtils.solrUrlFromConnection() from normalizeSolrUrl(CommandLine) (#4683)

Posted by ds...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

dsmiley pushed a commit to branch branch_10x
in repository https://gitbox.apache.org/repos/asf/solr.git

commit 14830a71a41f19056b9118dfdb81067cea0f4b34
Author: Jan Høydahl <ja...@apache.org>
AuthorDate: Thu Jul 30 17:02:40 2026 +0200

    Extract CLIUtils.solrUrlFromConnection() from normalizeSolrUrl(CommandLine) (#4683)
    
    (cherry picked from commit 9f5fac2a4e98f56fe07a9da1d7eab6f3c2a6a9eb)
---
 .../src/java/org/apache/solr/cli/CLIUtils.java     | 50 +++++++++++++---------
 1 file changed, 29 insertions(+), 21 deletions(-)

diff --git a/solr/core/src/java/org/apache/solr/cli/CLIUtils.java b/solr/core/src/java/org/apache/solr/cli/CLIUtils.java
index b6eda1f40d8..e0b3db25d29 100644
--- a/solr/core/src/java/org/apache/solr/cli/CLIUtils.java
+++ b/solr/core/src/java/org/apache/solr/cli/CLIUtils.java
@@ -235,34 +235,42 @@ public final class CLIUtils {
             "Neither --solr-connection, --zk-host or --solr-url parameters, nor SOLR_CONNECTION, ZK_HOST env var provided, so assuming solr url is "
                 + solrUrl
                 + ".");
-      } else if (!solrConnection.isZookeeper()) {
-        // HTTP form (e.g. `-s http://host:port`): the connection string already names a Solr URL,
-        // so use it directly without spinning up a CloudSolrClient.
-        solrUrl = normalizeSolrUrl(solrConnection.quorumItems().get(0), false);
       } else {
-        var builder =
-            new HttpJettySolrClient.Builder()
-                .withOptionalBasicAuthCredentials(
-                    cli.getOptionValue(CommonCLIOptions.CREDENTIALS_OPTION));
-        try (CloudSolrClient cloudSolrClient = getCloudSolrClient(solrConnection, builder)) {
-          Set<String> liveNodes = cloudSolrClient.getClusterState().getLiveNodes();
-          if (liveNodes.isEmpty())
-            throw new IllegalStateException(
-                "No live nodes found! Cannot determine 'solrUrl' from SolrCloud: "
-                    + solrConnection);
-
-          String firstLiveNode = liveNodes.iterator().next();
-          String urlScheme =
-              cloudSolrClient.getClusterStateProvider().getClusterProperty("urlScheme", "http");
-          solrUrl = URLUtil.getBaseUrlForNodeName(firstLiveNode, urlScheme, false);
-          solrUrl = normalizeSolrUrl(solrUrl, false);
-        }
+        solrUrl =
+            solrUrlFromConnection(
+                solrConnection, cli.getOptionValue(CommonCLIOptions.CREDENTIALS_OPTION));
       }
     }
     solrUrl = normalizeSolrUrl(solrUrl);
     return solrUrl;
   }
 
+  /**
+   * Resolves a base Solr URL from a parsed connection. The HTTP form (e.g. {@code -s
+   * http://host:port}) already names a Solr URL, so it is used directly without spinning up a
+   * CloudSolrClient; the ZooKeeper form queries the cluster for a live node's base URL.
+   */
+  public static String solrUrlFromConnection(
+      CloudSolrClient.CloudSolrClientConnection solrConnection, String credentials)
+      throws Exception {
+    if (!solrConnection.isZookeeper()) {
+      return normalizeSolrUrl(solrConnection.quorumItems().get(0), false);
+    }
+    var builder = new HttpJettySolrClient.Builder().withOptionalBasicAuthCredentials(credentials);
+    try (CloudSolrClient cloudSolrClient = getCloudSolrClient(solrConnection, builder)) {
+      Set<String> liveNodes = cloudSolrClient.getClusterState().getLiveNodes();
+      if (liveNodes.isEmpty())
+        throw new IllegalStateException(
+            "No live nodes found! Cannot determine 'solrUrl' from SolrCloud: " + solrConnection);
+
+      String firstLiveNode = liveNodes.iterator().next();
+      String urlScheme =
+          cloudSolrClient.getClusterStateProvider().getClusterProperty("urlScheme", "http");
+      return normalizeSolrUrl(
+          URLUtil.getBaseUrlForNodeName(firstLiveNode, urlScheme, false), false);
+    }
+  }
+
   /**
    * Returns true if the user supplied any of the connection-related CLI options ({@code
    * --solr-url}, {@code --solr-connection}, or {@code --zk-host}). Use this to gate logic that