romseygeek commented on code in PR #16424:
URL: https://github.com/apache/lucene/pull/16424#discussion_r3672696250


##########
lucene/core/src/java/org/apache/lucene/search/Sort.java:
##########
@@ -132,4 +134,37 @@ public boolean needsScores() {
     }
     return false;
   }
+
+  /**
+   * Returns the primary index sort field for the given LeafReader, or null if 
none is configured.
+   *
+   * <p>If sorting against a field would have no effect then that SortField is 
skipped over and the
+   * next SortField in the list is returned. This can happen for fields with 
no values in the
+   * segment, or fields that have only a single distinct value.
+   */
+  public static SortField getPrimarySortField(LeafReader reader) {
+    Sort sort = reader.getMetaData().sort();
+    if (sort == null) {
+      return null;
+    }
+    for (SortField sf : sort.fields) {
+      String field = sf.getField();
+      if (field == null) {
+        // Custom field that we don't know anything about, so return it as 
primary
+        return sf;
+      }
+      if (reader.getFieldInfos().fieldInfo(field) == null) {
+        // Field has no values in this segment, so sorting by it has no effect.
+        continue;
+      }
+      // If the field has a skip index, check whether all values are identical,
+      // in which case sorting by this field is a no-op for this segment.
+      DocValuesSkipper skipper = reader.getDocValuesSkipper(field);
+      if (skipper != null && skipper.minValue() == skipper.maxValue()) {

Review Comment:
   Oh that's a good point - if we have docs with missing values then that adds 
an implicit second sort value.  We currently check for denseness in the 
top-level caller but we should do that here instead.  I'll update, thanks!



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to