diff --git a/server/src/main/java/org/elasticsearch/search/NestedUtils.java b/server/src/main/java/org/elasticsearch/search/NestedUtils.java index c0f96f3069620..8f3b33dede0e1 100644 --- a/server/src/main/java/org/elasticsearch/search/NestedUtils.java +++ b/server/src/main/java/org/elasticsearch/search/NestedUtils.java @@ -71,20 +71,18 @@ public static Map> partitionByChildren( String currentInputName = pathFunction.apply(currentInput); assert currentInputName.startsWith(scope); - // Find all the inputs that sort before the first child, and add them to the current scope entry - while (currentInputName.compareTo(currentChild) < 0) { - output.get(scope).add(currentInput); - if (inputIterator.hasNext() == false) { - return output; - } - currentInput = inputIterator.next(); - currentInputName = pathFunction.apply(currentInput); - assert currentInputName.startsWith(scope); - } - // Iterate through all the children while (currentChild != null) { - if (currentInputName.startsWith(currentChild + ".")) { + if (currentInputName.compareTo(currentChild) < 0) { + // If we sort before the current child, then we sit in the parent scope + output.get(scope).add(currentInput); + if (inputIterator.hasNext() == false) { + return output; + } + currentInput = inputIterator.next(); + currentInputName = pathFunction.apply(currentInput); + assert currentInputName.startsWith(scope); + } else if (currentInputName.startsWith(currentChild + ".")) { // If this input sits under the current child, add it to that child scope // and then get the next input output.get(currentChild).add(currentInput); diff --git a/server/src/test/java/org/elasticsearch/search/NestedUtilsTests.java b/server/src/test/java/org/elasticsearch/search/NestedUtilsTests.java index 9805ffc76c784..e1e3fb3669417 100644 --- a/server/src/test/java/org/elasticsearch/search/NestedUtilsTests.java +++ b/server/src/test/java/org/elasticsearch/search/NestedUtilsTests.java @@ -23,6 +23,7 @@ public void testPartitionByChild() { "child1.grandchild", "child1.grandchild2", "child11", + "child12", "child2.grandchild", "frog" ); @@ -30,7 +31,7 @@ public void testPartitionByChild() { assertEquals( org.elasticsearch.core.Map.of( "", - org.elasticsearch.core.List.of("a", "b", "child11", "frog"), + org.elasticsearch.core.List.of("a", "b", "child11", "child12", "frog"), "child1", org.elasticsearch.core.List.of("child1.grandchild", "child1.grandchild2"), "child2",