Apache Lucene open-source search software
Fix incorrect handling of missing values in ToParentBlockJoinSortField(#15727)
Mary Gouseti167503f6d84d
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txtindex 77f55c11805..959ed3ce95e 100644--- a/lucene/CHANGES.txt+++ b/lucene/CHANGES.txt@@ -248,6 +248,10 @@ Bug Fixes* GITHUB#15702: Fix Potential NullPointException in BytesRefHash initialization#15702 (tyronecai)+* GITHUB#15727: Add separately configurable missing values to ToParentBlockJoinSortField for parent and children sorting;+ and fix incorrect handling of children missing values. Children with missing values now correctly participate in the+ min/max selection according to the configured missing value. (Mary Gouseti)+* GITHUB#15731: Fix tessellator failure when a hole is touching another hole in the middle of a segment. In this casewe might fail to detect it and choose a wrong bridge to eliminate the hole. (Ignacio Vera)diff --git a/lucene/join/src/java/org/apache/lucene/search/join/BlockJoinSelector.java b/lucene/join/src/java/org/apache/lucene/search/join/BlockJoinSelector.javaindex 1da660ffa3b..22cab53fbe2 100644--- a/lucene/join/src/java/org/apache/lucene/search/join/BlockJoinSelector.java+++ b/lucene/join/src/java/org/apache/lucene/search/join/BlockJoinSelector.java@@ -90,10 +90,15 @@ public class BlockJoinSelector {/*** Wraps the provided {@link SortedSetDocValues} in order to only select one value per parent- * among its {@code children} using the configured {@code selection} type.+ * among its {@code children} using the configured {@code selection} type. When a parent has+ * children with missing values, we sort missing values according to {@code sortMissingLast}.*/public static SortedDocValues wrap(- SortedSetDocValues sortedSet, Type selection, BitSet parents, DocIdSetIterator children) {+ SortedSetDocValues sortedSet,+ Type selection,+ BitSet parents,+ DocIdSetIterator children,+ boolean sortMissingLast) {SortedDocValues values;switch (selection) {case MIN:@@ -105,20 +110,25 @@ public class BlockJoinSelector {default:throw new AssertionError();}- return wrap(values, selection, parents, children);+ return wrap(values, selection, parents, children, sortMissingLast);}/*** Wraps the provided {@link SortedDocValues} in order to only select one value per parent among- * its {@code children} using the configured {@code selection} type.+ * its {@code children} using the configured {@code selection} type. When a parent has children+ * with missing values, we sort missing values according to {@code sortMissingLast}.*/public static SortedDocValues wrap(- final SortedDocValues values, Type selection, BitSet parents, DocIdSetIterator children) {+ final SortedDocValues values,+ Type selection,+ BitSet parents,+ DocIdSetIterator children,+ boolean sortMissingLast) {if (values.docID() != -1) {throw new IllegalArgumentException("values iterator was already consumed: values.docID=" + values.docID());}- return ToParentDocValues.wrap(values, selection, parents, children);+ return ToParentDocValues.wrap(values, selection, parents, children, sortMissingLast);}/** creates an iterator for the given bitset */@@ -128,13 +138,15 @@ public class BlockJoinSelector {/*** Wraps the provided {@link SortedNumericDocValues} in order to only select one value per parent- * among its {@code children} using the configured {@code selection} type.+ * among its {@code children} using the configured {@code selection} type. When a parent has+ * children with missing values, {@code childMissingValue} participates in the min/max selection.*/public static NumericDocValues wrap(SortedNumericDocValues sortedNumerics,Type selection,BitSet parents,- DocIdSetIterator children) {+ DocIdSetIterator children,+ Long childMissingValue) {NumericDocValues values;switch (selection) {case MIN:@@ -150,7 +162,7 @@ public class BlockJoinSelector {default:throw new AssertionError();}- return wrap(values, selection, parents, children);+ return wrap(values, selection, parents, children, childMissingValue);}/**@@ -166,4 +178,23 @@ public class BlockJoinSelector {}return ToParentDocValues.wrap(values, selection, parents, children);}++ /**+ * Wraps the provided {@link NumericDocValues}, iterating over only child documents, in order to+ * only select one value per parent among its {@code children} using the configured {@code+ * selection} type. When a parent has children with missing values, {@code missingValue}+ * participates in the min/max selection.+ */+ public static NumericDocValues wrap(+ final NumericDocValues values,+ Type selection,+ BitSet parents,+ DocIdSetIterator children,+ Long missingValue) {+ if (values.docID() != -1) {+ throw new IllegalArgumentException(+ "values iterator was already consumed: values.docID=" + values.docID());+ }+ return ToParentDocValues.wrap(values, selection, parents, children, missingValue);+ }}diff --git a/lucene/join/src/java/org/apache/lucene/search/join/ToParentBlockJoinSortField.java b/lucene/join/src/java/org/apache/lucene/search/join/ToParentBlockJoinSortField.javaindex b3d70320b6f..fa3cdaecb34 100644--- a/lucene/join/src/java/org/apache/lucene/search/join/ToParentBlockJoinSortField.java+++ b/lucene/join/src/java/org/apache/lucene/search/join/ToParentBlockJoinSortField.java@@ -47,9 +47,50 @@ import org.apache.lucene.util.NumericUtils;*/public class ToParentBlockJoinSortField extends SortField {- private final boolean order;+ private final boolean reverseChildren;private final BitSetProducer parentFilter;private final BitSetProducer childFilter;+ private final Object childMissingValue;++ /**+ * Create ToParentBlockJoinSortField. The parent and child document ordering is based on the flag+ * reverse. Missing values are treated as the default for the type.+ *+ * @param field The sort field on the nested / child level.+ * @param type The sort type on the nested / child level.+ * @param reverse Whether natural order should be reversed on both child and parent levels.+ * @param parentFilter Filter that identifies the parent documents.+ * @param childFilter Filter that defines which child documents participates in sorting.+ */+ public ToParentBlockJoinSortField(+ String field,+ Type type,+ boolean reverse,+ BitSetProducer parentFilter,+ BitSetProducer childFilter) {+ this(field, type, reverse, null, null, parentFilter, childFilter);+ }++ /**+ * Create ToParentBlockJoinSortField. Missing values are treated as the default for the type.+ *+ * @param field The sort field on the nested / child level.+ * @param type The sort type on the nested / child level.+ * @param reverseParents Whether natural order should be reversed on the parent level.+ * @param reverseChildren Whether natural order should be reversed on the nested / child document+ * level.+ * @param parentFilter Filter that identifies the parent documents.+ * @param childFilter Filter that defines which child documents participates in sorting.+ */+ public ToParentBlockJoinSortField(+ String field,+ Type type,+ boolean reverseParents,+ boolean reverseChildren,+ BitSetProducer parentFilter,+ BitSetProducer childFilter) {+ this(field, type, reverseParents, reverseChildren, null, null, parentFilter, childFilter);+ }/*** Create ToParentBlockJoinSortField. The parent document ordering is based on child document@@ -57,7 +98,14 @@ public class ToParentBlockJoinSortField extends SortField {** @param field The sort field on the nested / child level.* @param type The sort type on the nested / child level.- * @param reverse Whether natural order should be reversed on the nested / child level.+ * @param reverse Whether natural order should be reversed on both child and parent levels.+ * @param parentMissingValue The missing value for parent documents that have no child documents.+ * For Type.STRING use {@link SortField#STRING_FIRST} or {@link SortField#STRING_LAST}. For+ * numeric types use the corresponding boxed type (e.g. {@link Integer} for Type.INT). Pass+ * {@code null} for default behavior.+ * @param childMissingValue The missing value for child documents that lack the sort field. This+ * value participates in the min/max selection among siblings. Type constraints are the same+ * as for {@code parentMissingValue}. Pass {@code null} to skip children without a value.* @param parentFilter Filter that identifies the parent documents.* @param childFilter Filter that defines which child documents participates in sorting.*/@@ -65,28 +113,19 @@ public class ToParentBlockJoinSortField extends SortField {String field,Type type,boolean reverse,+ Object parentMissingValue,+ Object childMissingValue,BitSetProducer parentFilter,BitSetProducer childFilter) {- super(field, type, reverse);- switch (getType()) {- case STRING:- case DOUBLE:- case FLOAT:- case LONG:- case INT:- // ok- break;- case CUSTOM:- case DOC:- case REWRITEABLE:- case STRING_VAL:- case SCORE:- default:- throw new UnsupportedOperationException("Sort type " + type + " is not supported");- }- this.order = reverse;- this.parentFilter = parentFilter;- this.childFilter = childFilter;+ this(+ field,+ type,+ reverse,+ reverse,+ parentMissingValue,+ childMissingValue,+ parentFilter,+ childFilter);}/**@@ -94,45 +133,82 @@ public class ToParentBlockJoinSortField extends SortField {** @param field The sort field on the nested / child level.* @param type The sort type on the nested / child level.- * @param reverse Whether natural order should be reversed on the nested / child document level.- * @param order Whether natural order should be reversed on the parent level.+ * @param reverseParents Whether natural order should be reversed on the parent level.+ * @param reverseChildren Whether natural order should be reversed on the nested / child document+ * level.+ * @param parentMissingValue The missing value for parent documents whose children do not have a+ * value for the sort field. For Type.STRING use {@link SortField#STRING_FIRST} or {@link+ * SortField#STRING_LAST}. For numeric types use the corresponding boxed type (e.g. {@link+ * Integer} for Type.INT). Pass {@code null} for default behavior.+ * @param childMissingValue The missing value for child documents that lack the sort field. This+ * value participates in the min/max selection among siblings. Type constraints are the same+ * as for {@code parentMissingValue}. Pass {@code null} to skip children without a value.* @param parentFilter Filter that identifies the parent documents.* @param childFilter Filter that defines which child documents participates in sorting.*/public ToParentBlockJoinSortField(String field,Type type,- boolean reverse,- boolean order,+ boolean reverseParents,+ boolean reverseChildren,+ Object parentMissingValue,+ Object childMissingValue,BitSetProducer parentFilter,BitSetProducer childFilter) {- super(field, type, reverse);- this.order = order;+ super(field, type, reverseParents, parentMissingValue);+ validate(type, childMissingValue);+ this.reverseChildren = reverseChildren;this.parentFilter = parentFilter;this.childFilter = childFilter;+ this.childMissingValue = childMissingValue;+ }++ private static void validate(Type type, Object childMissingValue) {+ switch (type) {+ case STRING -> validateMissingValue(type, String.class, childMissingValue);+ case DOUBLE -> validateMissingValue(type, Double.class, childMissingValue);+ case FLOAT -> validateMissingValue(type, Float.class, childMissingValue);+ case LONG -> validateMissingValue(type, Long.class, childMissingValue);+ case INT -> validateMissingValue(type, Integer.class, childMissingValue);+ // $CASES-OMITTED$+ default -> throw new UnsupportedOperationException("Sort type " + type + " is not supported");+ }+ }++ private static <T> void validateMissingValue(Type type, Class<T> clazz, Object missingValue) {+ if (missingValue == null) {+ return;+ }+ if (type == Type.STRING) {+ if (missingValue != STRING_FIRST && missingValue != STRING_LAST) {+ throw new IllegalArgumentException(+ "For Type.STRING, missing value must be either STRING_FIRST or STRING_LAST");+ }+ return;+ }+ if (!(clazz.isInstance(missingValue))) {+ throw new IllegalArgumentException(+ "Missing value for "+ + type.getDeclaringClass().getName()+ + " must be a "+ + clazz.getName()+ + ", got "+ + missingValue.getClass().getName());+ }}@Overridepublic FieldComparator<?> getComparator(int numHits, Pruning pruning) {- switch (getType()) {- case STRING:- return getStringComparator(numHits);- case DOUBLE:- return getDoubleComparator(numHits);- case FLOAT:- return getFloatComparator(numHits);- case LONG:- return getLongComparator(numHits);- case INT:- return getIntComparator(numHits);- case CUSTOM:- case DOC:- case REWRITEABLE:- case STRING_VAL:- case SCORE:- default:- throw new UnsupportedOperationException("Sort type " + getType() + " is not supported");- }+ return switch (getType()) {+ case STRING -> getStringComparator(numHits);+ case DOUBLE -> getDoubleComparator(numHits);+ case FLOAT -> getFloatComparator(numHits);+ case LONG -> getLongComparator(numHits);+ case INT -> getIntComparator(numHits);+ // $CASES-OMITTED$+ default ->+ throw new UnsupportedOperationException("Sort type " + getType() + " is not supported");+ };}private FieldComparator<?> getStringComparator(int numHits) {@@ -143,13 +219,14 @@ public class ToParentBlockJoinSortField extends SortField {throws IOException {SortedSetDocValues sortedSet = DocValues.getSortedSet(context.reader(), field);final BlockJoinSelector.Type type =- order ? BlockJoinSelector.Type.MAX : BlockJoinSelector.Type.MIN;+ reverseChildren ? BlockJoinSelector.Type.MAX : BlockJoinSelector.Type.MIN;final BitSet parents = parentFilter.getBitSet(context);final BitSet children = childFilter.getBitSet(context);if (children == null) {return DocValues.emptySorted();}- return BlockJoinSelector.wrap(sortedSet, type, parents, toIter(children));+ return BlockJoinSelector.wrap(+ sortedSet, type, parents, toIter(children), childMissingValue == STRING_LAST);}};}@@ -166,13 +243,18 @@ public class ToParentBlockJoinSortField extends SortField {SortedNumericDocValues sortedNumeric =DocValues.getSortedNumeric(context.reader(), field);final BlockJoinSelector.Type type =- order ? BlockJoinSelector.Type.MAX : BlockJoinSelector.Type.MIN;+ reverseChildren ? BlockJoinSelector.Type.MAX : BlockJoinSelector.Type.MIN;final BitSet parents = parentFilter.getBitSet(context);final BitSet children = childFilter.getBitSet(context);if (children == null) {return DocValues.emptyNumeric();}- return BlockJoinSelector.wrap(sortedNumeric, type, parents, toIter(children));+ return BlockJoinSelector.wrap(+ sortedNumeric,+ type,+ parents,+ toIter(children),+ childMissingValue == null ? null : Long.valueOf((Integer) childMissingValue));}};}@@ -191,13 +273,14 @@ public class ToParentBlockJoinSortField extends SortField {SortedNumericDocValues sortedNumeric =DocValues.getSortedNumeric(context.reader(), field);final BlockJoinSelector.Type type =- order ? BlockJoinSelector.Type.MAX : BlockJoinSelector.Type.MIN;+ reverseChildren ? BlockJoinSelector.Type.MAX : BlockJoinSelector.Type.MIN;final BitSet parents = parentFilter.getBitSet(context);final BitSet children = childFilter.getBitSet(context);if (children == null) {return DocValues.emptyNumeric();}- return BlockJoinSelector.wrap(sortedNumeric, type, parents, toIter(children));+ return BlockJoinSelector.wrap(+ sortedNumeric, type, parents, toIter(children), (Long) childMissingValue);}};}@@ -216,14 +299,21 @@ public class ToParentBlockJoinSortField extends SortField {SortedNumericDocValues sortedNumeric =DocValues.getSortedNumeric(context.reader(), field);final BlockJoinSelector.Type type =- order ? BlockJoinSelector.Type.MAX : BlockJoinSelector.Type.MIN;+ reverseChildren ? BlockJoinSelector.Type.MAX : BlockJoinSelector.Type.MIN;final BitSet parents = parentFilter.getBitSet(context);final BitSet children = childFilter.getBitSet(context);if (children == null) {return DocValues.emptyNumeric();}return new FilterNumericDocValues(- BlockJoinSelector.wrap(sortedNumeric, type, parents, toIter(children))) {+ BlockJoinSelector.wrap(+ sortedNumeric,+ type,+ parents,+ toIter(children),+ childMissingValue == null+ ? null+ : (long) NumericUtils.floatToSortableInt((Float) childMissingValue))) {@Overridepublic long longValue() throws IOException {// undo the numericutils sortability@@ -248,14 +338,21 @@ public class ToParentBlockJoinSortField extends SortField {SortedNumericDocValues sortedNumeric =DocValues.getSortedNumeric(context.reader(), field);final BlockJoinSelector.Type type =- order ? BlockJoinSelector.Type.MAX : BlockJoinSelector.Type.MIN;+ reverseChildren ? BlockJoinSelector.Type.MAX : BlockJoinSelector.Type.MIN;final BitSet parents = parentFilter.getBitSet(context);final BitSet children = childFilter.getBitSet(context);if (children == null) {return DocValues.emptyNumeric();}return new FilterNumericDocValues(- BlockJoinSelector.wrap(sortedNumeric, type, parents, toIter(children))) {+ BlockJoinSelector.wrap(+ sortedNumeric,+ type,+ parents,+ toIter(children),+ childMissingValue == null+ ? null+ : NumericUtils.doubleToSortableLong((Double) childMissingValue))) {@Overridepublic long longValue() throws IOException {// undo the numericutils sortability@@ -273,8 +370,9 @@ public class ToParentBlockJoinSortField extends SortField {final int prime = 31;int result = super.hashCode();result = prime * result + ((childFilter == null) ? 0 : childFilter.hashCode());- result = prime * result + (order ? 1231 : 1237);+ result = prime * result + (reverseChildren ? 1231 : 1237);result = prime * result + ((parentFilter == null) ? 0 : parentFilter.hashCode());+ result = prime * result + ((childMissingValue == null) ? 0 : childMissingValue.hashCode());return result;}@@ -287,10 +385,13 @@ public class ToParentBlockJoinSortField extends SortField {if (childFilter == null) {if (other.childFilter != null) return false;} else if (!childFilter.equals(other.childFilter)) return false;- if (order != other.order) return false;+ if (reverseChildren != other.reverseChildren) return false;if (parentFilter == null) {if (other.parentFilter != null) return false;} else if (!parentFilter.equals(other.parentFilter)) return false;+ if (childMissingValue == null) {+ if (other.childMissingValue != null) return false;+ } else if (!childMissingValue.equals(other.childMissingValue)) return false;return true;}}diff --git a/lucene/join/src/java/org/apache/lucene/search/join/ToParentDocValues.java b/lucene/join/src/java/org/apache/lucene/search/join/ToParentDocValues.javaindex bcf409ebbda..8ba6b0e01b4 100644--- a/lucene/join/src/java/org/apache/lucene/search/join/ToParentDocValues.java+++ b/lucene/join/src/java/org/apache/lucene/search/join/ToParentDocValues.java@@ -32,21 +32,27 @@ class ToParentDocValues extends DocIdSetIterator {void reset() throws IOException;void increment() throws IOException;++ int getChildrenWithValuesCount();}private static final class SortedDVs extends SortedDocValues implements Accumulator {private final SortedDocValues values;private final BlockJoinSelector.Type selection;+ private final int missingOrd;private int ord = -1;+ private int childrenWithValuesCount = 0;private final ToParentDocValues iter;private SortedDVs(SortedDocValues values,BlockJoinSelector.Type selection,BitSet parents,- DocIdSetIterator children) {+ DocIdSetIterator children,+ boolean sortMissingLast) {this.values = values;this.selection = selection;+ this.missingOrd = sortMissingLast ? Integer.MAX_VALUE : -1;this.iter = new ToParentDocValues(values, parents, children, this);}@@ -58,17 +64,17 @@ class ToParentDocValues extends DocIdSetIterator {@Overridepublic void reset() throws IOException {ord = values.ordValue();+ childrenWithValuesCount = 1;}@Overridepublic void increment() throws IOException {- if (selection == BlockJoinSelector.Type.MIN) {- ord = Math.min(ord, values.ordValue());- } else if (selection == BlockJoinSelector.Type.MAX) {- ord = Math.max(ord, values.ordValue());- } else {- throw new AssertionError();+ assert selection != null;+ switch (selection) {+ case MIN -> ord = Math.min(ord, values.ordValue());+ case MAX -> ord = Math.max(ord, values.ordValue());}+ childrenWithValuesCount++;}@Override@@ -88,6 +94,12 @@ class ToParentDocValues extends DocIdSetIterator {@Overridepublic int ordValue() {+ if (iter.hasChildWithMissingValue()) {+ return switch (selection) {+ case MIN -> Math.min(ord, missingOrd);+ case MAX -> Math.max(ord, missingOrd);+ };+ }return ord;}@@ -105,12 +117,19 @@ class ToParentDocValues extends DocIdSetIterator {public long cost() {return values.cost();}++ @Override+ public int getChildrenWithValuesCount() {+ return childrenWithValuesCount;+ }}private static final class NumDV extends NumericDocValues implements Accumulator {private final NumericDocValues values;private long value;+ private int childrenWithValuesCount = 0;private final BlockJoinSelector.Type selection;+ private final Long missingValue;private final ToParentDocValues iter;@@ -119,28 +138,34 @@ class ToParentDocValues extends DocIdSetIterator {BlockJoinSelector.Type selection,BitSet parents,DocIdSetIterator children) {+ this(values, selection, parents, children, null);+ }++ private NumDV(+ NumericDocValues values,+ BlockJoinSelector.Type selection,+ BitSet parents,+ DocIdSetIterator children,+ Long missingValue) {this.values = values;this.selection = selection;+ this.missingValue = missingValue;iter = new ToParentDocValues(values, parents, children, this);}@Overridepublic void reset() throws IOException {value = values.longValue();+ childrenWithValuesCount = 1;}@Overridepublic void increment() throws IOException {switch (selection) {- case MIN:- value = Math.min(value, values.longValue());- break;- case MAX:- value = Math.max(value, values.longValue());- break;- default:- throw new AssertionError();+ case MIN -> value = Math.min(value, values.longValue());+ case MAX -> value = Math.max(value, values.longValue());}+ childrenWithValuesCount++;}@Override@@ -160,6 +185,12 @@ class ToParentDocValues extends DocIdSetIterator {@Overridepublic long longValue() {+ if (missingValue != null && iter.hasChildWithMissingValue()) {+ return switch (selection) {+ case MIN -> Math.min(value, missingValue);+ case MAX -> Math.max(value, missingValue);+ };+ }return value;}@@ -172,6 +203,11 @@ class ToParentDocValues extends DocIdSetIterator {public long cost() {return values.cost();}++ @Override+ public int getChildrenWithValuesCount() {+ return childrenWithValuesCount;+ }}private ToParentDocValues(@@ -183,15 +219,20 @@ class ToParentDocValues extends DocIdSetIterator {private final BitSet parents;private int docID = -1;+ private boolean hasChildWithMissingValue = false;private final Accumulator collector;boolean seen = false;- private DocIdSetIterator childWithValues;+ private final DocIdSetIterator childWithValues;@Overridepublic int docID() {return docID;}+ boolean hasChildWithMissingValue() {+ return hasChildWithMissingValue;+ }+@Overridepublic int nextDoc() throws IOException {assert docID != NO_MORE_DOCS;@@ -221,6 +262,9 @@ class ToParentDocValues extends DocIdSetIterator {}docID = nextParentDocID;+ int prevParentDocID = parents.prevSetBit(docID - 1);+ int totalChildren = docID - prevParentDocID - 1;+ hasChildWithMissingValue = collector.getChildrenWithValuesCount() < totalChildren;return docID;}@@ -258,11 +302,13 @@ class ToParentDocValues extends DocIdSetIterator {}docID = targetParentDocID;seen = false;+ hasChildWithMissingValue = false;// ord = -1;if (parents.get(targetParentDocID) == false) {return false;}int prevParentDocId = docID == 0 ? -1 : parents.prevSetBit(docID - 1);+ int totalChildren = docID - prevParentDocId - 1;int childDoc = childWithValues.docID();if (childDoc <= prevParentDocId) {childDoc = childWithValues.advance(prevParentDocId + 1);@@ -284,6 +330,7 @@ class ToParentDocValues extends DocIdSetIterator {for (int doc = childWithValues.docID(); doc < docID; doc = childWithValues.nextDoc()) {collector.increment();}+ hasChildWithMissingValue = collector.getChildrenWithValuesCount() < totalChildren;return true;}@@ -297,8 +344,21 @@ class ToParentDocValues extends DocIdSetIterator {return new ToParentDocValues.NumDV(values, selection, parents2, children);}+ static NumericDocValues wrap(+ NumericDocValues values,+ Type selection,+ BitSet parents,+ DocIdSetIterator children,+ Long missingValue) {+ return new ToParentDocValues.NumDV(values, selection, parents, children, missingValue);+ }+static SortedDocValues wrap(- SortedDocValues values, Type selection, BitSet parents2, DocIdSetIterator children) {- return new ToParentDocValues.SortedDVs(values, selection, parents2, children);+ SortedDocValues values,+ Type selection,+ BitSet parents,+ DocIdSetIterator children,+ boolean sortMissingLast) {+ return new ToParentDocValues.SortedDVs(values, selection, parents, children, sortMissingLast);}}diff --git a/lucene/join/src/test/org/apache/lucene/search/join/TestBlockJoinSelector.java b/lucene/join/src/test/org/apache/lucene/search/join/TestBlockJoinSelector.javaindex bcf1abffe25..f069940eee8 100644--- a/lucene/join/src/test/org/apache/lucene/search/join/TestBlockJoinSelector.java+++ b/lucene/join/src/test/org/apache/lucene/search/join/TestBlockJoinSelector.java@@ -117,13 +117,14 @@ public class TestBlockJoinSelector extends LuceneTestCase {parents.set(6);parents.set(10);parents.set(15);- parents.set(19);+ parents.set(18);final BitSet children = new FixedBitSet(20);children.set(2);children.set(3);children.set(4);children.set(12);+ children.set(16);children.set(17);final int[] ords = new int[20];@@ -132,18 +133,23 @@ public class TestBlockJoinSelector extends LuceneTestCase {ords[3] = 7;ords[4] = 3;ords[12] = 10;- ords[18] = 10;+ ords[16] = 9;+ ords[17] = 10;+ ords[18] = 11;+ ords[19] = 12;final SortedDocValues mins =BlockJoinSelector.wrap(DocValues.singleton(new CannedSortedDocValues(ords)),BlockJoinSelector.Type.MIN,parents,- toIter(children));+ toIter(children),+ true);assertEquals(5, nextDoc(mins, 5));assertEquals(3, mins.ordValue());assertEquals(15, nextDoc(mins, 15));assertEquals(10, mins.ordValue());+ assertEquals(18, nextDoc(mins, 18));assertNoMoreDoc(mins, 20);final SortedDocValues maxs =@@ -151,12 +157,130 @@ public class TestBlockJoinSelector extends LuceneTestCase {DocValues.singleton(new CannedSortedDocValues(ords)),BlockJoinSelector.Type.MAX,parents,- toIter(children));+ toIter(children),+ false);assertEquals(5, nextDoc(maxs, 5));assertEquals(7, maxs.ordValue());assertEquals(15, nextDoc(maxs, 15));assertEquals(10, maxs.ordValue());+ assertEquals(18, nextDoc(maxs, 18));assertNoMoreDoc(maxs, 20);++ SortedDocValues withMissingValues =+ BlockJoinSelector.wrap(+ DocValues.singleton(new CannedSortedDocValues(ords)),+ BlockJoinSelector.Type.MIN,+ parents,+ toIter(children),+ false);+ assertEquals(5, nextDoc(withMissingValues, 5));+ assertEquals(-1, withMissingValues.ordValue());+ assertEquals(15, nextDoc(withMissingValues, 15));+ assertEquals(-1, withMissingValues.ordValue());+ assertEquals(18, nextDoc(withMissingValues, 18));+ assertEquals(9, withMissingValues.ordValue());+ assertNoMoreDoc(withMissingValues, 20);++ withMissingValues =+ BlockJoinSelector.wrap(+ DocValues.singleton(new CannedSortedDocValues(ords)),+ BlockJoinSelector.Type.MIN,+ parents,+ toIter(children),+ true);+ assertEquals(5, nextDoc(withMissingValues, 5));+ assertEquals(3, withMissingValues.ordValue());+ assertEquals(15, nextDoc(withMissingValues, 15));+ assertEquals(10, withMissingValues.ordValue());+ assertEquals(18, nextDoc(withMissingValues, 18));+ assertEquals(9, withMissingValues.ordValue());+ assertNoMoreDoc(withMissingValues, 20);++ withMissingValues =+ BlockJoinSelector.wrap(+ DocValues.singleton(new CannedSortedDocValues(ords)),+ BlockJoinSelector.Type.MAX,+ parents,+ toIter(children),+ false);+ assertEquals(5, nextDoc(withMissingValues, 5));+ assertEquals(7, withMissingValues.ordValue());+ assertEquals(15, nextDoc(withMissingValues, 15));+ assertEquals(10, withMissingValues.ordValue());+ assertEquals(18, nextDoc(withMissingValues, 18));+ assertEquals(10, withMissingValues.ordValue());+ assertNoMoreDoc(withMissingValues, 20);++ withMissingValues =+ BlockJoinSelector.wrap(+ DocValues.singleton(new CannedSortedDocValues(ords)),+ BlockJoinSelector.Type.MAX,+ parents,+ toIter(children),+ true);+ assertEquals(5, nextDoc(withMissingValues, 5));+ assertEquals(Integer.MAX_VALUE, withMissingValues.ordValue());+ assertEquals(15, nextDoc(withMissingValues, 15));+ assertEquals(Integer.MAX_VALUE, withMissingValues.ordValue());+ assertEquals(18, nextDoc(withMissingValues, 18));+ assertEquals(10, withMissingValues.ordValue());+ assertNoMoreDoc(withMissingValues, 20);+ }++ public void testNextDocWithSkippedParents() throws IOException {+ final BitSet parents = new FixedBitSet(20);+ final BitSet children = new FixedBitSet(20);+ parents.set(0);++ children.set(1);+ children.set(2);+ parents.set(3);++ children.set(4);+ parents.set(5);++ children.set(6);+ children.set(7);+ children.set(8);+ children.set(9);+ parents.set(10);++ final int[] ords = new int[20];+ Arrays.fill(ords, -1);+ ords[1] = 5;+ ords[4] = 7;+ ords[5] = 3;+ ords[8] = 10;++ final SortedDocValues naturalOrder =+ BlockJoinSelector.wrap(+ DocValues.singleton(new CannedSortedDocValues(ords)),+ BlockJoinSelector.Type.MIN,+ parents,+ toIter(children),+ false);+ assertEquals(3, naturalOrder.nextDoc());+ assertEquals(-1, naturalOrder.ordValue());+ assertEquals(5, naturalOrder.nextDoc());+ assertEquals(7, naturalOrder.ordValue());+ assertEquals(10, naturalOrder.nextDoc());+ assertEquals(-1, naturalOrder.ordValue());+ assertEquals(NO_MORE_DOCS, naturalOrder.nextDoc());++ final SortedDocValues reverseOrder =+ BlockJoinSelector.wrap(+ DocValues.singleton(new CannedSortedDocValues(ords)),+ BlockJoinSelector.Type.MAX,+ parents,+ toIter(children),+ true);+ assertEquals(3, reverseOrder.nextDoc());+ assertEquals(Integer.MAX_VALUE, reverseOrder.ordValue());+ assertEquals(5, reverseOrder.nextDoc());+ assertEquals(7, reverseOrder.ordValue());+ assertEquals(10, reverseOrder.nextDoc());+ assertEquals(Integer.MAX_VALUE, reverseOrder.ordValue());+ assertEquals(NO_MORE_DOCS, reverseOrder.nextDoc());}private static class CannedSortedDocValues extends SortedDocValues {@@ -262,7 +386,8 @@ public class TestBlockJoinSelector extends LuceneTestCase {DocValues.singleton(new CannedNumericDocValues(longs, docsWithValue)),BlockJoinSelector.Type.MIN,parents,- toIter(children));+ toIter(children),+ null);assertEquals(5, nextDoc(mins, 5));assertEquals(3, mins.longValue());assertEquals(15, nextDoc(mins, 15));@@ -274,7 +399,8 @@ public class TestBlockJoinSelector extends LuceneTestCase {DocValues.singleton(new CannedNumericDocValues(longs, docsWithValue)),BlockJoinSelector.Type.MAX,parents,- toIter(children));+ toIter(children),+ null);assertEquals(5, nextDoc(maxs, 5));assertEquals(7, maxs.longValue());assertEquals(15, nextDoc(maxs, 15));diff --git a/lucene/join/src/test/org/apache/lucene/search/join/TestBlockJoinSorting.java b/lucene/join/src/test/org/apache/lucene/search/join/TestBlockJoinSorting.javaindex 0c9c77ed7e0..52dd08f780d 100644--- a/lucene/join/src/test/org/apache/lucene/search/join/TestBlockJoinSorting.java+++ b/lucene/join/src/test/org/apache/lucene/search/join/TestBlockJoinSorting.java@@ -21,6 +21,7 @@ import java.util.List;import java.util.function.Supplier;import org.apache.lucene.document.Document;import org.apache.lucene.document.Field;+import org.apache.lucene.document.NumericDocValuesField;import org.apache.lucene.document.SortedDocValuesField;import org.apache.lucene.document.StringField;import org.apache.lucene.index.DirectoryReader;@@ -326,6 +327,284 @@ public class TestBlockJoinSorting extends LuceneTestCase {dir.close();}+ @Test+ public void testParentMissingValueNestedSorting() throws Exception {+ final Directory dir = newDirectory();+ final RandomIndexWriter w =+ new RandomIndexWriter(+ random(),+ dir,+ newIndexWriterConfig(new MockAnalyzer(random())).setMergePolicy(newLogMergePolicy()));++ // Parent A (doc 2): children with values+ List<Document> docs = new ArrayList<>();+ Document document = new Document();+ document.add(new StringField("child", "true", Field.Store.NO));+ document.add(new NumericDocValuesField("sort_val", 20));+ docs.add(document);+ document = new Document();+ document.add(new StringField("child", "true", Field.Store.NO));+ document.add(new NumericDocValuesField("sort_val", 40));+ docs.add(document);+ document = new Document();+ document.add(new StringField("__type", "parent", Field.Store.NO));+ docs.add(document);+ w.addDocuments(docs);+ w.commit();++ // Parent B (doc 5): children with values+ docs.clear();+ document = new Document();+ document.add(new StringField("child", "true", Field.Store.NO));+ document.add(new NumericDocValuesField("sort_val", 10));+ docs.add(document);+ document = new Document();+ document.add(new StringField("child", "true", Field.Store.NO));+ document.add(new NumericDocValuesField("sort_val", 30));+ docs.add(document);+ document = new Document();+ document.add(new StringField("__type", "parent", Field.Store.NO));+ docs.add(document);+ w.addDocuments(docs);++ // Parent C (doc 8): children without values+ docs.clear();+ document = new Document();+ document.add(new StringField("child", "true", Field.Store.NO));+ docs.add(document);+ document = new Document();+ document.add(new StringField("child", "true", Field.Store.NO));+ docs.add(document);+ document = new Document();+ document.add(new StringField("__type", "parent", Field.Store.NO));+ docs.add(document);+ w.addDocuments(docs);+ w.commit();++ IndexSearcher searcher = new IndexSearcher(DirectoryReader.open(w.w));+ w.close();+ BitSetProducer parentFilter =+ new QueryBitSetProducer(new TermQuery(new Term("__type", "parent")));+ CheckJoinIndex.check(searcher.getIndexReader(), parentFilter);+ BitSetProducer childFilter = new QueryBitSetProducer(new TermQuery(new Term("child", "true")));+ ToParentBlockJoinQuery query =+ new ToParentBlockJoinQuery(+ new TermQuery(new Term("child", "true")), parentFilter, ScoreMode.None);++ // Sort by ascending, with smaller missing value+ ToParentBlockJoinSortField sortField =+ new ToParentBlockJoinSortField(+ "sort_val", SortField.Type.INT, false, 5, null, parentFilter, childFilter);+ TopFieldDocs topDocs = searcher.search(query, 10, new Sort(sortField));+ assertEquals(3, topDocs.totalHits.value());+ assertEquals(3, topDocs.scoreDocs.length);+ assertEquals(8, topDocs.scoreDocs[0].doc);+ assertEquals(5, (int) ((FieldDoc) topDocs.scoreDocs[0]).fields[0]);+ assertEquals(5, topDocs.scoreDocs[1].doc);+ assertEquals(10, (int) ((FieldDoc) topDocs.scoreDocs[1]).fields[0]);+ assertEquals(2, topDocs.scoreDocs[2].doc);+ assertEquals(20, (int) ((FieldDoc) topDocs.scoreDocs[2]).fields[0]);++ // Sort by descending, with smaller missing value+ sortField =+ new ToParentBlockJoinSortField(+ "sort_val", SortField.Type.INT, true, 5, null, parentFilter, childFilter);+ topDocs = searcher.search(query, 10, new Sort(sortField));+ assertEquals(3, topDocs.totalHits.value());+ assertEquals(3, topDocs.scoreDocs.length);+ assertEquals(2, topDocs.scoreDocs[0].doc);+ assertEquals(40, (int) ((FieldDoc) topDocs.scoreDocs[0]).fields[0]);+ assertEquals(5, topDocs.scoreDocs[1].doc);+ assertEquals(30, (int) ((FieldDoc) topDocs.scoreDocs[1]).fields[0]);+ assertEquals(8, topDocs.scoreDocs[2].doc);+ assertEquals(5, (int) ((FieldDoc) topDocs.scoreDocs[2]).fields[0]);++ // Sort by ascending, with greater missing value+ sortField =+ new ToParentBlockJoinSortField(+ "sort_val", SortField.Type.INT, false, 100, null, parentFilter, childFilter);+ topDocs = searcher.search(query, 10, new Sort(sortField));+ assertEquals(3, topDocs.totalHits.value());+ assertEquals(3, topDocs.scoreDocs.length);+ assertEquals(5, topDocs.scoreDocs[0].doc);+ assertEquals(10, (int) ((FieldDoc) topDocs.scoreDocs[0]).fields[0]);+ assertEquals(2, topDocs.scoreDocs[1].doc);+ assertEquals(20, (int) ((FieldDoc) topDocs.scoreDocs[1]).fields[0]);+ assertEquals(8, topDocs.scoreDocs[2].doc);+ assertEquals(100, (int) ((FieldDoc) topDocs.scoreDocs[2]).fields[0]);++ // Sort descending with greater missing value+ sortField =+ new ToParentBlockJoinSortField(+ "sort_val", SortField.Type.INT, true, 100, null, parentFilter, childFilter);+ topDocs = searcher.search(query, 10, new Sort(sortField));+ assertEquals(3, topDocs.totalHits.value());+ assertEquals(3, topDocs.scoreDocs.length);+ assertEquals(8, topDocs.scoreDocs[0].doc);+ assertEquals(100, (int) ((FieldDoc) topDocs.scoreDocs[0]).fields[0]);+ assertEquals(2, topDocs.scoreDocs[1].doc);+ assertEquals(40, (int) ((FieldDoc) topDocs.scoreDocs[1]).fields[0]);+ assertEquals(5, topDocs.scoreDocs[2].doc);+ assertEquals(30, (int) ((FieldDoc) topDocs.scoreDocs[2]).fields[0]);++ searcher.getIndexReader().close();+ dir.close();+ }++ @Test+ public void testChildMissingValueNestedSorting() throws Exception {+ final Directory dir = newDirectory();+ final RandomIndexWriter w =+ new RandomIndexWriter(+ random(),+ dir,+ newIndexWriterConfig(new MockAnalyzer(random())).setMergePolicy(newLogMergePolicy()));++ // Parent A (doc 2): one child with value, one child without+ List<Document> docs = new ArrayList<>();+ Document document = new Document();+ document.add(new StringField("child", "true", Field.Store.NO));+ document.add(new NumericDocValuesField("sort_numeric_val", 30));+ document.add(new SortedDocValuesField("sort_string_val", new BytesRef("30")));+ docs.add(document);+ document = new Document();+ document.add(new StringField("child", "true", Field.Store.NO));+ docs.add(document);+ document = new Document();+ document.add(new StringField("__type", "parent", Field.Store.NO));+ docs.add(document);+ w.addDocuments(docs);+ w.commit();++ // Parent B (doc 5): all children with values+ docs.clear();+ document = new Document();+ document.add(new StringField("child", "true", Field.Store.NO));+ document.add(new NumericDocValuesField("sort_numeric_val", 20));+ document.add(new SortedDocValuesField("sort_string_val", new BytesRef("20")));+ docs.add(document);+ document = new Document();+ document.add(new StringField("child", "true", Field.Store.NO));+ document.add(new NumericDocValuesField("sort_numeric_val", 40));+ document.add(new SortedDocValuesField("sort_string_val", new BytesRef("40")));+ docs.add(document);+ document = new Document();+ document.add(new StringField("__type", "parent", Field.Store.NO));+ docs.add(document);+ w.addDocuments(docs);+ w.commit();++ IndexSearcher searcher = new IndexSearcher(DirectoryReader.open(w.w));+ w.close();+ BitSetProducer parentFilter =+ new QueryBitSetProducer(new TermQuery(new Term("__type", "parent")));+ CheckJoinIndex.check(searcher.getIndexReader(), parentFilter);+ BitSetProducer childFilter = new QueryBitSetProducer(new TermQuery(new Term("child", "true")));+ ToParentBlockJoinQuery query =+ new ToParentBlockJoinQuery(+ new TermQuery(new Term("child", "true")), parentFilter, ScoreMode.None);++ // Sort by ascending with a smaller missing value+ ToParentBlockJoinSortField sortField =+ new ToParentBlockJoinSortField(+ "sort_numeric_val", SortField.Type.INT, false, null, 5, parentFilter, childFilter);+ TopFieldDocs topDocs = searcher.search(query, 10, new Sort(sortField));+ assertEquals(2, topDocs.totalHits.value());+ assertEquals(2, topDocs.scoreDocs.length);+ assertEquals(2, topDocs.scoreDocs[0].doc);+ assertEquals(5, (int) ((FieldDoc) topDocs.scoreDocs[0]).fields[0]);+ assertEquals(5, topDocs.scoreDocs[1].doc);+ assertEquals(20, (int) ((FieldDoc) topDocs.scoreDocs[1]).fields[0]);++ // Sort by descending with a smaller missing value+ sortField =+ new ToParentBlockJoinSortField(+ "sort_numeric_val", SortField.Type.INT, true, null, 5, parentFilter, childFilter);+ topDocs = searcher.search(query, 10, new Sort(sortField));+ assertEquals(2, topDocs.totalHits.value());+ assertEquals(2, topDocs.scoreDocs.length);+ assertEquals(5, topDocs.scoreDocs[0].doc);+ assertEquals(40, (int) ((FieldDoc) topDocs.scoreDocs[0]).fields[0]);+ assertEquals(2, topDocs.scoreDocs[1].doc);+ assertEquals(30, (int) ((FieldDoc) topDocs.scoreDocs[1]).fields[0]);++ // Sort by ascending with a greater missing value+ sortField =+ new ToParentBlockJoinSortField(+ "sort_numeric_val", SortField.Type.INT, false, null, 50, parentFilter, childFilter);+ topDocs = searcher.search(query, 10, new Sort(sortField));+ assertEquals(2, topDocs.totalHits.value());+ assertEquals(2, topDocs.scoreDocs.length);+ assertEquals(5, topDocs.scoreDocs[0].doc);+ assertEquals(20, (int) ((FieldDoc) topDocs.scoreDocs[0]).fields[0]);+ assertEquals(2, topDocs.scoreDocs[1].doc);+ assertEquals(30, (int) ((FieldDoc) topDocs.scoreDocs[1]).fields[0]);++ // Sort by descending with a greater missing value+ sortField =+ new ToParentBlockJoinSortField(+ "sort_numeric_val", SortField.Type.INT, true, null, 50, parentFilter, childFilter);+ topDocs = searcher.search(query, 10, new Sort(sortField));+ assertEquals(2, topDocs.totalHits.value());+ assertEquals(2, topDocs.scoreDocs.length);+ assertEquals(2, topDocs.scoreDocs[0].doc);+ assertEquals(50, (int) ((FieldDoc) topDocs.scoreDocs[0]).fields[0]);+ assertEquals(5, topDocs.scoreDocs[1].doc);+ assertEquals(40, (int) ((FieldDoc) topDocs.scoreDocs[1]).fields[0]);++ // Sort by ascending with missing values first+ sortField =+ new ToParentBlockJoinSortField(+ "sort_string_val", SortField.Type.STRING, false, null, null, parentFilter, childFilter);+ topDocs = searcher.search(query, 10, new Sort(sortField));+ assertEquals(2, topDocs.totalHits.value());+ assertEquals(2, topDocs.scoreDocs.length);+ assertEquals(2, topDocs.scoreDocs[0].doc);+ assertNull(((FieldDoc) topDocs.scoreDocs[0]).fields[0]);+ assertEquals(5, topDocs.scoreDocs[1].doc);+ assertEquals("20", ((BytesRef) ((FieldDoc) topDocs.scoreDocs[1]).fields[0]).utf8ToString());++ // Sort by descending with missing values last in child level and last in+ sortField =+ new ToParentBlockJoinSortField(+ "sort_string_val",+ SortField.Type.STRING,+ false,+ null,+ SortField.STRING_LAST,+ parentFilter,+ childFilter);+ topDocs = searcher.search(query, 10, new Sort(sortField));+ assertEquals(2, topDocs.totalHits.value());+ assertEquals(2, topDocs.scoreDocs.length);+ assertEquals(5, topDocs.scoreDocs[0].doc);+ assertEquals("20", ((BytesRef) ((FieldDoc) topDocs.scoreDocs[0]).fields[0]).utf8ToString());+ assertEquals(2, topDocs.scoreDocs[1].doc);+ assertEquals("30", ((BytesRef) ((FieldDoc) topDocs.scoreDocs[1]).fields[0]).utf8ToString());++ // Sort by ascending with missing values first in child level and reverse order in parent+ sortField =+ new ToParentBlockJoinSortField(+ "sort_string_val",+ SortField.Type.STRING,+ true,+ false,+ null,+ SortField.STRING_FIRST,+ parentFilter,+ childFilter);+ topDocs = searcher.search(query, 10, new Sort(sortField));+ assertEquals(2, topDocs.totalHits.value());+ assertEquals(2, topDocs.scoreDocs.length);+ assertEquals(5, topDocs.scoreDocs[0].doc);+ assertEquals("20", ((BytesRef) ((FieldDoc) topDocs.scoreDocs[0]).fields[0]).utf8ToString());+ assertEquals(2, topDocs.scoreDocs[1].doc);+ assertNull(((FieldDoc) topDocs.scoreDocs[1]).fields[0]);++ searcher.getIndexReader().close();+ dir.close();+ }+private ToParentBlockJoinSortField notEqual(ToParentBlockJoinSortField old, Supplier<ToParentBlockJoinSortField> create) {final ToParentBlockJoinSortField newObj = create.get();