You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@pinot.apache.org by GitBox <gi...@apache.org> on 2022/06/27 15:55:18 UTC

[GitHub] [pinot] gortiz opened a new pull request, #8979: optimize `order by sorted ASC, unsorted` case

gortiz opened a new pull request, #8979:
URL: https://github.com/apache/pinot/pull/8979

   This is a quite large PR that should be marked as a Draft. The improvements included here are important, but I also have to change several APIs and there may be better ways to do it. In fact it is not mandatory to change these APIs, but most of them try to add order in a bunch of casting and assumptions that were  I find very confusing the abusive usage of casting and sorting assumptions that were scattered in the code. I think they are now clearer, but I understand that it is a subjective issue. The code is not properly tested and that is something I would like to solve before merging this.
   
   The current order-by code have some inefficiencies that may not be trivial to fix, but will significantly increase the performance. I discovered that by reading #8837, but this PR doesn't fix the performance problem detected in that issue. Instead, it is focused on queries like:
   
   ```
   SELECT whatever FROM table WHERE whatever ORDER BY <some_sorted_column> ASC, <some_unsorted_column_or_expression> LIMIT <some_value> OFFSET <some_other_value>
   ```
   
   As proved by the included benchmark, the performance gain is huge:
   
   ```
   
   Benchmark                      (_numRows)  (_partialOrderBy)  (_primaryRepetitions)                                                                                   (_query)  (_scenario)  Mode  Cnt   Score   Error  Units
   BenchmarkOrderByQueries.query     1500000               true                      1  SELECT SORTED_COL FROM MyTable ORDER BY SORTED_COL, LOW_CARDINALITY_STRING_COL LIMIT 1052     EXP(0.5)  avgt    5   0.992 ± 0.041  ms/op
   BenchmarkOrderByQueries.query     1500000               true                   1000  SELECT SORTED_COL FROM MyTable ORDER BY SORTED_COL, LOW_CARDINALITY_STRING_COL LIMIT 1052     EXP(0.5)  avgt    5   1.588 ± 0.128  ms/op
   BenchmarkOrderByQueries.query     1500000              false                      1  SELECT SORTED_COL FROM MyTable ORDER BY SORTED_COL, LOW_CARDINALITY_STRING_COL LIMIT 1052     EXP(0.5)  avgt    5  62.553 ± 0.606  ms/op
   BenchmarkOrderByQueries.query     1500000              false                   1000  SELECT SORTED_COL FROM MyTable ORDER BY SORTED_COL, LOW_CARDINALITY_STRING_COL LIMIT 1052     EXP(0.5)  avgt    5  59.222 ± 5.772  ms/op
   ```
   
   Before this PR, this kind of queries were executed in `O(SlogL)` where S is the number of rows in the segment and L the effective limit (calculated as `min(max_limit, offeset + limit)`). That is a waste which is more evident in degraded scenarios like having a segment that only contains a rows that are all distinct in the sorting column. In that case, we the query above should be executed in `O(L)`, as we only need to read the first L rows that match the predicate and return them because they would be already sorted. Of course that is not valid in the general case, but we can use the fact data is already partially sorted by `<some_sorted_column>`, so we don't need to read the whole segment.
   
   What this PR does is to determine how many already sorted expressions are a _prefix_ in the list of order-by expressions. In other words: this optimization is only applied if there is a number `0 < i < orderByExpr.length : orderByExpr[i] is sorted`. Where `is sorted` means that the expression is either a constant (which is quite useless, but still) or if it is a column that is sorted and the order is ASC. Pinot already has an optimization when that `i` is exactly equal to `orderByExpr.length`. This PR adds another one when `0 < i < orderByExpr.length`.
   
   What this PR does is to partition the segment into P [mathematical partitions](https://en.wikipedia.org/wiki/Partition_of_a_set#:~:text=In%20mathematics%2C%20a%20partition%20of,included%20in%20exactly%20one%20subset.) where two rows are in the same partition if and only if they the value of their _prefix_ columns is equal.
   
   As we know that these _prefix_ of expressions is sorted, we know that the rows of each partition are going to be consecutives. These partitions will be also sorted. Which means that partitions that contains smaller elements (compared with the _prefix_ of sorted order by expressions) are going to be found before than any other partition that is higher.
   
   Therefore, we can add the results to an unbound List and stop when:
   
   - Either there are no more rows that matched the predicate
   - Or the List has more than L elements AND there are no more elements in the partition.
   
   As all elements in the same partition are consecutives, we can easily know that a partition has finished when a value that doesn't belong to that partition is found.
   
   Once we stop, we just need to sort (using all order-by expressions) the List (whose size will lower or equal to L + size of the last included partition) and return the first L elements there.
   
   There is another interesting property: as elements of different partitions are already sorted, we don't need to sort the whole List once we finish. We can simply sort each partition when a new one is found, reducing the cost from `O(SlogL)` to `O(pPlog(P))` where P is the size of the bigger partition included in the result and p the number of partitions included.
   
   This optimization is ideal if the number of partitions is very high (close to the number of rows), as the cost will tend to be `O(L)`. If the number of partitions is very small, the cost is tend to be `O(Slog(L))`, which is the same we had before.
   
   Right now the optimization is disabled by default and have to be activated with a new option called partial-order-by, which is used in the benchmark to compare results.
    


-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] gortiz commented on pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
gortiz commented on PR #8979:
URL: https://github.com/apache/pinot/pull/8979#issuecomment-1250639244

   Do you think it makes sense to keep the descending optimization or it would be better to just remove it and wait until we have descending iterators?


-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] siddharthteotia commented on pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
siddharthteotia commented on PR #8979:
URL: https://github.com/apache/pinot/pull/8979#issuecomment-1247719106

   Seems like a great optimization. Any plans of resuming this ? 


-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] gortiz commented on a diff in pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
gortiz commented on code in PR #8979:
URL: https://github.com/apache/pinot/pull/8979#discussion_r982027120


##########
pinot-core/src/main/java/org/apache/pinot/core/operator/combine/MinMaxValueBasedSelectionOrderByCombineOperator.java:
##########
@@ -211,30 +211,51 @@ protected void processSegments() {
           ((AcquireReleaseColumnsSegmentOperator) operator).release();
         }
       }
-      PriorityQueue<Object[]> selectionResult = (PriorityQueue<Object[]>) resultsBlock.getRows();
-      if (selectionResult != null && selectionResult.size() == _numRowsToKeep) {
-        // Segment result has enough rows, update the boundary value
-        assert selectionResult.peek() != null;
-        Comparable segmentBoundaryValue = (Comparable) selectionResult.peek()[0];
-        if (boundaryValue == null) {
-          boundaryValue = segmentBoundaryValue;
-        } else {
-          if (asc) {
-            if (segmentBoundaryValue.compareTo(boundaryValue) < 0) {
-              boundaryValue = segmentBoundaryValue;
-            }
-          } else {
-            if (segmentBoundaryValue.compareTo(boundaryValue) > 0) {
-              boundaryValue = segmentBoundaryValue;
-            }
-          }
-        }
+      Collection<Object[]> rows = resultsBlock.getRows();
+      if (rows != null && rows.size() >= _numRowsToKeep) {
+        boundaryValue = updateBoundaryValue(boundaryValue, extractBoundaryValue(rows), asc);
       }
       threadBoundaryValue = boundaryValue;
       _blockingQueue.offer(resultsBlock);
     }
   }
 
+  private Comparable extractBoundaryValue(Collection<Object[]> rows) {
+    if (rows instanceof PriorityQueue) {
+      PriorityQueue<Object[]> selectionResult = (PriorityQueue<Object[]>) rows;
+      assert selectionResult.peek() != null;
+      // at this point, priority queues are sorted in the inverse order
+      return (Comparable) selectionResult.peek()[0];
+    }
+    List<Object[]> selectionResult;
+    if (rows instanceof List) {
+      selectionResult = (List<Object[]>) rows;
+    } else {
+      LOGGER.warn("Selection result stored in an unexpected data structure of type {}. A copy is needed",

Review Comment:
   I mean, right now rows are always List or PriorityQueue. By specifying that in the constructor, we make it clear. Ideally we should try to move to something closer to my alternative solution with two subclasses, as it was even clearer and type safe in the usage side (ie in case we need to add a `SelectionResultsBlock` whose rows are a set, then the compiler would tell us that we have to do plan how to get the `extractBoundaryValue` in this new class).
   
   But yeah, we can also do what you propose. Also, I think list should also fail if the instance doesn't have a Comparator. Semantically, if there is no comparator, the list doesn't have to be ordered.



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] gortiz commented on pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
gortiz commented on PR #8979:
URL: https://github.com/apache/pinot/pull/8979#issuecomment-1180533867

   I've fixed one bug detected by the integration tests (it is an error to create a PriorityQueue with 0 elements) but I wasn't able to fix the second one because I don't actually know why does it time out.


-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] gortiz commented on a diff in pull request #8979: optimize `order by sorted ASC, unsorted` case

Posted by GitBox <gi...@apache.org>.
gortiz commented on code in PR #8979:
URL: https://github.com/apache/pinot/pull/8979#discussion_r913454116


##########
pinot-core/src/main/java/org/apache/pinot/core/operator/query/SelectionPartiallyOrderedByOperator.java:
##########
@@ -0,0 +1,303 @@
+/**
+ * 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.pinot.core.operator.query;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+import javax.annotation.Nullable;
+import org.apache.pinot.common.request.context.ExpressionContext;
+import org.apache.pinot.common.request.context.OrderByExpressionContext;
+import org.apache.pinot.common.utils.DataSchema;
+import org.apache.pinot.core.common.BlockValSet;
+import org.apache.pinot.core.common.Operator;
+import org.apache.pinot.core.common.RowBasedBlockValueFetcher;
+import org.apache.pinot.core.operator.BaseOperator;
+import org.apache.pinot.core.operator.ExecutionStatistics;
+import org.apache.pinot.core.operator.blocks.IntermediateResultsBlock;
+import org.apache.pinot.core.operator.blocks.TransformBlock;
+import org.apache.pinot.core.operator.transform.TransformOperator;
+import org.apache.pinot.core.operator.transform.TransformResultMetadata;
+import org.apache.pinot.core.query.request.context.QueryContext;
+import org.apache.pinot.core.query.selection.SelectionOperatorUtils;
+import org.apache.pinot.segment.spi.IndexSegment;
+
+
+/**
+ * An operator for order-by queries that are partially sorted over the sorting keys.
+ */
+public class SelectionPartiallyOrderedByOperator extends BaseOperator<IntermediateResultsBlock> {
+
+  private static final String EXPLAIN_NAME = "SELECT_PARTIAL_ORDERBY";
+
+  private final IndexSegment _indexSegment;
+
+  // Deduped order-by expressions followed by output expressions from SelectionOperatorUtils.extractExpressions()
+  private final List<ExpressionContext> _expressions;
+  private final List<ExpressionContext> _alreadySorted;
+  private final List<ExpressionContext> _toSort;
+
+  private final TransformOperator _transformOperator;
+  private final List<OrderByExpressionContext> _orderByExpressions;
+  private final TransformResultMetadata[] _expressionsMetadata;
+  private final int _numRowsToKeep;
+  private final PartiallySortedListBuilder _sorter;
+
+  private int _numDocsScanned = 0;
+  private long _numEntriesScannedPostFilter = 0;
+  private boolean _used = false;
+  private Comparator<Object[]> _comparator;
+
+  public SelectionPartiallyOrderedByOperator(IndexSegment indexSegment, QueryContext queryContext,
+      List<ExpressionContext> expressions, TransformOperator transformOperator, int sortedExpr) {
+    Preconditions.checkArgument(sortedExpr > 0,
+        "This operator should not be used when sorting expressions doesn't start with sorted expressions");
+    _indexSegment = indexSegment;
+    _expressions = expressions;
+    _transformOperator = transformOperator;
+
+    _orderByExpressions = queryContext.getOrderByExpressions();
+    assert _orderByExpressions != null;
+    int numOrderByExpressions = _orderByExpressions.size();
+
+    _alreadySorted = expressions.subList(0, sortedExpr);
+    _toSort = expressions.subList(sortedExpr, numOrderByExpressions);
+
+    Preconditions.checkArgument(!_toSort.isEmpty(),
+        "This operator should not be used when all sorting expressions are sorted. "
+            + "Use %s instead", SelectionOrderByOperator.class.getName());
+
+    _expressionsMetadata = new TransformResultMetadata[_expressions.size()];
+    for (int i = 0; i < _expressionsMetadata.length; i++) {
+      ExpressionContext expression = _expressions.get(i);
+      _expressionsMetadata[i] = _transformOperator.getResultMetadata(expression);
+    }
+
+    _numRowsToKeep = queryContext.getOffset() + queryContext.getLimit();
+
+    int expectedSize = Math.min(_numRowsToKeep * 2, SelectionOperatorUtils.MAX_ROW_HOLDER_INITIAL_CAPACITY);
+    Comparator<Object[]> sortedComparator =
+        SelectionOrderByOperator.getComparator(_orderByExpressions, _expressionsMetadata, true, 0, sortedExpr);
+    Comparator<Object[]> unsortedComparator =
+        SelectionOrderByOperator.getComparator(_orderByExpressions, _expressionsMetadata, true, sortedExpr,
+            numOrderByExpressions);
+    _sorter = new PartiallySortedListBuilder(expectedSize, sortedComparator, unsortedComparator);
+    _comparator = SelectionOrderByOperator.getComparator(_orderByExpressions, _expressionsMetadata, false);
+  }
+
+  @Override
+  public List<Operator> getChildOperators() {
+    return Collections.singletonList(_transformOperator);
+  }
+
+  @Override
+  protected IntermediateResultsBlock getNextBlock() {
+    if (!_used) {
+      _used = true;
+      fetch();
+
+      DataSchema dataSchema = createDataSchema();
+
+      return new IntermediateResultsBlock.ListSelection(dataSchema, _sorter.build(), _comparator);
+    }
+    return null;
+  }
+
+  private DataSchema createDataSchema() {
+
+    int numExpressions = _expressions.size();
+
+    // Create the data schema
+    String[] columnNames = new String[numExpressions];
+    DataSchema.ColumnDataType[] columnDataTypes = new DataSchema.ColumnDataType[numExpressions];
+    for (int i = 0; i < columnNames.length; i++) {
+      columnNames[i] = _expressions.get(i).toString();
+    }
+    for (int i = 0; i < numExpressions; i++) {
+      TransformResultMetadata expressionMetadata = _expressionsMetadata[i];
+      columnDataTypes[i] =
+          DataSchema.ColumnDataType.fromDataType(expressionMetadata.getDataType(), expressionMetadata.isSingleValue());
+    }
+    return new DataSchema(columnNames, columnDataTypes);
+  }
+
+  /**
+   * Fetches the rows that are needed into {@link #_sorter} and updated the metrics.
+   *
+   * The sorter can still be used.
+   */
+  private void fetch() {
+    int numExpressions = _expressions.size();
+    BlockValSet[] blockValSets = new BlockValSet[numExpressions];
+
+    TransformBlock transformBlock;
+    int numColumnsProjected = _transformOperator.getNumColumnsProjected();
+    try {
+      while ((transformBlock = _transformOperator.nextBlock()) != null) {
+        for (int i = 0; i < numExpressions; i++) {
+          ExpressionContext expression = _expressions.get(i);
+          blockValSets[i] = transformBlock.getBlockValueSet(expression);
+        }
+        RowBasedBlockValueFetcher blockValueFetcher = new RowBasedBlockValueFetcher(blockValSets);
+        int numDocsFetched = transformBlock.getNumDocs();
+        _numDocsScanned += numDocsFetched;
+        for (int i = 0; i < numDocsFetched; i++) {
+          boolean newBlock = _sorter.add(blockValueFetcher.getRow(i));
+          if (newBlock && _sorter.sortedSize() >= _numRowsToKeep) {
+            // We changed to a new section to ordered sorted values and we have more values than required.
+            // Therefore, we can stop the execution here.
+            return;
+          }
+        }
+      }
+    } finally {
+      _numEntriesScannedPostFilter = (long) _numDocsScanned * numColumnsProjected;
+    }
+  }
+
+  @Override
+  public String toExplainString() {
+    StringBuilder sb = new StringBuilder(EXPLAIN_NAME);
+
+    sb.append("(sortedList: ");
+    concatList(sb, _alreadySorted);
+
+    sb.append(", unsortedList: ");
+    concatList(sb, _toSort);
+
+    sb.append(", rest: ");
+    concatList(sb, _expressions.subList(_alreadySorted.size() + _toSort.size(), _expressions.size()));
+
+    sb.append(')');
+    return sb.toString();
+  }
+
+  private void concatList(StringBuilder sb, List<?> list) {
+    sb.append('(');
+    Iterator<?> it = list.iterator();
+    if (it.hasNext()) {
+      sb.append(it.next());
+      while (it.hasNext()) {
+        sb.append(", ").append(it.next());
+      }
+    }
+    sb.append(')');
+  }
+
+  @Override
+  public ExecutionStatistics getExecutionStatistics() {
+    long numEntriesScannedInFilter = _transformOperator.getExecutionStatistics().getNumEntriesScannedInFilter();
+    int numTotalDocs = _indexSegment.getSegmentMetadata().getTotalDocs();
+    return new ExecutionStatistics(_numDocsScanned, numEntriesScannedInFilter, _numEntriesScannedPostFilter,
+        numTotalDocs);
+  }
+
+  /**
+   * A private class used to build a sorted list by adding partially sorted data.
+   *
+   * Specifically, this class has been designed to receive successive calls to {@link #add(Object[])} follow by a single
+   * call to {@link #build()}. Once this method is called, the behavior of this object is undefined and therefore it
+   * should not be used.
+   *
+   * Rows must be inserted in ascending order accordingly to the partial order specified by {@link #_sortedComparator}.
+   * This comparator will define <i>partitions</i> of rows. All the rows in the same partition same are considered equal
+   * by that comparator.
+   *
+   * There is a second comparator called {@link #_unsortedComparator} that is used to sort rows inside each partition.
+   * When calling {@link #add(Object[])} with a row that doesn't belong to the current partition, a new one is started
+   * and the previous one is sorted. Therefore, this object maintains the invariant that at any moment there are at
+   * least {@link #sortedSize()} elements that are completely sorted, which means that no matter which elements are
+   * added after that, these elements are going to be smallest.
+   */
+  private static class PartiallySortedListBuilder {
+    private final ArrayList<Object[]> _rows;
+    private final Comparator<Object[]> _sortedComparator;
+    private final Comparator<Object[]> _unsortedComparator;
+
+    public PartiallySortedListBuilder(int expectedSize, Comparator<Object[]> sortedComparator,
+        Comparator<Object[]> unsortedComparator) {
+      _rows = new ArrayList<>(expectedSize);
+      _sortedComparator = sortedComparator;
+      _unsortedComparator = unsortedComparator;
+    }
+
+    @Nullable
+    private Object[] _lastBlockRow;
+    private int _lastSorted;
+
+    /**
+     * Adds the given row to this object. The new column must be equal or higher than the last added row in relation to
+     * {@link #_sortedComparator}.
+     *
+     * @param row The row to add. The values of the already sorted columns must be equal or higher than the last added
+     *           row, if any.
+     * @return true if and only if the previous block was closed.
+     */
+    boolean add(Object[] row) {
+      boolean result;
+      if (_lastBlockRow == null) {
+        _lastSorted = 0;
+        _lastBlockRow = row;
+        result = false;
+      } else {
+        int cmp = _sortedComparator.compare(_lastBlockRow, row);
+        assert cmp >= 0 : "Row " + Arrays.toString(row) + " is lower than previously added row"

Review Comment:
   This is more a "computable comment" than something I would like to evaluate every time one element is being added.



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] gortiz commented on pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
gortiz commented on PR #8979:
URL: https://github.com/apache/pinot/pull/8979#issuecomment-1234453883

   These are the results I'm having with the last version. It seems that the descending version is slower than in the first attempts. It may be due to the incorrect behaviors that were detected by @Jackie-Jiang, but it may also be some implementation inefficiencies. I'll will try to study that a bit
   
   ```
   Benchmark                                    (_numRows)  (_primaryRepetitions)  (_scenario)  (_skipOptimization)  Mode  Cnt    Score    Error  Units
   BenchmarkOrderByQueries.sortedAsc               1500000                      1     EXP(0.5)                 true  avgt    5   36.699 ±  1.108  ms/op
   BenchmarkOrderByQueries.sortedAsc               1500000                      1     EXP(0.5)                false  avgt    5    1.349 ±  0.091  ms/op
   BenchmarkOrderByQueries.sortedAsc               1500000                   1000     EXP(0.5)                 true  avgt    5   29.210 ±  1.966  ms/op
   BenchmarkOrderByQueries.sortedAsc               1500000                   1000     EXP(0.5)                false  avgt    5    0.421 ±  0.032  ms/op
   BenchmarkOrderByQueries.sortedAscPartially      1500000                      1     EXP(0.5)                 true  avgt    5   85.217 ± 11.162  ms/op
   BenchmarkOrderByQueries.sortedAscPartially      1500000                      1     EXP(0.5)                false  avgt    5    1.460 ±  0.261  ms/op
   BenchmarkOrderByQueries.sortedAscPartially      1500000                   1000     EXP(0.5)                 true  avgt    5   81.292 ± 25.354  ms/op
   BenchmarkOrderByQueries.sortedAscPartially      1500000                   1000     EXP(0.5)                false  avgt    5    2.086 ±  0.500  ms/op
   BenchmarkOrderByQueries.sortedDesc              1500000                      1     EXP(0.5)                 true  avgt    5  352.122 ± 37.947  ms/op
   BenchmarkOrderByQueries.sortedDesc              1500000                      1     EXP(0.5)                false  avgt    5   14.572 ±  0.771  ms/op
   BenchmarkOrderByQueries.sortedDesc              1500000                   1000     EXP(0.5)                 true  avgt    5  283.754 ± 12.982  ms/op
   BenchmarkOrderByQueries.sortedDesc              1500000                   1000     EXP(0.5)                false  avgt    5    9.702 ±  2.364  ms/op
   BenchmarkOrderByQueries.sortedDescPartially     1500000                      1     EXP(0.5)                 true  avgt    5  443.211 ± 53.459  ms/op
   BenchmarkOrderByQueries.sortedDescPartially     1500000                      1     EXP(0.5)                false  avgt    5   71.102 ± 64.952  ms/op
   BenchmarkOrderByQueries.sortedDescPartially     1500000                   1000     EXP(0.5)                 true  avgt    5  623.616 ± 45.834  ms/op
   BenchmarkOrderByQueries.sortedDescPartially     1500000                   1000     EXP(0.5)                false  avgt    5   92.627 ±  9.508  ms/op
   
   ```
   


-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] gortiz commented on pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
gortiz commented on PR #8979:
URL: https://github.com/apache/pinot/pull/8979#issuecomment-1185614439

   I think I finally found why the test was failing. It was due to a `cmp >= 0` assertion that should be `cmp <= 0`. The reason that made it very hard to find the problem is that `BaseCombineOperator` is not prepared to catch `Errors`, so the task at the server just failed without printing any log and as a result the broker didn't receive a response, so the error shown in the broker was that some server didn't answer.
   
   Things to know about:
   - Pinot may not log `AssertionErrors`, so it is better to do not use `assert` expressions
   - We may or may not want to log in case we receive an error. As I don't know what do we want to do in that case, I've just changed my code to throw an `ArgumentException`.


-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] gortiz commented on pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
gortiz commented on PR #8979:
URL: https://github.com/apache/pinot/pull/8979#issuecomment-1233094899

   I applied several suggested changes, but there are a lot of conflicts with merge. I'm planning to solve them tomorrow and given that we decided to do not apply my change on `IntermediateResultsBlock`, I think it may be easier to apply the operator changes in a new branch (which may be this PR, but doing some rewrite of the history)


-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] gortiz commented on pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
gortiz commented on PR #8979:
URL: https://github.com/apache/pinot/pull/8979#issuecomment-1261175557

   New results with the last improvements suggested by @Jackie-Jiang:
   
   ```
   
   Benchmark                                        (_limit)  (_numRows)  (_orderByAlgorithm)  (_primaryRepetitions)  Mode  Cnt     Score     Error  Units
   BenchmarkOrderByDescQueries.sortedDesc                101     1500000                naive                      1  avgt    5   212.764 ±  22.368  ms/op
   BenchmarkOrderByDescQueries.sortedDesc                101     1500000                naive                   1000  avgt    5    46.058 ±   2.962  ms/op
   BenchmarkOrderByDescQueries.sortedDesc                101     1500000                naive                   5000  avgt    5    33.271 ±   5.227  ms/op
   BenchmarkOrderByDescQueries.sortedDesc                101     1500000                 null                      1  avgt    5    10.628 ±   1.358  ms/op
   BenchmarkOrderByDescQueries.sortedDesc                101     1500000                 null                   1000  avgt    5     7.170 ±   0.565  ms/op
   BenchmarkOrderByDescQueries.sortedDesc                101     1500000                 null                   5000  avgt    5     7.007 ±   0.536  ms/op
   BenchmarkOrderByDescQueries.sortedDesc              10100     1500000                naive                      1  avgt    5   502.738 ±  12.277  ms/op
   BenchmarkOrderByDescQueries.sortedDesc              10100     1500000                naive                   1000  avgt    5   461.401 ±  19.661  ms/op
   BenchmarkOrderByDescQueries.sortedDesc              10100     1500000                naive                   5000  avgt    5   381.431 ±   9.761  ms/op
   BenchmarkOrderByDescQueries.sortedDesc              10100     1500000                 null                      1  avgt    5    50.491 ±   6.376  ms/op
   BenchmarkOrderByDescQueries.sortedDesc              10100     1500000                 null                   1000  avgt    5    38.933 ±   5.553  ms/op
   BenchmarkOrderByDescQueries.sortedDesc              10100     1500000                 null                   5000  avgt    5    33.065 ±   1.795  ms/op
   BenchmarkOrderByDescQueries.sortedDesc             101000     1500000                naive                      1  avgt    5   637.033 ±  11.965  ms/op
   BenchmarkOrderByDescQueries.sortedDesc             101000     1500000                naive                   1000  avgt    5   528.267 ±  22.312  ms/op
   BenchmarkOrderByDescQueries.sortedDesc             101000     1500000                naive                   5000  avgt    5   527.354 ±  45.383  ms/op
   BenchmarkOrderByDescQueries.sortedDesc             101000     1500000                 null                      1  avgt    5    52.356 ±   3.886  ms/op
   BenchmarkOrderByDescQueries.sortedDesc             101000     1500000                 null                   1000  avgt    5    47.692 ±   4.879  ms/op
   BenchmarkOrderByDescQueries.sortedDesc             101000     1500000                 null                   5000  avgt    5    37.208 ±  12.339  ms/op
   BenchmarkOrderByDescQueries.sortedDescPartially       101     1500000                naive                      1  avgt    5   265.343 ±  16.922  ms/op
   BenchmarkOrderByDescQueries.sortedDescPartially       101     1500000                naive                   1000  avgt    5   184.912 ±   8.529  ms/op
   BenchmarkOrderByDescQueries.sortedDescPartially       101     1500000                naive                   5000  avgt    5   105.262 ±   5.114  ms/op
   BenchmarkOrderByDescQueries.sortedDescPartially       101     1500000                 null                      1  avgt    5    53.949 ±   4.434  ms/op
   BenchmarkOrderByDescQueries.sortedDescPartially       101     1500000                 null                   1000  avgt    5    89.993 ±  31.135  ms/op
   BenchmarkOrderByDescQueries.sortedDescPartially       101     1500000                 null                   5000  avgt    5    81.264 ±   5.733  ms/op
   BenchmarkOrderByDescQueries.sortedDescPartially     10100     1500000                naive                      1  avgt    5   472.145 ±  16.579  ms/op
   BenchmarkOrderByDescQueries.sortedDescPartially     10100     1500000                naive                   1000  avgt    5   757.835 ±  51.859  ms/op
   BenchmarkOrderByDescQueries.sortedDescPartially     10100     1500000                naive                   5000  avgt    5   762.778 ±  15.560  ms/op
   BenchmarkOrderByDescQueries.sortedDescPartially     10100     1500000                 null                      1  avgt    5   100.263 ±  18.075  ms/op
   BenchmarkOrderByDescQueries.sortedDescPartially     10100     1500000                 null                   1000  avgt    5   104.300 ±   3.241  ms/op
   BenchmarkOrderByDescQueries.sortedDescPartially     10100     1500000                 null                   5000  avgt    5   103.599 ±   9.995  ms/op
   BenchmarkOrderByDescQueries.sortedDescPartially    101000     1500000                naive                      1  avgt    5   638.340 ±  62.591  ms/op
   BenchmarkOrderByDescQueries.sortedDescPartially    101000     1500000                naive                   1000  avgt    5   941.473 ± 139.675  ms/op
   BenchmarkOrderByDescQueries.sortedDescPartially    101000     1500000                naive                   5000  avgt    5  1030.555 ±  12.376  ms/op
   BenchmarkOrderByDescQueries.sortedDescPartially    101000     1500000                 null                      1  avgt    5   118.147 ±   8.753  ms/op
   BenchmarkOrderByDescQueries.sortedDescPartially    101000     1500000                 null                   1000  avgt    5   113.684 ±   9.346  ms/op
   BenchmarkOrderByDescQueries.sortedDescPartially    101000     1500000                 null                   5000  avgt    5   121.790 ±   7.841  ms/op
   ```


-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] gortiz commented on pull request #8979: optimize `order by sorted ASC, unsorted` case

Posted by GitBox <gi...@apache.org>.
gortiz commented on PR #8979:
URL: https://github.com/apache/pinot/pull/8979#issuecomment-1178869657

   I've added some changes to also optimize the `order by sorted_col DESC (, more columns)*` case. The results are even better in this case because the priority queue is quite less effective in the desc case, as it has each of the N insertions has to move the whole queue.
   
   The benchmarks now are:
   
   sortedAsc:
   ```
           SELECT SORTED_COL
               FROM MyTable
               ORDER BY SORTED_COL ASC
               LIMIT 1052
               option(partial-order-by= + _partialOrderBy + )
   ```
   
   sortedAscPartially
   ```
           SELECT SORTED_COL
               FROM MyTable
               ORDER BY SORTED_COL ASC, LOW_CARDINALITY_STRING_COL
               LIMIT 1052
               option(partial-order-by= + _partialOrderBy + )
   ```
   
   sortedDesc
   ```
           SELECT SORTED_COL
               FROM MyTable
               ORDER BY SORTED_COL DESC
               LIMIT 1052
               option(partial-order-by= + _partialOrderBy + )
   ```
   sortedDescPartially
   ```
           SELECT SORTED_COL
               FROM MyTable
               ORDER BY SORTED_COL DESC, LOW_CARDINALITY_STRING_COL
               LIMIT 1052
               option(partial-order-by= + _partialOrderBy + )
   ```
   
   ```
   Benchmark                                    (_numRows)  (_partialOrderBy)  (_primaryRepetitions)  (_scenario)  Mode  Cnt    Score    Error  Units
   BenchmarkOrderByQueries.sortedAsc               1500000               true                      1     EXP(0.5)  avgt    5    0.982 ±  0.041  ms/op
   BenchmarkOrderByQueries.sortedAsc               1500000               true                   1000     EXP(0.5)  avgt    5    0.330 ±  0.032  ms/op
   BenchmarkOrderByQueries.sortedAsc               1500000              false                      1     EXP(0.5)  avgt    5    0.993 ±  0.040  ms/op
   BenchmarkOrderByQueries.sortedAsc               1500000              false                   1000     EXP(0.5)  avgt    5    0.329 ±  0.011  ms/op
   BenchmarkOrderByQueries.sortedAscPartially      1500000               true                      1     EXP(0.5)  avgt    5    1.108 ±  0.047  ms/op
   BenchmarkOrderByQueries.sortedAscPartially      1500000               true                   1000     EXP(0.5)  avgt    5    2.280 ±  0.156  ms/op
   BenchmarkOrderByQueries.sortedAscPartially      1500000              false                      1     EXP(0.5)  avgt    5   82.985 ±  2.531  ms/op
   BenchmarkOrderByQueries.sortedAscPartially      1500000              false                   1000     EXP(0.5)  avgt    5   86.798 ± 14.747  ms/op
   BenchmarkOrderByQueries.sortedDesc              1500000               true                      1     EXP(0.5)  avgt    5    1.646 ±  0.213  ms/op
   BenchmarkOrderByQueries.sortedDesc              1500000               true                   1000     EXP(0.5)  avgt    5    1.740 ±  0.162  ms/op
   BenchmarkOrderByQueries.sortedDesc              1500000              false                      1     EXP(0.5)  avgt    5  314.980 ± 14.875  ms/op
   BenchmarkOrderByQueries.sortedDesc              1500000              false                   1000     EXP(0.5)  avgt    5  253.157 ± 10.557  ms/op
   BenchmarkOrderByQueries.sortedDescPartially     1500000               true                      1     EXP(0.5)  avgt    5    2.025 ±  0.113  ms/op
   BenchmarkOrderByQueries.sortedDescPartially     1500000               true                   1000     EXP(0.5)  avgt    5    5.113 ±  0.717  ms/op
   BenchmarkOrderByQueries.sortedDescPartially     1500000              false                      1     EXP(0.5)  avgt    5  410.110 ± 28.135  ms/op
   BenchmarkOrderByQueries.sortedDescPartially     1500000              false                   1000     EXP(0.5)  avgt    5  583.025 ± 23.282  ms/op
   ```
   I still need to add tests to verify the correctness, which is in what I'm going to be focused early next week.


-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] Jackie-Jiang commented on a diff in pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
Jackie-Jiang commented on code in PR #8979:
URL: https://github.com/apache/pinot/pull/8979#discussion_r955319247


##########
pinot-core/src/main/java/org/apache/pinot/core/common/NullableRowBasedBlockValueFetcher.java:
##########
@@ -0,0 +1,53 @@
+/**
+ * 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.pinot.core.common;
+
+import org.roaringbitmap.RoaringBitmap;
+
+
+public class NullableRowBasedBlockValueFetcher extends RowBasedBlockValueFetcher {

Review Comment:
   Checked all the usages of `RowBasedBlockValueFetcher`, and we should just change it to take the boolean `nullHandlingEnabled`. No need to make a sub-class for it



##########
pinot-core/src/main/java/org/apache/pinot/core/plan/SelectionPlanNode.java:
##########
@@ -50,67 +52,113 @@ public Operator<IntermediateResultsBlock> run() {
     List<ExpressionContext> expressions = SelectionOperatorUtils.extractExpressions(_queryContext, _indexSegment);
     int limit = _queryContext.getLimit();
 
-    if (limit > 0) {
-      List<OrderByExpressionContext> orderByExpressions = _queryContext.getOrderByExpressions();
-      if (orderByExpressions == null) {
-        // Selection only
-        TransformOperator transformOperator = new TransformPlanNode(_indexSegment, _queryContext, expressions,
-            Math.min(limit, DocIdSetPlanNode.MAX_DOC_PER_CALL)).run();
-        return new SelectionOnlyOperator(_indexSegment, _queryContext, expressions, transformOperator);
-      } else {
-        // Selection order-by
-        if (isAllOrderByColumnsSorted(orderByExpressions)) {
-          // All order-by columns are sorted, no need to sort the records
-          TransformOperator transformOperator = new TransformPlanNode(_indexSegment, _queryContext, expressions,
-              Math.min(limit + _queryContext.getOffset(), DocIdSetPlanNode.MAX_DOC_PER_CALL)).run();
-          return new SelectionOrderByOperator(_indexSegment, _queryContext, expressions, transformOperator, true);
-        } else if (orderByExpressions.size() == expressions.size()) {
-          // All output expressions are ordered
-          TransformOperator transformOperator =
-              new TransformPlanNode(_indexSegment, _queryContext, expressions, DocIdSetPlanNode.MAX_DOC_PER_CALL).run();
-          return new SelectionOrderByOperator(_indexSegment, _queryContext, expressions, transformOperator, false);
-        } else {
-          // Not all output expressions are ordered, only fetch the order-by expressions and docId to avoid the
-          // unnecessary data fetch
-          List<ExpressionContext> expressionsToTransform = new ArrayList<>(orderByExpressions.size());
-          for (OrderByExpressionContext orderByExpression : orderByExpressions) {
-            expressionsToTransform.add(orderByExpression.getExpression());
-          }
-          TransformOperator transformOperator =
-              new TransformPlanNode(_indexSegment, _queryContext, expressionsToTransform,
-                  DocIdSetPlanNode.MAX_DOC_PER_CALL).run();
-          return new SelectionOrderByOperator(_indexSegment, _queryContext, expressions, transformOperator, false);
-        }
-      }
-    } else {
+    if (limit == 0) {
       // Empty selection (LIMIT 0)
       TransformOperator transformOperator = new TransformPlanNode(_indexSegment, _queryContext, expressions, 0).run();
       return new EmptySelectionOperator(_indexSegment, expressions, transformOperator);
     }
+    List<OrderByExpressionContext> orderByExpressions = _queryContext.getOrderByExpressions();
+
+    if (orderByExpressions == null) {
+      // Selection only
+      // ie: SELECT ... FROM Table WHERE ... LIMIT 10
+      int actualLimit = Math.min(limit, DocIdSetPlanNode.MAX_DOC_PER_CALL);

Review Comment:
   `actualLimit` is confusing here. Either inline it as the original code, or rename it
   ```suggestion
         int maxDocsPerCall = Math.min(limit, DocIdSetPlanNode.MAX_DOC_PER_CALL);
   ```



##########
pinot-core/src/main/java/org/apache/pinot/core/operator/query/SelectionPartiallyOrderedByDescOperation.java:
##########
@@ -0,0 +1,132 @@
+/**
+ * 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.pinot.core.operator.query;
+
+import com.google.common.base.Preconditions;
+import com.google.common.base.Supplier;
+import java.util.ArrayList;
+import java.util.List;
+import org.apache.pinot.common.request.context.ExpressionContext;
+import org.apache.pinot.core.common.BlockValSet;
+import org.apache.pinot.core.common.RowBasedBlockValueFetcher;
+import org.apache.pinot.core.operator.blocks.TransformBlock;
+import org.apache.pinot.core.operator.transform.TransformOperator;
+import org.apache.pinot.core.query.request.context.QueryContext;
+import org.apache.pinot.segment.spi.IndexSegment;
+
+
+/**
+ * An operator for order-by queries DESC that are partially sorted over the sorting keys.
+ *
+ * @see LinearSelectionOrderByOperator
+ */
+public class SelectionPartiallyOrderedByDescOperation extends LinearSelectionOrderByOperator {
+
+  private static final String EXPLAIN_NAME = "SELECT_PARTIAL_ORDER_BY_DESC";
+
+  private int _numDocsScanned = 0;
+  private long _numEntriesScannedPostFilter = 0;
+
+  public SelectionPartiallyOrderedByDescOperation(IndexSegment indexSegment, QueryContext queryContext,
+      List<ExpressionContext> expressions, TransformOperator transformOperator, int sortedExpr) {
+    super(indexSegment, queryContext, expressions, transformOperator, sortedExpr);
+    assert queryContext.getOrderByExpressions() != null;
+    Preconditions.checkArgument(queryContext.getOrderByExpressions().stream()
+            .filter(expr -> expr.getExpression().getType() == ExpressionContext.Type.IDENTIFIER)
+            .findFirst()
+            .orElseThrow(() -> new IllegalArgumentException("The query is not order by identifiers"))
+            .isDesc(),
+        "%s can only be used when the first column in order by is DESC", EXPLAIN_NAME);
+  }
+
+  @Override
+  protected List<Object[]> fetch(Supplier<ListBuilder> listBuilderSupplier) {
+
+    // Ideally we would use a descending cursor, but we don't actually have them
+    // Alternatively, we could store all blocks in a list and iterate them in reverse order, but ProjectionBlocks share
+    // the same DataBlockCache, so they may be ephemeral and being overridden by the next block.
+    // The only alternative we have right now is to retrieve the last LIMIT elements from each block
+
+    TransformBlock block;
+    int numColumnsProjected = _transformOperator.getNumColumnsProjected();
+    int numExpressions = _expressions.size();
+    BlockValSet[] blockValSets = new BlockValSet[numExpressions];
+
+    List<List<Object[]>> rowsPerBlock = new ArrayList<>();

Review Comment:
   This will cause memory issue when the LIMIT is large (e.g. when the LIMIT is 10000, which is the same as the block size, we will cache all rows in memory)
   
   One way to avoid it is to keep only the rows selected up to the current block, and then when the new block comes, if we don't gather enough rows, add the records from the previous blocks and update the rows.
   
   When the `LIMIT` is larger than the block size, this will always add overhead, so we should avoid using this operator



##########
pinot-core/src/main/java/org/apache/pinot/core/operator/blocks/IntermediateResultsBlock.java:
##########
@@ -587,4 +600,101 @@ public BlockDocIdValueSet getBlockDocIdValueSet() {
   public BlockMetadata getMetadata() {
     throw new UnsupportedOperationException();
   }
+
+  public static class ListSelection extends IntermediateResultsBlock {

Review Comment:
   Suggest not creating subclasses for now. For the purpose of this PR, we can add the `_comparator` to the `IntermediateResultsBlock` and change the constructor to `public IntermediateResultsBlock(DataSchema dataSchema, Collection<Object[]> selectionResult, @Nullable Comparator comparator, boolean nullHandlingEnabled)`
   
   I'm planning to split the `IntermediateResultsBlock` into results block for each query type (similar idea with this one), but IMO it is better to do it in a separate PR



##########
pinot-core/src/main/java/org/apache/pinot/core/plan/SelectionPlanNode.java:
##########
@@ -50,67 +52,113 @@ public Operator<IntermediateResultsBlock> run() {
     List<ExpressionContext> expressions = SelectionOperatorUtils.extractExpressions(_queryContext, _indexSegment);
     int limit = _queryContext.getLimit();
 
-    if (limit > 0) {
-      List<OrderByExpressionContext> orderByExpressions = _queryContext.getOrderByExpressions();
-      if (orderByExpressions == null) {
-        // Selection only
-        TransformOperator transformOperator = new TransformPlanNode(_indexSegment, _queryContext, expressions,
-            Math.min(limit, DocIdSetPlanNode.MAX_DOC_PER_CALL)).run();
-        return new SelectionOnlyOperator(_indexSegment, _queryContext, expressions, transformOperator);
-      } else {
-        // Selection order-by
-        if (isAllOrderByColumnsSorted(orderByExpressions)) {
-          // All order-by columns are sorted, no need to sort the records
-          TransformOperator transformOperator = new TransformPlanNode(_indexSegment, _queryContext, expressions,
-              Math.min(limit + _queryContext.getOffset(), DocIdSetPlanNode.MAX_DOC_PER_CALL)).run();
-          return new SelectionOrderByOperator(_indexSegment, _queryContext, expressions, transformOperator, true);
-        } else if (orderByExpressions.size() == expressions.size()) {
-          // All output expressions are ordered
-          TransformOperator transformOperator =
-              new TransformPlanNode(_indexSegment, _queryContext, expressions, DocIdSetPlanNode.MAX_DOC_PER_CALL).run();
-          return new SelectionOrderByOperator(_indexSegment, _queryContext, expressions, transformOperator, false);
-        } else {
-          // Not all output expressions are ordered, only fetch the order-by expressions and docId to avoid the
-          // unnecessary data fetch
-          List<ExpressionContext> expressionsToTransform = new ArrayList<>(orderByExpressions.size());
-          for (OrderByExpressionContext orderByExpression : orderByExpressions) {
-            expressionsToTransform.add(orderByExpression.getExpression());
-          }
-          TransformOperator transformOperator =
-              new TransformPlanNode(_indexSegment, _queryContext, expressionsToTransform,
-                  DocIdSetPlanNode.MAX_DOC_PER_CALL).run();
-          return new SelectionOrderByOperator(_indexSegment, _queryContext, expressions, transformOperator, false);
-        }
-      }
-    } else {
+    if (limit == 0) {
       // Empty selection (LIMIT 0)
       TransformOperator transformOperator = new TransformPlanNode(_indexSegment, _queryContext, expressions, 0).run();
       return new EmptySelectionOperator(_indexSegment, expressions, transformOperator);
     }
+    List<OrderByExpressionContext> orderByExpressions = _queryContext.getOrderByExpressions();
+
+    if (orderByExpressions == null) {
+      // Selection only
+      // ie: SELECT ... FROM Table WHERE ... LIMIT 10
+      int actualLimit = Math.min(limit, DocIdSetPlanNode.MAX_DOC_PER_CALL);
+      TransformPlanNode planNode = new TransformPlanNode(_indexSegment, _queryContext, expressions, actualLimit);
+      TransformOperator transformOperator = planNode.run();
+
+      return new SelectionOnlyOperator(_indexSegment, _queryContext, expressions, transformOperator);
+    }
+    int numOrderByExpressions = orderByExpressions.size();
+    // Although it is a break of abstraction, some code, specially merging, assumes that if there is an order by
+    // expression the operator will return a block whose selection result is a priority queue.
+    int sortedColumnsPrefixSize = getSortedColumnsPrefix(orderByExpressions);

Review Comment:
   When null-handling is enabled, and the sorted column contains `null`, we cannot use the optimized operator because it breaks the sorted assumption. `null` value can be stored as any default value, but when ordering it, we want to put it in the end



##########
pinot-core/src/main/java/org/apache/pinot/core/plan/SelectionPlanNode.java:
##########
@@ -50,67 +52,113 @@ public Operator<IntermediateResultsBlock> run() {
     List<ExpressionContext> expressions = SelectionOperatorUtils.extractExpressions(_queryContext, _indexSegment);
     int limit = _queryContext.getLimit();
 
-    if (limit > 0) {
-      List<OrderByExpressionContext> orderByExpressions = _queryContext.getOrderByExpressions();
-      if (orderByExpressions == null) {
-        // Selection only
-        TransformOperator transformOperator = new TransformPlanNode(_indexSegment, _queryContext, expressions,
-            Math.min(limit, DocIdSetPlanNode.MAX_DOC_PER_CALL)).run();
-        return new SelectionOnlyOperator(_indexSegment, _queryContext, expressions, transformOperator);
-      } else {
-        // Selection order-by
-        if (isAllOrderByColumnsSorted(orderByExpressions)) {
-          // All order-by columns are sorted, no need to sort the records
-          TransformOperator transformOperator = new TransformPlanNode(_indexSegment, _queryContext, expressions,
-              Math.min(limit + _queryContext.getOffset(), DocIdSetPlanNode.MAX_DOC_PER_CALL)).run();
-          return new SelectionOrderByOperator(_indexSegment, _queryContext, expressions, transformOperator, true);
-        } else if (orderByExpressions.size() == expressions.size()) {
-          // All output expressions are ordered
-          TransformOperator transformOperator =
-              new TransformPlanNode(_indexSegment, _queryContext, expressions, DocIdSetPlanNode.MAX_DOC_PER_CALL).run();
-          return new SelectionOrderByOperator(_indexSegment, _queryContext, expressions, transformOperator, false);
-        } else {
-          // Not all output expressions are ordered, only fetch the order-by expressions and docId to avoid the
-          // unnecessary data fetch
-          List<ExpressionContext> expressionsToTransform = new ArrayList<>(orderByExpressions.size());
-          for (OrderByExpressionContext orderByExpression : orderByExpressions) {
-            expressionsToTransform.add(orderByExpression.getExpression());
-          }
-          TransformOperator transformOperator =
-              new TransformPlanNode(_indexSegment, _queryContext, expressionsToTransform,
-                  DocIdSetPlanNode.MAX_DOC_PER_CALL).run();
-          return new SelectionOrderByOperator(_indexSegment, _queryContext, expressions, transformOperator, false);
-        }
-      }
-    } else {
+    if (limit == 0) {
       // Empty selection (LIMIT 0)
       TransformOperator transformOperator = new TransformPlanNode(_indexSegment, _queryContext, expressions, 0).run();
       return new EmptySelectionOperator(_indexSegment, expressions, transformOperator);
     }
+    List<OrderByExpressionContext> orderByExpressions = _queryContext.getOrderByExpressions();
+
+    if (orderByExpressions == null) {
+      // Selection only
+      // ie: SELECT ... FROM Table WHERE ... LIMIT 10
+      int actualLimit = Math.min(limit, DocIdSetPlanNode.MAX_DOC_PER_CALL);
+      TransformPlanNode planNode = new TransformPlanNode(_indexSegment, _queryContext, expressions, actualLimit);
+      TransformOperator transformOperator = planNode.run();
+
+      return new SelectionOnlyOperator(_indexSegment, _queryContext, expressions, transformOperator);
+    }
+    int numOrderByExpressions = orderByExpressions.size();
+    // Although it is a break of abstraction, some code, specially merging, assumes that if there is an order by
+    // expression the operator will return a block whose selection result is a priority queue.
+    int sortedColumnsPrefixSize = getSortedColumnsPrefix(orderByExpressions);
+    if (sortedColumnsPrefixSize > 0 && isOrderByOptimizationEnabled()) {
+      // The first order by expressions are sorted (either asc or desc).
+      // ie: SELECT ... FROM Table WHERE predicates ORDER BY sorted_column DESC LIMIT 10 OFFSET 5
+      // or: SELECT ... FROM Table WHERE predicates ORDER BY sorted_column, not_sorted LIMIT 10 OFFSET 5
+      // but not SELECT ... FROM Table WHERE predicates ORDER BY not_sorted, sorted_column LIMIT 10 OFFSET 5
+      if (orderByExpressions.get(0).isAsc()) {
+        int actualLimit = Math.min(limit + _queryContext.getOffset(), DocIdSetPlanNode.MAX_DOC_PER_CALL);
+        TransformPlanNode planNode = new TransformPlanNode(_indexSegment, _queryContext, expressions, actualLimit);
+        TransformOperator transformOperator = planNode.run();
+        return new SelectionPartiallyOrderedByAscOperator(_indexSegment, _queryContext, expressions,
+            transformOperator, sortedColumnsPrefixSize);
+      } else {
+        int actualLimit = DocIdSetPlanNode.MAX_DOC_PER_CALL;
+        TransformPlanNode planNode = new TransformPlanNode(_indexSegment, _queryContext, expressions, actualLimit);
+        TransformOperator transformOperator = planNode.run();
+        return new SelectionPartiallyOrderedByDescOperation(_indexSegment, _queryContext, expressions,
+            transformOperator, sortedColumnsPrefixSize);
+      }
+    }
+    if (numOrderByExpressions == expressions.size()) {
+      // All output expressions are ordered
+      // ie: SELECT not_sorted1, not_sorted2 FROM Table WHERE ... ORDER BY not_sorted1, not_sorted2 LIMIT 10 OFFSET 5
+      TransformOperator transformOperator =
+          new TransformPlanNode(_indexSegment, _queryContext, expressions, DocIdSetPlanNode.MAX_DOC_PER_CALL).run();
+      return new SelectionOrderByOperator(_indexSegment, _queryContext, expressions, transformOperator);
+    }
+    // Not all output expressions are ordered, only fetch the order-by expressions and docId to avoid the
+    // unnecessary data fetch
+    // ie: SELECT ... FROM Table WHERE ... ORDER BY not_sorted1, not_sorted2 LIMIT 10
+    List<ExpressionContext> expressionsToTransform = new ArrayList<>(numOrderByExpressions);
+    for (OrderByExpressionContext orderByExpression : orderByExpressions) {
+      expressionsToTransform.add(orderByExpression.getExpression());
+    }
+    TransformOperator transformOperator =
+        new TransformPlanNode(_indexSegment, _queryContext, expressionsToTransform,
+            DocIdSetPlanNode.MAX_DOC_PER_CALL).run();
+    return new SelectionOrderByOperator(_indexSegment, _queryContext, expressions, transformOperator);
   }
 
   /**
-   *  This function checks whether all columns in order by clause are pre-sorted.
-   *  This is used to optimize order by limit clauses.
-   *  For eg:
-   *  A query like "select * from table order by col1, col2 limit 10"
-   *  will take all the n matching rows and add it to a priority queue of size 10.
-   *  This is nlogk operation which can be quite expensive for a large n.
-   *  In the above example, if the docs in the segment are already sorted by col1 and col2 then there is no need for
-   *  sorting at all (only limit is needed).
-   * @return true is all columns in order by clause are sorted . False otherwise
+   * This functions returns the number of expressions that are sorted by the implicit order in the index.
+   *
+   * This means that query that uses these expressions in its order by doesn't actually need to sort from 0 to the
+   * given number (excluded) of expressions, as they are returned in the correct order.
+   *
+   * This method supports ASC and DESC order and ensures that all prefix expressions follow the same order. For example,
+   * ORDER BY sorted_col1 ASC, sorted_col2 ASC and ORDER BY sorted_col1 DESC, sorted_col2 DESC will return 2 but
+   * ORDER BY sorted_col1 DESC, sorted_col2 ASC and ORDER BY sorted_col1 ASC, sorted_col2 DESC will return 1 while
+   * ORDER BY not_sorted, sorted_col1 will return 0 because the first column is not sorted.
+   *
+   * It doesn't make sense to add literal expressions in an order by expression, but if they are included, they are
+   * considered sorted and its ASC/DESC is ignored.
+   *
+   * @return the max number that guarantees that from the first expression to the returned number, the index is already
+   * sorted.
    */
-  private boolean isAllOrderByColumnsSorted(List<OrderByExpressionContext> orderByExpressions) {
-    for (OrderByExpressionContext orderByExpression : orderByExpressions) {
-      if (!(orderByExpression.getExpression().getType() == ExpressionContext.Type.IDENTIFIER)
-          || !orderByExpression.isAsc()) {
-        return false;
+  private int getSortedColumnsPrefix(List<OrderByExpressionContext> orderByExpressions) {
+    boolean asc = orderByExpressions.get(0).isAsc();
+    for (int i = 0; i < orderByExpressions.size(); i++) {
+      if (!isSorted(orderByExpressions.get(i), asc)) {
+        return i;
       }
-      String column = orderByExpression.getExpression().getIdentifier();
-      if (!_indexSegment.getDataSource(column).getDataSourceMetadata().isSorted()) {
+    }
+    // If we reach here, all are sorted
+    return orderByExpressions.size();
+  }
+
+  private boolean isSorted(OrderByExpressionContext orderByExpression, boolean asc) {
+    switch (orderByExpression.getExpression().getType()) {
+      case LITERAL: {
+        return true;
+      }
+      case IDENTIFIER: {
+        if (!orderByExpression.isAsc() == asc) {
+          return false;
+        }
+        String column = orderByExpression.getExpression().getIdentifier();
+        return _indexSegment.getDataSource(column).getDataSourceMetadata().isSorted();
+      }
+      case FUNCTION: // we could optimize monotonically increasing functions
+      default: {
         return false;
       }
     }
-    return true;
+  }
+
+  private boolean isOrderByOptimizationEnabled() {

Review Comment:
   I don't think we need this since it is on by default. If you want to have the ability to turn it off, put it in the `QueryOptions`



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] gortiz commented on pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
gortiz commented on PR #8979:
URL: https://github.com/apache/pinot/pull/8979#issuecomment-1198909909

   >  assert can be enabled by setting a JVM parameter: -ea
   
   Yeah, that is the behavior of assert. The problem is: In several parts of Pinot there are try-catch sections that catch Exception and do something (logging, returning something special, etc). Usually it is a bad practice in Java to catch Throwable because most of the times the application can not survive to an Error. For example, if we are getting out of memory or if there is an assertion that fail. 
   
   But that usual good practice does not always apply. For example I found that by not catching OOM errors in the ingestion jobs we are in fact not failing when one of them is thrown and therefore we break the consistency. In this PR I found a similar problem: As our code is not catching the AssertionError that assert throws, the integration tests were neither failing appropriately neither logging the problem. Instead I've got a very random error and no logging, which makes it very difficult to understand where the problem was.
   
   We have two options here: Either modify our codebase to try to catch all the Throwables in the root of the threads or do not use assertions. What we cannot do is to continue using assert when it is more problematic than useful.


-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] gortiz commented on a diff in pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
gortiz commented on code in PR #8979:
URL: https://github.com/apache/pinot/pull/8979#discussion_r980025857


##########
pinot-core/src/main/java/org/apache/pinot/core/plan/SelectionPlanNode.java:
##########
@@ -50,67 +55,119 @@ public Operator<SelectionResultsBlock> run() {
     List<ExpressionContext> expressions = SelectionOperatorUtils.extractExpressions(_queryContext, _indexSegment);
     int limit = _queryContext.getLimit();
 
-    if (limit > 0) {
-      List<OrderByExpressionContext> orderByExpressions = _queryContext.getOrderByExpressions();
-      if (orderByExpressions == null) {
-        // Selection only
-        TransformOperator transformOperator = new TransformPlanNode(_indexSegment, _queryContext, expressions,
-            Math.min(limit, DocIdSetPlanNode.MAX_DOC_PER_CALL)).run();
-        return new SelectionOnlyOperator(_indexSegment, _queryContext, expressions, transformOperator);
-      } else {
-        // Selection order-by
-        if (isAllOrderByColumnsSorted(orderByExpressions)) {
-          // All order-by columns are sorted, no need to sort the records
-          TransformOperator transformOperator = new TransformPlanNode(_indexSegment, _queryContext, expressions,
-              Math.min(limit + _queryContext.getOffset(), DocIdSetPlanNode.MAX_DOC_PER_CALL)).run();
-          return new SelectionOrderByOperator(_indexSegment, _queryContext, expressions, transformOperator, true);
-        } else if (orderByExpressions.size() == expressions.size()) {
-          // All output expressions are ordered
-          TransformOperator transformOperator =
-              new TransformPlanNode(_indexSegment, _queryContext, expressions, DocIdSetPlanNode.MAX_DOC_PER_CALL).run();
-          return new SelectionOrderByOperator(_indexSegment, _queryContext, expressions, transformOperator, false);
-        } else {
-          // Not all output expressions are ordered, only fetch the order-by expressions and docId to avoid the
-          // unnecessary data fetch
-          List<ExpressionContext> expressionsToTransform = new ArrayList<>(orderByExpressions.size());
-          for (OrderByExpressionContext orderByExpression : orderByExpressions) {
-            expressionsToTransform.add(orderByExpression.getExpression());
-          }
-          TransformOperator transformOperator =
-              new TransformPlanNode(_indexSegment, _queryContext, expressionsToTransform,
-                  DocIdSetPlanNode.MAX_DOC_PER_CALL).run();
-          return new SelectionOrderByOperator(_indexSegment, _queryContext, expressions, transformOperator, false);
-        }
-      }
-    } else {
+    if (limit == 0) {
       // Empty selection (LIMIT 0)
       TransformOperator transformOperator = new TransformPlanNode(_indexSegment, _queryContext, expressions, 0).run();
       return new EmptySelectionOperator(_indexSegment, expressions, transformOperator);
     }
+    List<OrderByExpressionContext> orderByExpressions = _queryContext.getOrderByExpressions();
+    if (orderByExpressions == null) {
+      // Selection only
+      // ie: SELECT ... FROM Table WHERE ... LIMIT 10
+      int maxDocsPerCall = Math.min(limit, DocIdSetPlanNode.MAX_DOC_PER_CALL);
+      TransformPlanNode planNode = new TransformPlanNode(_indexSegment, _queryContext, expressions, maxDocsPerCall);
+      TransformOperator transformOperator = planNode.run();
+
+      return new SelectionOnlyOperator(_indexSegment, _queryContext, expressions, transformOperator);
+    }
+    int numOrderByExpressions = orderByExpressions.size();
+    // Although it is a break of abstraction, some code, specially merging, assumes that if there is an order by
+    // expression the operator will return a block whose selection result is a priority queue.
+    int sortedColumnsPrefixSize = getSortedColumnsPrefix(orderByExpressions, _queryContext.isNullHandlingEnabled());
+    if (sortedColumnsPrefixSize > 0 && !isSkipOrderByOptimization()) {
+      // The first order by expressions are sorted (either asc or desc).
+      // ie: SELECT ... FROM Table WHERE predicates ORDER BY sorted_column DESC LIMIT 10 OFFSET 5
+      // or: SELECT ... FROM Table WHERE predicates ORDER BY sorted_column, not_sorted LIMIT 10 OFFSET 5
+      // but not SELECT ... FROM Table WHERE predicates ORDER BY not_sorted, sorted_column LIMIT 10 OFFSET 5
+      if (orderByExpressions.get(0).isAsc()) {
+        int maxDocsPerCall = Math.min(limit + _queryContext.getOffset(), DocIdSetPlanNode.MAX_DOC_PER_CALL);
+        TransformPlanNode planNode = new TransformPlanNode(_indexSegment, _queryContext, expressions, maxDocsPerCall);
+        TransformOperator transformOperator = planNode.run();
+        return new SelectionPartiallyOrderedByAscOperator(_indexSegment, _queryContext, expressions,
+            transformOperator, sortedColumnsPrefixSize);
+      } else {
+        int maxDocsPerCall = DocIdSetPlanNode.MAX_DOC_PER_CALL;

Review Comment:
   I'm not sure about that. The cost of this optimization should almost always be better than the previous one. Trying to bring light in the topic, I've created a new benchmark to test that, these are the results (_orderByAlgorithm=naive implies to use the brute force algorithm, null means try to use all optimizations):
   
   ```
   
   Benchmark                                        (_limit)  (_numRows)  (_orderByAlgorithm)  (_primaryRepetitions)  Mode  Cnt     Score     Error  Units
   BenchmarkOrderByDescQueries.sortedDesc                101     1500000                naive                      1  avgt    5   291.745 ±  32.896  ms/op
   BenchmarkOrderByDescQueries.sortedDesc                101     1500000                naive                   1000  avgt    5    45.143 ±   3.794  ms/op
   BenchmarkOrderByDescQueries.sortedDesc                101     1500000                 null                      1  avgt    5    11.280 ±   0.688  ms/op
   BenchmarkOrderByDescQueries.sortedDesc                101     1500000                 null                   1000  avgt    5     7.919 ±   1.100  ms/op
   BenchmarkOrderByDescQueries.sortedDesc              10100     1500000                naive                      1  avgt    5   486.737 ±  24.255  ms/op
   BenchmarkOrderByDescQueries.sortedDesc              10100     1500000                naive                   1000  avgt    5   472.893 ±  18.295  ms/op
   BenchmarkOrderByDescQueries.sortedDesc              10100     1500000                 null                      1  avgt    5    46.034 ±   9.756  ms/op
   BenchmarkOrderByDescQueries.sortedDesc              10100     1500000                 null                   1000  avgt    5    42.245 ±   8.914  ms/op
   BenchmarkOrderByDescQueries.sortedDesc             101000     1500000                naive                      1  avgt    5   667.891 ±  75.390  ms/op
   BenchmarkOrderByDescQueries.sortedDesc             101000     1500000                naive                   1000  avgt    5   632.281 ±  68.473  ms/op
   BenchmarkOrderByDescQueries.sortedDesc             101000     1500000                 null                      1  avgt    5   254.195 ±  28.543  ms/op
   BenchmarkOrderByDescQueries.sortedDesc             101000     1500000                 null                   1000  avgt    5   213.058 ±   6.653  ms/op
   BenchmarkOrderByDescQueries.sortedDescPartially       101     1500000                naive                      1  avgt    5   280.261 ±  28.662  ms/op
   BenchmarkOrderByDescQueries.sortedDescPartially       101     1500000                naive                   1000  avgt    5   181.734 ±   5.478  ms/op
   BenchmarkOrderByDescQueries.sortedDescPartially       101     1500000                 null                      1  avgt    5    53.713 ±   2.282  ms/op
   BenchmarkOrderByDescQueries.sortedDescPartially       101     1500000                 null                   1000  avgt    5   101.987 ±  12.397  ms/op
   BenchmarkOrderByDescQueries.sortedDescPartially     10100     1500000                naive                      1  avgt    5   495.354 ±  29.019  ms/op
   BenchmarkOrderByDescQueries.sortedDescPartially     10100     1500000                naive                   1000  avgt    5   809.116 ±  56.675  ms/op
   BenchmarkOrderByDescQueries.sortedDescPartially     10100     1500000                 null                      1  avgt    5   144.217 ±   6.340  ms/op
   BenchmarkOrderByDescQueries.sortedDescPartially     10100     1500000                 null                   1000  avgt    5   307.823 ±  40.541  ms/op
   BenchmarkOrderByDescQueries.sortedDescPartially    101000     1500000                naive                      1  avgt    5   622.101 ±  70.437  ms/op
   BenchmarkOrderByDescQueries.sortedDescPartially    101000     1500000                naive                   1000  avgt    5  1042.126 ± 125.183  ms/op
   BenchmarkOrderByDescQueries.sortedDescPartially    101000     1500000                 null                      1  avgt    5   151.553 ±  24.081  ms/op
   BenchmarkOrderByDescQueries.sortedDescPartially    101000     1500000                 null                   1000  avgt    5   325.945 ±  14.207  ms/op
   ```
   
   I need to study the results a little bit more because some numbers don't make sense (for example, with limit 10100, `BenchmarkOrderByDescQueries.sortedDesc ` seems to be slower than `BenchmarkOrderByDescQueries.sortedDescPartially`.



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] gortiz commented on a diff in pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
gortiz commented on code in PR #8979:
URL: https://github.com/apache/pinot/pull/8979#discussion_r979823620


##########
pinot-core/src/main/java/org/apache/pinot/core/util/QueryOptionsUtils.java:
##########
@@ -102,4 +102,8 @@ public static boolean isNullHandlingEnabled(Map<String, String> queryOptions) {
   public static boolean isServerReturnFinalResult(Map<String, String> queryOptions) {
     return Boolean.parseBoolean(queryOptions.get(QueryOptionKey.SERVER_RETURN_FINAL_RESULT));
   }
+
+  public static boolean isSkipOrderByOptimization(Map<String, String> queryOptions) {
+    return Boolean.parseBoolean(queryOptions.getOrDefault("skip-order-by", "false"));

Review Comment:
   I've replaced it with a new enum option `order-by-algorithm`. The only literal right now is to apply the `naive` algorithm, which means to run with the brute force algorithm, but we could add more literals in the future to be treated as a hint or as a mandatory algorithm (which is very useful in benchmarks, but may be useful in case there is a bug in some algorithm).



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] Jackie-Jiang commented on a diff in pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
Jackie-Jiang commented on code in PR #8979:
URL: https://github.com/apache/pinot/pull/8979#discussion_r959846240


##########
pinot-core/src/main/java/org/apache/pinot/core/plan/SelectionPlanNode.java:
##########
@@ -50,67 +52,113 @@ public Operator<IntermediateResultsBlock> run() {
     List<ExpressionContext> expressions = SelectionOperatorUtils.extractExpressions(_queryContext, _indexSegment);
     int limit = _queryContext.getLimit();
 
-    if (limit > 0) {
-      List<OrderByExpressionContext> orderByExpressions = _queryContext.getOrderByExpressions();
-      if (orderByExpressions == null) {
-        // Selection only
-        TransformOperator transformOperator = new TransformPlanNode(_indexSegment, _queryContext, expressions,
-            Math.min(limit, DocIdSetPlanNode.MAX_DOC_PER_CALL)).run();
-        return new SelectionOnlyOperator(_indexSegment, _queryContext, expressions, transformOperator);
-      } else {
-        // Selection order-by
-        if (isAllOrderByColumnsSorted(orderByExpressions)) {
-          // All order-by columns are sorted, no need to sort the records
-          TransformOperator transformOperator = new TransformPlanNode(_indexSegment, _queryContext, expressions,
-              Math.min(limit + _queryContext.getOffset(), DocIdSetPlanNode.MAX_DOC_PER_CALL)).run();
-          return new SelectionOrderByOperator(_indexSegment, _queryContext, expressions, transformOperator, true);
-        } else if (orderByExpressions.size() == expressions.size()) {
-          // All output expressions are ordered
-          TransformOperator transformOperator =
-              new TransformPlanNode(_indexSegment, _queryContext, expressions, DocIdSetPlanNode.MAX_DOC_PER_CALL).run();
-          return new SelectionOrderByOperator(_indexSegment, _queryContext, expressions, transformOperator, false);
-        } else {
-          // Not all output expressions are ordered, only fetch the order-by expressions and docId to avoid the
-          // unnecessary data fetch
-          List<ExpressionContext> expressionsToTransform = new ArrayList<>(orderByExpressions.size());
-          for (OrderByExpressionContext orderByExpression : orderByExpressions) {
-            expressionsToTransform.add(orderByExpression.getExpression());
-          }
-          TransformOperator transformOperator =
-              new TransformPlanNode(_indexSegment, _queryContext, expressionsToTransform,
-                  DocIdSetPlanNode.MAX_DOC_PER_CALL).run();
-          return new SelectionOrderByOperator(_indexSegment, _queryContext, expressions, transformOperator, false);
-        }
-      }
-    } else {
+    if (limit == 0) {
       // Empty selection (LIMIT 0)
       TransformOperator transformOperator = new TransformPlanNode(_indexSegment, _queryContext, expressions, 0).run();
       return new EmptySelectionOperator(_indexSegment, expressions, transformOperator);
     }
+    List<OrderByExpressionContext> orderByExpressions = _queryContext.getOrderByExpressions();
+
+    if (orderByExpressions == null) {
+      // Selection only
+      // ie: SELECT ... FROM Table WHERE ... LIMIT 10
+      int actualLimit = Math.min(limit, DocIdSetPlanNode.MAX_DOC_PER_CALL);
+      TransformPlanNode planNode = new TransformPlanNode(_indexSegment, _queryContext, expressions, actualLimit);
+      TransformOperator transformOperator = planNode.run();
+
+      return new SelectionOnlyOperator(_indexSegment, _queryContext, expressions, transformOperator);
+    }
+    int numOrderByExpressions = orderByExpressions.size();
+    // Although it is a break of abstraction, some code, specially merging, assumes that if there is an order by
+    // expression the operator will return a block whose selection result is a priority queue.
+    int sortedColumnsPrefixSize = getSortedColumnsPrefix(orderByExpressions);

Review Comment:
   I believe we use `LAST` by default to match the Presto behavior: https://prestodb.io/docs/current/sql/select.html#order-by-clause
   
   Currently we store `null` as any default value, so there can be a corner case where a sorted column has null values inside. Per the convention we pick, column with null value should not be count as sorted, so we should account for that



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] gortiz commented on a diff in pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
gortiz commented on code in PR #8979:
URL: https://github.com/apache/pinot/pull/8979#discussion_r959234516


##########
pinot-core/src/main/java/org/apache/pinot/core/plan/SelectionPlanNode.java:
##########
@@ -50,67 +52,113 @@ public Operator<IntermediateResultsBlock> run() {
     List<ExpressionContext> expressions = SelectionOperatorUtils.extractExpressions(_queryContext, _indexSegment);
     int limit = _queryContext.getLimit();
 
-    if (limit > 0) {
-      List<OrderByExpressionContext> orderByExpressions = _queryContext.getOrderByExpressions();
-      if (orderByExpressions == null) {
-        // Selection only
-        TransformOperator transformOperator = new TransformPlanNode(_indexSegment, _queryContext, expressions,
-            Math.min(limit, DocIdSetPlanNode.MAX_DOC_PER_CALL)).run();
-        return new SelectionOnlyOperator(_indexSegment, _queryContext, expressions, transformOperator);
-      } else {
-        // Selection order-by
-        if (isAllOrderByColumnsSorted(orderByExpressions)) {
-          // All order-by columns are sorted, no need to sort the records
-          TransformOperator transformOperator = new TransformPlanNode(_indexSegment, _queryContext, expressions,
-              Math.min(limit + _queryContext.getOffset(), DocIdSetPlanNode.MAX_DOC_PER_CALL)).run();
-          return new SelectionOrderByOperator(_indexSegment, _queryContext, expressions, transformOperator, true);
-        } else if (orderByExpressions.size() == expressions.size()) {
-          // All output expressions are ordered
-          TransformOperator transformOperator =
-              new TransformPlanNode(_indexSegment, _queryContext, expressions, DocIdSetPlanNode.MAX_DOC_PER_CALL).run();
-          return new SelectionOrderByOperator(_indexSegment, _queryContext, expressions, transformOperator, false);
-        } else {
-          // Not all output expressions are ordered, only fetch the order-by expressions and docId to avoid the
-          // unnecessary data fetch
-          List<ExpressionContext> expressionsToTransform = new ArrayList<>(orderByExpressions.size());
-          for (OrderByExpressionContext orderByExpression : orderByExpressions) {
-            expressionsToTransform.add(orderByExpression.getExpression());
-          }
-          TransformOperator transformOperator =
-              new TransformPlanNode(_indexSegment, _queryContext, expressionsToTransform,
-                  DocIdSetPlanNode.MAX_DOC_PER_CALL).run();
-          return new SelectionOrderByOperator(_indexSegment, _queryContext, expressions, transformOperator, false);
-        }
-      }
-    } else {
+    if (limit == 0) {
       // Empty selection (LIMIT 0)
       TransformOperator transformOperator = new TransformPlanNode(_indexSegment, _queryContext, expressions, 0).run();
       return new EmptySelectionOperator(_indexSegment, expressions, transformOperator);
     }
+    List<OrderByExpressionContext> orderByExpressions = _queryContext.getOrderByExpressions();
+
+    if (orderByExpressions == null) {
+      // Selection only
+      // ie: SELECT ... FROM Table WHERE ... LIMIT 10
+      int actualLimit = Math.min(limit, DocIdSetPlanNode.MAX_DOC_PER_CALL);
+      TransformPlanNode planNode = new TransformPlanNode(_indexSegment, _queryContext, expressions, actualLimit);
+      TransformOperator transformOperator = planNode.run();
+
+      return new SelectionOnlyOperator(_indexSegment, _queryContext, expressions, transformOperator);
+    }
+    int numOrderByExpressions = orderByExpressions.size();
+    // Although it is a break of abstraction, some code, specially merging, assumes that if there is an order by
+    // expression the operator will return a block whose selection result is a priority queue.
+    int sortedColumnsPrefixSize = getSortedColumnsPrefix(orderByExpressions);
+    if (sortedColumnsPrefixSize > 0 && isOrderByOptimizationEnabled()) {
+      // The first order by expressions are sorted (either asc or desc).
+      // ie: SELECT ... FROM Table WHERE predicates ORDER BY sorted_column DESC LIMIT 10 OFFSET 5
+      // or: SELECT ... FROM Table WHERE predicates ORDER BY sorted_column, not_sorted LIMIT 10 OFFSET 5
+      // but not SELECT ... FROM Table WHERE predicates ORDER BY not_sorted, sorted_column LIMIT 10 OFFSET 5
+      if (orderByExpressions.get(0).isAsc()) {
+        int actualLimit = Math.min(limit + _queryContext.getOffset(), DocIdSetPlanNode.MAX_DOC_PER_CALL);
+        TransformPlanNode planNode = new TransformPlanNode(_indexSegment, _queryContext, expressions, actualLimit);
+        TransformOperator transformOperator = planNode.run();
+        return new SelectionPartiallyOrderedByAscOperator(_indexSegment, _queryContext, expressions,
+            transformOperator, sortedColumnsPrefixSize);
+      } else {
+        int actualLimit = DocIdSetPlanNode.MAX_DOC_PER_CALL;
+        TransformPlanNode planNode = new TransformPlanNode(_indexSegment, _queryContext, expressions, actualLimit);
+        TransformOperator transformOperator = planNode.run();
+        return new SelectionPartiallyOrderedByDescOperation(_indexSegment, _queryContext, expressions,
+            transformOperator, sortedColumnsPrefixSize);
+      }
+    }
+    if (numOrderByExpressions == expressions.size()) {
+      // All output expressions are ordered
+      // ie: SELECT not_sorted1, not_sorted2 FROM Table WHERE ... ORDER BY not_sorted1, not_sorted2 LIMIT 10 OFFSET 5
+      TransformOperator transformOperator =
+          new TransformPlanNode(_indexSegment, _queryContext, expressions, DocIdSetPlanNode.MAX_DOC_PER_CALL).run();
+      return new SelectionOrderByOperator(_indexSegment, _queryContext, expressions, transformOperator);
+    }
+    // Not all output expressions are ordered, only fetch the order-by expressions and docId to avoid the
+    // unnecessary data fetch
+    // ie: SELECT ... FROM Table WHERE ... ORDER BY not_sorted1, not_sorted2 LIMIT 10
+    List<ExpressionContext> expressionsToTransform = new ArrayList<>(numOrderByExpressions);
+    for (OrderByExpressionContext orderByExpression : orderByExpressions) {
+      expressionsToTransform.add(orderByExpression.getExpression());
+    }
+    TransformOperator transformOperator =
+        new TransformPlanNode(_indexSegment, _queryContext, expressionsToTransform,
+            DocIdSetPlanNode.MAX_DOC_PER_CALL).run();
+    return new SelectionOrderByOperator(_indexSegment, _queryContext, expressions, transformOperator);
   }
 
   /**
-   *  This function checks whether all columns in order by clause are pre-sorted.
-   *  This is used to optimize order by limit clauses.
-   *  For eg:
-   *  A query like "select * from table order by col1, col2 limit 10"
-   *  will take all the n matching rows and add it to a priority queue of size 10.
-   *  This is nlogk operation which can be quite expensive for a large n.
-   *  In the above example, if the docs in the segment are already sorted by col1 and col2 then there is no need for
-   *  sorting at all (only limit is needed).
-   * @return true is all columns in order by clause are sorted . False otherwise
+   * This functions returns the number of expressions that are sorted by the implicit order in the index.
+   *
+   * This means that query that uses these expressions in its order by doesn't actually need to sort from 0 to the
+   * given number (excluded) of expressions, as they are returned in the correct order.
+   *
+   * This method supports ASC and DESC order and ensures that all prefix expressions follow the same order. For example,
+   * ORDER BY sorted_col1 ASC, sorted_col2 ASC and ORDER BY sorted_col1 DESC, sorted_col2 DESC will return 2 but
+   * ORDER BY sorted_col1 DESC, sorted_col2 ASC and ORDER BY sorted_col1 ASC, sorted_col2 DESC will return 1 while
+   * ORDER BY not_sorted, sorted_col1 will return 0 because the first column is not sorted.
+   *
+   * It doesn't make sense to add literal expressions in an order by expression, but if they are included, they are
+   * considered sorted and its ASC/DESC is ignored.
+   *
+   * @return the max number that guarantees that from the first expression to the returned number, the index is already
+   * sorted.
    */
-  private boolean isAllOrderByColumnsSorted(List<OrderByExpressionContext> orderByExpressions) {
-    for (OrderByExpressionContext orderByExpression : orderByExpressions) {
-      if (!(orderByExpression.getExpression().getType() == ExpressionContext.Type.IDENTIFIER)
-          || !orderByExpression.isAsc()) {
-        return false;
+  private int getSortedColumnsPrefix(List<OrderByExpressionContext> orderByExpressions) {
+    boolean asc = orderByExpressions.get(0).isAsc();
+    for (int i = 0; i < orderByExpressions.size(); i++) {
+      if (!isSorted(orderByExpressions.get(i), asc)) {
+        return i;
       }
-      String column = orderByExpression.getExpression().getIdentifier();
-      if (!_indexSegment.getDataSource(column).getDataSourceMetadata().isSorted()) {
+    }
+    // If we reach here, all are sorted
+    return orderByExpressions.size();
+  }
+
+  private boolean isSorted(OrderByExpressionContext orderByExpression, boolean asc) {
+    switch (orderByExpression.getExpression().getType()) {
+      case LITERAL: {
+        return true;
+      }
+      case IDENTIFIER: {
+        if (!orderByExpression.isAsc() == asc) {
+          return false;
+        }
+        String column = orderByExpression.getExpression().getIdentifier();
+        return _indexSegment.getDataSource(column).getDataSourceMetadata().isSorted();
+      }
+      case FUNCTION: // we could optimize monotonically increasing functions
+      default: {
         return false;
       }
     }
-    return true;
+  }
+
+  private boolean isOrderByOptimizationEnabled() {

Review Comment:
   I guess you mean to move it to `QueryOptionsUtils`. I'll do that.
   
   Anyway, the `SelectionPlanNode.isOrderByOptimizationEnabled` is still there because it is free and I think 
   ```java
   if (sortedColumnsPrefixSize > 0 && isOrderByOptimizationEnabled()) {
   ```
   
   is more readable than
   
   ```java
   if (sortedColumnsPrefixSize > 0 && QueryOptionsUtils.isOrderByOptimizationEnabled(_queryContext.getQueryOptions()))  {
   ```



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] Jackie-Jiang commented on pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
Jackie-Jiang commented on PR #8979:
URL: https://github.com/apache/pinot/pull/8979#issuecomment-1189551878

   > I think I finally found why the test was failing. It was due to a `cmp >= 0` assertion that should be `cmp <= 0`. The reason that made it very hard to find the problem is that `BaseCombineOperator` is not prepared to catch `Errors`, so the task at the server just failed without printing any log and as a result the broker didn't receive a response, so the error shown in the broker was that some server didn't answer.
   > 
   > Things to know about:
   > 
   > * Pinot may not log `AssertionErrors`, so it is better to do not use `assert` expressions
   > * We may or may not want to log in case we receive an error. As I don't know what do we want to do in that case, I've just changed my code to throw an `ArgumentException`.
   
   We use `assert` to ensure certain behavior, but also avoid the overhead of the extra check. In production environment, `assert` statement is ignored, which is the desired behavior. In performance critical path, we want to avoid the extra check if we know certain behavior is expected.
   `assert` can be enabled by setting a JVM parameter: `-ea`


-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] codecov-commenter commented on pull request #8979: optimize `order by sorted ASC, unsorted` case

Posted by GitBox <gi...@apache.org>.
codecov-commenter commented on PR #8979:
URL: https://github.com/apache/pinot/pull/8979#issuecomment-1174733254

   # [Codecov](https://codecov.io/gh/apache/pinot/pull/8979?src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation) Report
   > Merging [#8979](https://codecov.io/gh/apache/pinot/pull/8979?src=pr&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation) (38f397c) into [master](https://codecov.io/gh/apache/pinot/commit/3ff4d13af7b693ec8f4766bbc281c1b3034621ba?el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation) (3ff4d13) will **decrease** coverage by `54.77%`.
   > The diff coverage is `0.00%`.
   
   ```diff
   @@              Coverage Diff              @@
   ##             master    #8979       +/-   ##
   =============================================
   - Coverage     70.09%   15.32%   -54.78%     
   + Complexity     4732      170     -4562     
   =============================================
     Files          1826     1780       -46     
     Lines         95980    94064     -1916     
     Branches      14352    14140      -212     
   =============================================
   - Hits          67281    14411    -52870     
   - Misses        24057    78626    +54569     
   + Partials       4642     1027     -3615     
   ```
   
   | Flag | Coverage Δ | |
   |---|---|---|
   | integration1 | `?` | |
   | integration2 | `?` | |
   | unittests1 | `?` | |
   | unittests2 | `15.32% <0.00%> (-0.02%)` | :arrow_down: |
   
   Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#carryforward-flags-in-the-pull-request-comment) to find out more.
   
   | [Impacted Files](https://codecov.io/gh/apache/pinot/pull/8979?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation) | Coverage Δ | |
   |---|---|---|
   | [.../pinot/core/operator/InstanceResponseOperator.java](https://codecov.io/gh/apache/pinot/pull/8979/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-cGlub3QtY29yZS9zcmMvbWFpbi9qYXZhL29yZy9hcGFjaGUvcGlub3QvY29yZS9vcGVyYXRvci9JbnN0YW5jZVJlc3BvbnNlT3BlcmF0b3IuamF2YQ==) | `0.00% <ø> (-87.18%)` | :arrow_down: |
   | [...re/operator/StreamingInstanceResponseOperator.java](https://codecov.io/gh/apache/pinot/pull/8979/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-cGlub3QtY29yZS9zcmMvbWFpbi9qYXZhL29yZy9hcGFjaGUvcGlub3QvY29yZS9vcGVyYXRvci9TdHJlYW1pbmdJbnN0YW5jZVJlc3BvbnNlT3BlcmF0b3IuamF2YQ==) | `0.00% <ø> (-76.93%)` | :arrow_down: |
   | [...core/operator/blocks/IntermediateResultsBlock.java](https://codecov.io/gh/apache/pinot/pull/8979/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-cGlub3QtY29yZS9zcmMvbWFpbi9qYXZhL29yZy9hcGFjaGUvcGlub3QvY29yZS9vcGVyYXRvci9ibG9ja3MvSW50ZXJtZWRpYXRlUmVzdWx0c0Jsb2NrLmphdmE=) | `0.00% <0.00%> (-82.49%)` | :arrow_down: |
   | [...erator/combine/AggregationOnlyCombineOperator.java](https://codecov.io/gh/apache/pinot/pull/8979/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-cGlub3QtY29yZS9zcmMvbWFpbi9qYXZhL29yZy9hcGFjaGUvcGlub3QvY29yZS9vcGVyYXRvci9jb21iaW5lL0FnZ3JlZ2F0aW9uT25seUNvbWJpbmVPcGVyYXRvci5qYXZh) | `0.00% <0.00%> (-83.34%)` | :arrow_down: |
   | [...not/core/operator/combine/BaseCombineOperator.java](https://codecov.io/gh/apache/pinot/pull/8979/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-cGlub3QtY29yZS9zcmMvbWFpbi9qYXZhL29yZy9hcGFjaGUvcGlub3QvY29yZS9vcGVyYXRvci9jb21iaW5lL0Jhc2VDb21iaW5lT3BlcmF0b3IuamF2YQ==) | `0.00% <0.00%> (-88.00%)` | :arrow_down: |
   | [...core/operator/combine/DistinctCombineOperator.java](https://codecov.io/gh/apache/pinot/pull/8979/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-cGlub3QtY29yZS9zcmMvbWFpbi9qYXZhL29yZy9hcGFjaGUvcGlub3QvY29yZS9vcGVyYXRvci9jb21iaW5lL0Rpc3RpbmN0Q29tYmluZU9wZXJhdG9yLmphdmE=) | `0.00% <0.00%> (-84.62%)` | :arrow_down: |
   | [...perator/combine/GroupByOrderByCombineOperator.java](https://codecov.io/gh/apache/pinot/pull/8979/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-cGlub3QtY29yZS9zcmMvbWFpbi9qYXZhL29yZy9hcGFjaGUvcGlub3QvY29yZS9vcGVyYXRvci9jb21iaW5lL0dyb3VwQnlPcmRlckJ5Q29tYmluZU9wZXJhdG9yLmphdmE=) | `0.00% <0.00%> (-82.76%)` | :arrow_down: |
   | [...nMaxValueBasedSelectionOrderByCombineOperator.java](https://codecov.io/gh/apache/pinot/pull/8979/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-cGlub3QtY29yZS9zcmMvbWFpbi9qYXZhL29yZy9hcGFjaGUvcGlub3QvY29yZS9vcGVyYXRvci9jb21iaW5lL01pbk1heFZhbHVlQmFzZWRTZWxlY3Rpb25PcmRlckJ5Q29tYmluZU9wZXJhdG9yLmphdmE=) | `0.00% <0.00%> (-74.81%)` | :arrow_down: |
   | [...operator/combine/SelectionOnlyCombineOperator.java](https://codecov.io/gh/apache/pinot/pull/8979/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-cGlub3QtY29yZS9zcmMvbWFpbi9qYXZhL29yZy9hcGFjaGUvcGlub3QvY29yZS9vcGVyYXRvci9jb21iaW5lL1NlbGVjdGlvbk9ubHlDb21iaW5lT3BlcmF0b3IuamF2YQ==) | `0.00% <0.00%> (-62.07%)` | :arrow_down: |
   | [...rator/combine/SelectionOrderByCombineOperator.java](https://codecov.io/gh/apache/pinot/pull/8979/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-cGlub3QtY29yZS9zcmMvbWFpbi9qYXZhL29yZy9hcGFjaGUvcGlub3QvY29yZS9vcGVyYXRvci9jb21iaW5lL1NlbGVjdGlvbk9yZGVyQnlDb21iaW5lT3BlcmF0b3IuamF2YQ==) | `0.00% <0.00%> (-55.18%)` | :arrow_down: |
   | ... and [1397 more](https://codecov.io/gh/apache/pinot/pull/8979/diff?src=pr&el=tree-more&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation) | |
   
   ------
   
   [Continue to review full report at Codecov](https://codecov.io/gh/apache/pinot/pull/8979?src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation).
   > **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation)
   > `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
   > Powered by [Codecov](https://codecov.io/gh/apache/pinot/pull/8979?src=pr&el=footer&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation). Last update [3ff4d13...38f397c](https://codecov.io/gh/apache/pinot/pull/8979?src=pr&el=lastupdated&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation).
   


-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] Jackie-Jiang commented on a diff in pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
Jackie-Jiang commented on code in PR #8979:
URL: https://github.com/apache/pinot/pull/8979#discussion_r961853918


##########
pinot-core/src/main/java/org/apache/pinot/core/operator/blocks/IntermediateResultsBlock.java:
##########
@@ -587,4 +600,101 @@ public BlockDocIdValueSet getBlockDocIdValueSet() {
   public BlockMetadata getMetadata() {
     throw new UnsupportedOperationException();
   }
+
+  public static class ListSelection extends IntermediateResultsBlock {

Review Comment:
   I agree. Ideally the comparator should be within the combine operator instead of the results block, and that's why I suggest not changing this class too much, but do a cleanup separately to move the comparator into the operator.



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] gortiz commented on a diff in pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
gortiz commented on code in PR #8979:
URL: https://github.com/apache/pinot/pull/8979#discussion_r960574343


##########
pinot-core/src/main/java/org/apache/pinot/core/plan/SelectionPlanNode.java:
##########
@@ -50,67 +52,113 @@ public Operator<IntermediateResultsBlock> run() {
     List<ExpressionContext> expressions = SelectionOperatorUtils.extractExpressions(_queryContext, _indexSegment);
     int limit = _queryContext.getLimit();
 
-    if (limit > 0) {
-      List<OrderByExpressionContext> orderByExpressions = _queryContext.getOrderByExpressions();
-      if (orderByExpressions == null) {
-        // Selection only
-        TransformOperator transformOperator = new TransformPlanNode(_indexSegment, _queryContext, expressions,
-            Math.min(limit, DocIdSetPlanNode.MAX_DOC_PER_CALL)).run();
-        return new SelectionOnlyOperator(_indexSegment, _queryContext, expressions, transformOperator);
-      } else {
-        // Selection order-by
-        if (isAllOrderByColumnsSorted(orderByExpressions)) {
-          // All order-by columns are sorted, no need to sort the records
-          TransformOperator transformOperator = new TransformPlanNode(_indexSegment, _queryContext, expressions,
-              Math.min(limit + _queryContext.getOffset(), DocIdSetPlanNode.MAX_DOC_PER_CALL)).run();
-          return new SelectionOrderByOperator(_indexSegment, _queryContext, expressions, transformOperator, true);
-        } else if (orderByExpressions.size() == expressions.size()) {
-          // All output expressions are ordered
-          TransformOperator transformOperator =
-              new TransformPlanNode(_indexSegment, _queryContext, expressions, DocIdSetPlanNode.MAX_DOC_PER_CALL).run();
-          return new SelectionOrderByOperator(_indexSegment, _queryContext, expressions, transformOperator, false);
-        } else {
-          // Not all output expressions are ordered, only fetch the order-by expressions and docId to avoid the
-          // unnecessary data fetch
-          List<ExpressionContext> expressionsToTransform = new ArrayList<>(orderByExpressions.size());
-          for (OrderByExpressionContext orderByExpression : orderByExpressions) {
-            expressionsToTransform.add(orderByExpression.getExpression());
-          }
-          TransformOperator transformOperator =
-              new TransformPlanNode(_indexSegment, _queryContext, expressionsToTransform,
-                  DocIdSetPlanNode.MAX_DOC_PER_CALL).run();
-          return new SelectionOrderByOperator(_indexSegment, _queryContext, expressions, transformOperator, false);
-        }
-      }
-    } else {
+    if (limit == 0) {
       // Empty selection (LIMIT 0)
       TransformOperator transformOperator = new TransformPlanNode(_indexSegment, _queryContext, expressions, 0).run();
       return new EmptySelectionOperator(_indexSegment, expressions, transformOperator);
     }
+    List<OrderByExpressionContext> orderByExpressions = _queryContext.getOrderByExpressions();
+
+    if (orderByExpressions == null) {
+      // Selection only
+      // ie: SELECT ... FROM Table WHERE ... LIMIT 10
+      int actualLimit = Math.min(limit, DocIdSetPlanNode.MAX_DOC_PER_CALL);
+      TransformPlanNode planNode = new TransformPlanNode(_indexSegment, _queryContext, expressions, actualLimit);
+      TransformOperator transformOperator = planNode.run();
+
+      return new SelectionOnlyOperator(_indexSegment, _queryContext, expressions, transformOperator);
+    }
+    int numOrderByExpressions = orderByExpressions.size();
+    // Although it is a break of abstraction, some code, specially merging, assumes that if there is an order by
+    // expression the operator will return a block whose selection result is a priority queue.
+    int sortedColumnsPrefixSize = getSortedColumnsPrefix(orderByExpressions);

Review Comment:
   Let me verify if I correctly understand it. Given a table `T` with three rows where with a single column called `col` whose values are `1`, `null` and `2`.
   
   1. `col` is considered sorted.
   2. If the default null value of `col` is null, `select col from T order by T` should return `1`, `2`, `null`
   
   Is that right? And if it is... why do we considered `col` a sorted column if, in fact, it is not sorted in the segment? More formally, given for each d1 and d2 such as d1 < d2 then it is not guaranteed that segment[d1][col] <= segment[d2][col]



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] gortiz commented on a diff in pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
gortiz commented on code in PR #8979:
URL: https://github.com/apache/pinot/pull/8979#discussion_r982653377


##########
pinot-core/src/main/java/org/apache/pinot/core/operator/query/OrderByComparatorFactory.java:
##########
@@ -0,0 +1,170 @@
+/**
+ * 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.pinot.core.operator.query;
+
+import com.google.common.base.Preconditions;
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.List;
+import org.apache.pinot.common.request.context.OrderByExpressionContext;
+import org.apache.pinot.core.operator.transform.TransformResultMetadata;
+import org.apache.pinot.spi.data.FieldSpec;
+import org.apache.pinot.spi.exception.BadQueryRequestException;
+import org.apache.pinot.spi.utils.ByteArray;
+
+
+/**
+ * A utility class used to create comparators that should be used by operators that implements order by semantics.
+ */
+public class OrderByComparatorFactory {
+
+  private OrderByComparatorFactory() {
+  }
+
+  public static Comparator<Object[]> getComparator(List<OrderByExpressionContext> orderByExpressions,
+      TransformResultMetadata[] orderByExpressionMetadata, boolean asc, boolean nullHandlingEnabled) {

Review Comment:
   I called it `direct` in the other overloaded method, but reverse is quite better.



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] Jackie-Jiang commented on a diff in pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
Jackie-Jiang commented on code in PR #8979:
URL: https://github.com/apache/pinot/pull/8979#discussion_r981764533


##########
pinot-core/src/main/java/org/apache/pinot/core/operator/combine/BaseCombineOperator.java:
##########
@@ -157,23 +157,31 @@ protected void processSegments() {
     int operatorId;
     while ((operatorId = _nextOperatorId.getAndIncrement()) < _numOperators) {
       Operator operator = _operators.get(operatorId);
-      T resultsBlock;
+      BaseResultsBlock operatorBlock;
       try {
         if (operator instanceof AcquireReleaseColumnsSegmentOperator) {
           ((AcquireReleaseColumnsSegmentOperator) operator).acquire();
         }
-        resultsBlock = (T) operator.nextBlock();
+        operatorBlock = (BaseResultsBlock) operator.nextBlock();
       } finally {
         if (operator instanceof AcquireReleaseColumnsSegmentOperator) {
           ((AcquireReleaseColumnsSegmentOperator) operator).release();
         }
       }
-      if (isQuerySatisfied(resultsBlock)) {
+
+      T resultBlock;

Review Comment:
   (minor) keep the variable name as `resultsBlock`



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] Jackie-Jiang commented on a diff in pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
Jackie-Jiang commented on code in PR #8979:
URL: https://github.com/apache/pinot/pull/8979#discussion_r981779653


##########
pinot-core/src/main/java/org/apache/pinot/core/operator/combine/MinMaxValueBasedSelectionOrderByCombineOperator.java:
##########
@@ -211,30 +211,51 @@ protected void processSegments() {
           ((AcquireReleaseColumnsSegmentOperator) operator).release();
         }
       }
-      PriorityQueue<Object[]> selectionResult = (PriorityQueue<Object[]>) resultsBlock.getRows();
-      if (selectionResult != null && selectionResult.size() == _numRowsToKeep) {
-        // Segment result has enough rows, update the boundary value
-        assert selectionResult.peek() != null;
-        Comparable segmentBoundaryValue = (Comparable) selectionResult.peek()[0];
-        if (boundaryValue == null) {
-          boundaryValue = segmentBoundaryValue;
-        } else {
-          if (asc) {
-            if (segmentBoundaryValue.compareTo(boundaryValue) < 0) {
-              boundaryValue = segmentBoundaryValue;
-            }
-          } else {
-            if (segmentBoundaryValue.compareTo(boundaryValue) > 0) {
-              boundaryValue = segmentBoundaryValue;
-            }
-          }
-        }
+      Collection<Object[]> rows = resultsBlock.getRows();
+      if (rows != null && rows.size() >= _numRowsToKeep) {
+        boundaryValue = updateBoundaryValue(boundaryValue, extractBoundaryValue(rows), asc);
       }
       threadBoundaryValue = boundaryValue;
       _blockingQueue.offer(resultsBlock);
     }
   }
 
+  private Comparable extractBoundaryValue(Collection<Object[]> rows) {
+    if (rows instanceof PriorityQueue) {
+      PriorityQueue<Object[]> selectionResult = (PriorityQueue<Object[]>) rows;
+      assert selectionResult.peek() != null;
+      // at this point, priority queues are sorted in the inverse order
+      return (Comparable) selectionResult.peek()[0];
+    }
+    List<Object[]> selectionResult;
+    if (rows instanceof List) {
+      selectionResult = (List<Object[]>) rows;
+    } else {
+      LOGGER.warn("Selection result stored in an unexpected data structure of type {}. A copy is needed",

Review Comment:
   I don't see how we can enforce that because people can change the code in `SelectionResultsBlock`. What we want to prevent is someone adding `Set` as the rows, and we want it to fail so that people can find the missing code here. Essentially something like:
   ```
   if (rows instanceof PriorityQueue) {
     ...
   }
   if (rows instanceof List) {
     ...
   }
   throw new IllegalStateException("Got unexpected rows class: " + rows.getClass());
   ```



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] Jackie-Jiang merged pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
Jackie-Jiang merged PR #8979:
URL: https://github.com/apache/pinot/pull/8979


-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] walterddr commented on pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
walterddr commented on PR #8979:
URL: https://github.com/apache/pinot/pull/8979#issuecomment-1187587417

   > I think I finally found why the test was failing. It was due to a `cmp >= 0` assertion that should be `cmp <= 0`. The reason that made it very hard to find the problem is that `BaseCombineOperator` is not prepared to catch `Errors`, so the task at the server just failed without printing any log and as a result the broker didn't receive a response, so the error shown in the broker was that some server didn't answer.
   > 
   > Things to know about:
   > 
   > * Pinot may not log `AssertionErrors`, so it is better to do not use `assert` expressions
   > * We may or may not want to log in case we receive an error. As I don't know what do we want to do in that case, I've just changed my code to throw an `ArgumentException`.
   
   +1. can we file an issue for fixing the AssertException not surfacing problem? 


-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] gortiz commented on a diff in pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
gortiz commented on code in PR #8979:
URL: https://github.com/apache/pinot/pull/8979#discussion_r973875208


##########
pinot-core/src/main/java/org/apache/pinot/core/operator/query/SelectionPartiallyOrderedByOperator.java:
##########
@@ -0,0 +1,303 @@
+/**
+ * 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.pinot.core.operator.query;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+import javax.annotation.Nullable;
+import org.apache.pinot.common.request.context.ExpressionContext;
+import org.apache.pinot.common.request.context.OrderByExpressionContext;
+import org.apache.pinot.common.utils.DataSchema;
+import org.apache.pinot.core.common.BlockValSet;
+import org.apache.pinot.core.common.Operator;
+import org.apache.pinot.core.common.RowBasedBlockValueFetcher;
+import org.apache.pinot.core.operator.BaseOperator;
+import org.apache.pinot.core.operator.ExecutionStatistics;
+import org.apache.pinot.core.operator.blocks.IntermediateResultsBlock;
+import org.apache.pinot.core.operator.blocks.TransformBlock;
+import org.apache.pinot.core.operator.transform.TransformOperator;
+import org.apache.pinot.core.operator.transform.TransformResultMetadata;
+import org.apache.pinot.core.query.request.context.QueryContext;
+import org.apache.pinot.core.query.selection.SelectionOperatorUtils;
+import org.apache.pinot.segment.spi.IndexSegment;
+
+
+/**
+ * An operator for order-by queries that are partially sorted over the sorting keys.
+ */
+public class SelectionPartiallyOrderedByOperator extends BaseOperator<IntermediateResultsBlock> {
+
+  private static final String EXPLAIN_NAME = "SELECT_PARTIAL_ORDERBY";
+
+  private final IndexSegment _indexSegment;
+
+  // Deduped order-by expressions followed by output expressions from SelectionOperatorUtils.extractExpressions()
+  private final List<ExpressionContext> _expressions;
+  private final List<ExpressionContext> _alreadySorted;
+  private final List<ExpressionContext> _toSort;
+
+  private final TransformOperator _transformOperator;
+  private final List<OrderByExpressionContext> _orderByExpressions;
+  private final TransformResultMetadata[] _expressionsMetadata;
+  private final int _numRowsToKeep;
+  private final PartiallySortedListBuilder _sorter;
+
+  private int _numDocsScanned = 0;
+  private long _numEntriesScannedPostFilter = 0;
+  private boolean _used = false;
+  private Comparator<Object[]> _comparator;
+
+  public SelectionPartiallyOrderedByOperator(IndexSegment indexSegment, QueryContext queryContext,
+      List<ExpressionContext> expressions, TransformOperator transformOperator, int sortedExpr) {
+    Preconditions.checkArgument(sortedExpr > 0,
+        "This operator should not be used when sorting expressions doesn't start with sorted expressions");
+    _indexSegment = indexSegment;
+    _expressions = expressions;
+    _transformOperator = transformOperator;
+
+    _orderByExpressions = queryContext.getOrderByExpressions();
+    assert _orderByExpressions != null;
+    int numOrderByExpressions = _orderByExpressions.size();
+
+    _alreadySorted = expressions.subList(0, sortedExpr);
+    _toSort = expressions.subList(sortedExpr, numOrderByExpressions);
+
+    Preconditions.checkArgument(!_toSort.isEmpty(),
+        "This operator should not be used when all sorting expressions are sorted. "
+            + "Use %s instead", SelectionOrderByOperator.class.getName());
+
+    _expressionsMetadata = new TransformResultMetadata[_expressions.size()];
+    for (int i = 0; i < _expressionsMetadata.length; i++) {
+      ExpressionContext expression = _expressions.get(i);
+      _expressionsMetadata[i] = _transformOperator.getResultMetadata(expression);
+    }
+
+    _numRowsToKeep = queryContext.getOffset() + queryContext.getLimit();
+
+    int expectedSize = Math.min(_numRowsToKeep * 2, SelectionOperatorUtils.MAX_ROW_HOLDER_INITIAL_CAPACITY);
+    Comparator<Object[]> sortedComparator =
+        SelectionOrderByOperator.getComparator(_orderByExpressions, _expressionsMetadata, true, 0, sortedExpr);
+    Comparator<Object[]> unsortedComparator =
+        SelectionOrderByOperator.getComparator(_orderByExpressions, _expressionsMetadata, true, sortedExpr,
+            numOrderByExpressions);
+    _sorter = new PartiallySortedListBuilder(expectedSize, sortedComparator, unsortedComparator);
+    _comparator = SelectionOrderByOperator.getComparator(_orderByExpressions, _expressionsMetadata, false);
+  }
+
+  @Override
+  public List<Operator> getChildOperators() {
+    return Collections.singletonList(_transformOperator);
+  }
+
+  @Override
+  protected IntermediateResultsBlock getNextBlock() {
+    if (!_used) {
+      _used = true;
+      fetch();
+
+      DataSchema dataSchema = createDataSchema();
+
+      return new IntermediateResultsBlock.ListSelection(dataSchema, _sorter.build(), _comparator);
+    }
+    return null;
+  }
+
+  private DataSchema createDataSchema() {
+
+    int numExpressions = _expressions.size();
+
+    // Create the data schema
+    String[] columnNames = new String[numExpressions];
+    DataSchema.ColumnDataType[] columnDataTypes = new DataSchema.ColumnDataType[numExpressions];
+    for (int i = 0; i < columnNames.length; i++) {
+      columnNames[i] = _expressions.get(i).toString();
+    }
+    for (int i = 0; i < numExpressions; i++) {
+      TransformResultMetadata expressionMetadata = _expressionsMetadata[i];
+      columnDataTypes[i] =
+          DataSchema.ColumnDataType.fromDataType(expressionMetadata.getDataType(), expressionMetadata.isSingleValue());
+    }
+    return new DataSchema(columnNames, columnDataTypes);
+  }
+
+  /**
+   * Fetches the rows that are needed into {@link #_sorter} and updated the metrics.
+   *
+   * The sorter can still be used.
+   */
+  private void fetch() {
+    int numExpressions = _expressions.size();
+    BlockValSet[] blockValSets = new BlockValSet[numExpressions];
+
+    TransformBlock transformBlock;
+    int numColumnsProjected = _transformOperator.getNumColumnsProjected();
+    try {
+      while ((transformBlock = _transformOperator.nextBlock()) != null) {
+        for (int i = 0; i < numExpressions; i++) {
+          ExpressionContext expression = _expressions.get(i);
+          blockValSets[i] = transformBlock.getBlockValueSet(expression);
+        }
+        RowBasedBlockValueFetcher blockValueFetcher = new RowBasedBlockValueFetcher(blockValSets);
+        int numDocsFetched = transformBlock.getNumDocs();
+        _numDocsScanned += numDocsFetched;
+        for (int i = 0; i < numDocsFetched; i++) {
+          boolean newBlock = _sorter.add(blockValueFetcher.getRow(i));
+          if (newBlock && _sorter.sortedSize() >= _numRowsToKeep) {
+            // We changed to a new section to ordered sorted values and we have more values than required.
+            // Therefore, we can stop the execution here.
+            return;
+          }
+        }
+      }
+    } finally {
+      _numEntriesScannedPostFilter = (long) _numDocsScanned * numColumnsProjected;
+    }
+  }
+
+  @Override
+  public String toExplainString() {
+    StringBuilder sb = new StringBuilder(EXPLAIN_NAME);
+
+    sb.append("(sortedList: ");
+    concatList(sb, _alreadySorted);
+
+    sb.append(", unsortedList: ");
+    concatList(sb, _toSort);
+
+    sb.append(", rest: ");
+    concatList(sb, _expressions.subList(_alreadySorted.size() + _toSort.size(), _expressions.size()));
+
+    sb.append(')');
+    return sb.toString();
+  }
+
+  private void concatList(StringBuilder sb, List<?> list) {
+    sb.append('(');
+    Iterator<?> it = list.iterator();
+    if (it.hasNext()) {
+      sb.append(it.next());
+      while (it.hasNext()) {
+        sb.append(", ").append(it.next());
+      }
+    }
+    sb.append(')');
+  }
+
+  @Override
+  public ExecutionStatistics getExecutionStatistics() {
+    long numEntriesScannedInFilter = _transformOperator.getExecutionStatistics().getNumEntriesScannedInFilter();
+    int numTotalDocs = _indexSegment.getSegmentMetadata().getTotalDocs();
+    return new ExecutionStatistics(_numDocsScanned, numEntriesScannedInFilter, _numEntriesScannedPostFilter,
+        numTotalDocs);
+  }
+
+  /**
+   * A private class used to build a sorted list by adding partially sorted data.
+   *
+   * Specifically, this class has been designed to receive successive calls to {@link #add(Object[])} follow by a single
+   * call to {@link #build()}. Once this method is called, the behavior of this object is undefined and therefore it
+   * should not be used.
+   *
+   * Rows must be inserted in ascending order accordingly to the partial order specified by {@link #_sortedComparator}.
+   * This comparator will define <i>partitions</i> of rows. All the rows in the same partition same are considered equal
+   * by that comparator.
+   *
+   * There is a second comparator called {@link #_unsortedComparator} that is used to sort rows inside each partition.
+   * When calling {@link #add(Object[])} with a row that doesn't belong to the current partition, a new one is started
+   * and the previous one is sorted. Therefore, this object maintains the invariant that at any moment there are at
+   * least {@link #sortedSize()} elements that are completely sorted, which means that no matter which elements are
+   * added after that, these elements are going to be smallest.
+   */
+  private static class PartiallySortedListBuilder {
+    private final ArrayList<Object[]> _rows;
+    private final Comparator<Object[]> _sortedComparator;
+    private final Comparator<Object[]> _unsortedComparator;
+
+    public PartiallySortedListBuilder(int expectedSize, Comparator<Object[]> sortedComparator,
+        Comparator<Object[]> unsortedComparator) {
+      _rows = new ArrayList<>(expectedSize);
+      _sortedComparator = sortedComparator;
+      _unsortedComparator = unsortedComparator;
+    }
+
+    @Nullable
+    private Object[] _lastBlockRow;
+    private int _lastSorted;
+
+    /**
+     * Adds the given row to this object. The new column must be equal or higher than the last added row in relation to
+     * {@link #_sortedComparator}.
+     *
+     * @param row The row to add. The values of the already sorted columns must be equal or higher than the last added
+     *           row, if any.
+     * @return true if and only if the previous block was closed.
+     */
+    boolean add(Object[] row) {
+      boolean result;
+      if (_lastBlockRow == null) {
+        _lastSorted = 0;
+        _lastBlockRow = row;
+        result = false;
+      } else {
+        int cmp = _sortedComparator.compare(_lastBlockRow, row);
+        assert cmp >= 0 : "Row " + Arrays.toString(row) + " is lower than previously added row"

Review Comment:
   This assertion was changed with an explicit `if` given that in case of failure, the `AssetionError` is not caught by Pinot job, so the error is lost.



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] gortiz commented on pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
gortiz commented on PR #8979:
URL: https://github.com/apache/pinot/pull/8979#issuecomment-1250593801

   > Seems like a great optimization. Any plans of resuming this ?
   
   If I remember correctly there are two things we would need to improve:
   - Disable the optimization when null handling is active
   - Decide whether we should remove the descending optimization or not. As suggested by @Jackie-Jiang, it would make more sense (and be more efficient) to have descending operators. The current solution in this PR runs faster than the previous code, but given the complexities of the code, it is difficult to be sure whether the solution is always correct or not.


-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] Jackie-Jiang commented on a diff in pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
Jackie-Jiang commented on code in PR #8979:
URL: https://github.com/apache/pinot/pull/8979#discussion_r981791146


##########
pinot-core/src/main/java/org/apache/pinot/core/operator/query/LinearSelectionOrderByOperator.java:
##########
@@ -0,0 +1,476 @@
+/**
+ * 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.pinot.core.operator.query;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+import java.util.PriorityQueue;
+import java.util.function.IntFunction;
+import java.util.function.Supplier;
+import javax.annotation.Nullable;
+import org.apache.pinot.common.request.context.ExpressionContext;
+import org.apache.pinot.common.request.context.OrderByExpressionContext;
+import org.apache.pinot.common.utils.DataSchema;
+import org.apache.pinot.core.common.BlockValSet;
+import org.apache.pinot.core.common.Operator;
+import org.apache.pinot.core.common.RowBasedBlockValueFetcher;
+import org.apache.pinot.core.operator.BaseOperator;
+import org.apache.pinot.core.operator.ExecutionStatistics;
+import org.apache.pinot.core.operator.blocks.TransformBlock;
+import org.apache.pinot.core.operator.blocks.results.SelectionResultsBlock;
+import org.apache.pinot.core.operator.transform.TransformOperator;
+import org.apache.pinot.core.operator.transform.TransformResultMetadata;
+import org.apache.pinot.core.query.request.context.QueryContext;
+import org.apache.pinot.core.query.selection.SelectionOperatorUtils;
+import org.apache.pinot.segment.spi.IndexSegment;
+import org.roaringbitmap.RoaringBitmap;
+
+
+/**
+ * A selection Operator used when the first expressions in the order by are identifier expressions of columns that are
+ * already sorted (either ascendingly or descendingly), even if the tail of order by expressions are not sorted.
+ *
+ * ie: SELECT ... FROM Table WHERE predicates ORDER BY sorted_column DESC LIMIT 10 OFFSET 5
+ * or: SELECT ... FROM Table WHERE predicates ORDER BY sorted_column, not_sorted LIMIT 10 OFFSET 5
+ * but not SELECT ... FROM Table WHERE predicates ORDER BY not_sorted, sorted_column LIMIT 10 OFFSET 5
+ *
+ * Operators that derives from this class are going to have an almost linear cost instead of the usual NlogN when actual
+ * sorting must be done, where N is the number of rows in the segment.
+ * There is a degraded scenario when the cost is actually NlogL (where L is the limit of the query) when all the first L
+ * rows have the exact same value for the prefix of the sorted columns. Even in that case, L should be quite smaller
+ * than N, so this implementation is algorithmically better than the normal solution.
+ */
+public abstract class LinearSelectionOrderByOperator extends BaseOperator<SelectionResultsBlock> {
+  protected final IndexSegment _indexSegment;
+
+  protected final boolean _nullHandlingEnabled;
+  // Deduped order-by expressions followed by output expressions from SelectionOperatorUtils.extractExpressions()
+  protected final List<ExpressionContext> _expressions;
+  protected final List<ExpressionContext> _alreadySorted;
+  protected final List<ExpressionContext> _toSort;
+
+  protected final TransformOperator _transformOperator;
+  protected final List<OrderByExpressionContext> _orderByExpressions;
+  protected final TransformResultMetadata[] _expressionsMetadata;
+  protected final int _numRowsToKeep;
+  private final Supplier<ListBuilder> _listBuilderSupplier;
+  protected boolean _used = false;
+  protected Comparator<Object[]> _comparator;
+
+  /**
+   *
+   * @param expressions order by expressions must be at the head of the list.
+   * @param sortedExpr How many expressions at the head of the expression list are going to be considered sorted by
+   * {@link #fetch(Supplier<ListBuilder>)}
+   */
+  public LinearSelectionOrderByOperator(IndexSegment indexSegment, QueryContext queryContext,
+      List<ExpressionContext> expressions, TransformOperator transformOperator,
+      int sortedExpr) {
+    _indexSegment = indexSegment;
+    _nullHandlingEnabled = queryContext.isNullHandlingEnabled();
+    _expressions = expressions;
+    _transformOperator = transformOperator;
+
+    _orderByExpressions = queryContext.getOrderByExpressions();
+    assert _orderByExpressions != null;
+    int numOrderByExpressions = _orderByExpressions.size();
+
+    _alreadySorted = expressions.subList(0, sortedExpr);
+    _toSort = expressions.subList(sortedExpr, numOrderByExpressions);
+
+    _expressionsMetadata = new TransformResultMetadata[_expressions.size()];
+    for (int i = 0; i < _expressionsMetadata.length; i++) {
+      ExpressionContext expression = _expressions.get(i);
+      _expressionsMetadata[i] = _transformOperator.getResultMetadata(expression);
+    }
+
+    _numRowsToKeep = queryContext.getOffset() + queryContext.getLimit();
+
+    if (_toSort.isEmpty()) {
+      int expectedSize = Math.min(SelectionOperatorUtils.MAX_ROW_HOLDER_INITIAL_CAPACITY, _numRowsToKeep);
+      _listBuilderSupplier = () -> new TotallySortedListBuilder(expectedSize);
+    } else {
+      int maxSize = Math.min(SelectionOperatorUtils.MAX_ROW_HOLDER_INITIAL_CAPACITY, _numRowsToKeep * 2);
+
+      Comparator<Object[]> sortedComparator = OrderByComparatorFactory.getComparator(_orderByExpressions,
+          _expressionsMetadata, true, _nullHandlingEnabled, 0, sortedExpr);
+      Comparator<Object[]> unsortedComparator = OrderByComparatorFactory.getComparator(_orderByExpressions,
+          _expressionsMetadata, true, _nullHandlingEnabled, sortedExpr, numOrderByExpressions);
+      _listBuilderSupplier = () -> new PartiallySortedListBuilder(maxSize, sortedComparator, unsortedComparator);
+    }
+
+    _comparator =
+        OrderByComparatorFactory.getComparator(_orderByExpressions, _expressionsMetadata, false, _nullHandlingEnabled);
+  }
+
+  @Override
+  public IndexSegment getIndexSegment() {
+    return _indexSegment;
+  }
+
+  @Override
+  public ExecutionStatistics getExecutionStatistics() {
+    long numEntriesScannedInFilter = _transformOperator.getExecutionStatistics().getNumEntriesScannedInFilter();
+    int numTotalDocs = _indexSegment.getSegmentMetadata().getTotalDocs();
+    return new ExecutionStatistics(getNumDocsScanned(), numEntriesScannedInFilter, getNumEntriesScannedPostFilter(),
+        numTotalDocs);
+  }
+
+  protected IntFunction<Object[]> fetchBlock(TransformBlock transformBlock, BlockValSet[] blockValSets) {
+    int numExpressions = _expressions.size();
+
+    for (int i = 0; i < numExpressions; i++) {
+      ExpressionContext expression = _expressions.get(i);
+      blockValSets[i] = transformBlock.getBlockValueSet(expression);
+    }
+    RowBasedBlockValueFetcher blockValueFetcher = new RowBasedBlockValueFetcher(blockValSets);
+
+    if (!_nullHandlingEnabled) {
+      return blockValueFetcher::getRow;
+    }
+    RoaringBitmap[] nullBitmaps = new RoaringBitmap[numExpressions];
+    for (int i = 0; i < numExpressions; i++) {
+      nullBitmaps[i] = blockValSets[i].getNullBitmap();
+    }
+    return (docId) -> {
+      Object[] row = blockValueFetcher.getRow(docId);
+      for (int colId = 0; colId < nullBitmaps.length; colId++) {
+        if (nullBitmaps[colId] != null && nullBitmaps[colId].contains(docId)) {
+          row[colId] = null;
+        }
+      }
+      return row;
+    };
+  }
+
+  protected abstract long getNumEntriesScannedPostFilter();
+
+  protected abstract int getNumDocsScanned();
+
+  /**
+   * Returns a list of rows sorted that:
+   * <ul>
+   *   <li>At least contains all the rows that fulfill the predicate</li>
+   *   <li>Rows are sorted in a way that is compatible with the given list builder supplier</li>
+   * </ul>
+   *
+   * That means that the result may contain more rows than required.
+   *
+   * @param listBuilderSupplier a {@link ListBuilder} supplier that should be used to create the result. Each time is
+   *                            called a new {@link ListBuilder} will be returned. All returned instances use the same
+   *                            comparator logic.
+   */
+  protected abstract List<Object[]> fetch(Supplier<ListBuilder> listBuilderSupplier);
+
+  @Override
+  public List<Operator> getChildOperators() {
+    return Collections.singletonList(_transformOperator);
+  }
+
+  protected abstract String getExplainName();
+
+  @Override
+  public String toExplainString() {
+    StringBuilder sb = new StringBuilder(getExplainName());
+
+    sb.append("(sortedList: ");
+    concatList(sb, _alreadySorted);
+
+    sb.append(", unsortedList: ");
+    concatList(sb, _toSort);
+
+    sb.append(", rest: ");
+    concatList(sb, _expressions.subList(_alreadySorted.size() + _toSort.size(), _expressions.size()));
+
+    sb.append(')');
+    return sb.toString();
+  }
+
+  private void concatList(StringBuilder sb, List<?> list) {
+    sb.append('(');
+    Iterator<?> it = list.iterator();
+    if (it.hasNext()) {
+      sb.append(it.next());
+      while (it.hasNext()) {
+        sb.append(", ").append(it.next());
+      }
+    }
+    sb.append(')');
+  }
+
+  @Override
+  protected SelectionResultsBlock getNextBlock() {
+    Preconditions.checkState(!_used, "nextBlock was called more than once");
+    _used = true;
+    List<Object[]> list = fetch(_listBuilderSupplier);
+
+    DataSchema dataSchema = createDataSchema();
+
+    if (list.size() > _numRowsToKeep) {
+      list = new ArrayList<>(list.subList(0, _numRowsToKeep));
+    }
+
+    SelectionResultsBlock resultsBlock = new SelectionResultsBlock(dataSchema, list, _comparator);
+
+    return resultsBlock;
+  }
+
+  protected DataSchema createDataSchema() {
+    int numExpressions = _expressions.size();
+
+    // Create the data schema
+    String[] columnNames = new String[numExpressions];
+    DataSchema.ColumnDataType[] columnDataTypes = new DataSchema.ColumnDataType[numExpressions];
+    for (int i = 0; i < columnNames.length; i++) {
+      columnNames[i] = _expressions.get(i).toString();
+    }
+    for (int i = 0; i < numExpressions; i++) {
+      TransformResultMetadata expressionMetadata = _expressionsMetadata[i];
+      columnDataTypes[i] =
+          DataSchema.ColumnDataType.fromDataType(expressionMetadata.getDataType(), expressionMetadata.isSingleValue());
+    }
+    return new DataSchema(columnNames, columnDataTypes);
+  }
+
+  /**
+   * A private class used to build a sorted list by adding partially sorted data.
+   *
+   * Specifically, this class has been designed to receive successive calls to {@link #add(Object[])} follow by a single
+   * call to {@link #build()}. Once this method is called, the behavior of this object is undefined and therefore it
+   * should not be used.
+   *
+   * Rows must be inserted in ascending order accordingly to the partial order specified by a comparator.
+   * This comparator will define <i>partitions</i> of rows. All the rows in the same partition same are considered equal
+   * by that comparator.
+   *
+   * Some implementations, like {@link PartiallySortedListBuilder} accepts a second comparator that is used to sort rows
+   * inside each partition.
+   * When calling {@link #add(Object[])} with a row that doesn't belong to the current partition, a new one is started
+   * and the previous one is sorted. Therefore, this object maintains the invariant that at any moment there are at
+   * least {@link #sortedSize()} elements that are completely sorted, which means that no matter which elements are
+   * added after that, these elements are going to be smallest.
+   */
+  protected interface ListBuilder {
+
+    /**
+     * Adds the given row to this object. The new column must be equal or higher than the partition comparator.
+     *
+     * @param row The row to add. The values of the already sorted columns must be equal or higher than the last added
+     *           row, if any.
+     * @return true if and only if the previous partition was closed.
+     */
+    boolean add(Object[] row);
+
+    /**
+     * Builds the sorted list. The returned list will be sorted, even if a previous call t o {@link #sortedSize()}
+     * returned a number lower than the number of elements that have been added.
+     *
+     * Once this method is called, the builder should not be used. There is no guaranteed on whether
+     * {@link #sortedSize()} is updated or not.
+     */
+    List<Object[]> build();
+
+    /**
+     * How many elements are actually sorted. This number is lower or equal to the number of elements that has been
+     * added.
+     */
+    int sortedSize();
+  }
+
+  /**
+   * This is the faster {@link ListBuilder} but also the most restrictive one. It can only be used when data is inserted
+   * in total order. Therefore it cannot be used to implement order-by queries where there is at least one expression
+   * that is not sorted. In such case {@link PartiallySortedListBuilder} should be used.
+   *
+   * This implementation is just a wrapper over an ArrayList and therefore the average costs of its methods is constant.
+   */
+  protected static class TotallySortedListBuilder implements ListBuilder {
+    private final ArrayList<Object[]> _list;
+
+    public TotallySortedListBuilder(int expectedSize) {
+      _list = new ArrayList<>(expectedSize);
+    }
+
+    @Override
+    public boolean add(Object[] row) {
+      _list.add(row);
+      return true;
+    }
+
+    @Override
+    public List<Object[]> build() {
+      return _list;
+    }
+
+    @Override
+    public int sortedSize() {
+      return _list.size();
+    }
+  }
+
+  /**
+   * This is the more versatile {@link ListBuilder} that requires two comparators: The first defines the order on which
+   * {@link #add(Object[])} is called and defines the partitions. The second one is used to sort rows in the same
+   * partition. This class can be used to implement order-by queries that include one or more not sorted expressions.
+   * In cases where all expressions are sorted, {@link TotallySortedListBuilder} should be used because its performance
+   * is better.
+   *
+   * In this implementation the {@link #add(Object[])} method has a log(P) cost, where P is the number of elements in
+   * each partition. In normal cases we can consider P a constant. In some degenerated cases like having an ordering by
+   * a sorted column whose values are all equal, P may tend to the number of elements in the segment, which would make
+   * the cost of this method log(N).
+   *
+   * This class is optimized for scenarios where the partitions are smaller than the limit. In that case, the partition
+   * is only sorted once it is closed (aka when a new element for the other partition is found), so each insertion has
+   * an average cost of log(P) (where P-1 insertions are cost O(1) and the last one is O(PlogP)). In cases where at
+   * least one partition is larger than the limit, this implementation delegates the last partition to a
+   * {@link PriorityQueue}.
+   */
+  private static class PartiallySortedListBuilder implements ListBuilder {
+    private final ArrayList<Object[]> _rows;
+    /**
+     * The comparator that defines the partitions and the one that impose in which order add has to be called.
+     */
+    private final Comparator<Object[]> _partitionComparator;
+    /**
+     * The comparator that sorts different rows on each partition.
+     */
+    private final Comparator<Object[]> _unsortedComparator;
+    @Nullable
+    private Object[] _lastPartitionRow;
+    /**
+     * How many elements are already sorted. This is also the index where the last (and still not sorted) partition
+     * starts or should start.
+     */
+    private int _sortedPrefixSize;
+    private final int _maxSize;
+    private PriorityQueue<Object[]> _queue = null;
+    private int _maxPriorityQueueValues;
+
+    public PartiallySortedListBuilder(int maxSize, Comparator<Object[]> partitionComparator,
+        Comparator<Object[]> unsortedComparator) {
+      Preconditions.checkArgument(maxSize > 0, "Max size must be greater than 0");
+      _maxSize = maxSize;
+      _rows = new ArrayList<>(maxSize);
+      _partitionComparator = partitionComparator;
+      _unsortedComparator = unsortedComparator;
+    }
+
+    @Override
+    public boolean add(Object[] row) {
+      boolean result;
+      if (_lastPartitionRow == null) {
+        _sortedPrefixSize = 0;
+        _lastPartitionRow = row;
+        _rows.add(row);
+        return false;
+      } else {
+        int cmp = _partitionComparator.compare(row, _lastPartitionRow);
+        if (cmp < 0) {
+          throw new IllegalArgumentException("Row " + Arrays.toString(row) + " is lower than previously added row"
+              + Arrays.toString(_lastPartitionRow));
+        }
+
+        if (_queue != null) {
+          if (cmp > 0) {
+            // the new row is in a greater partition, just don't add it and continue
+            return true;
+          }
+          // otherwise they are equal by the already sorted columns. Let's check the other columns and evict the higher
+          // also, we have the higher value at the last position
+          SelectionOperatorUtils.addToPriorityQueue(row, _queue, _maxPriorityQueueValues);
+          return false;
+        } else {
+          if (_rows.size() == _maxSize) { // we already have _maxSize results
+            if (cmp > 0) {
+              // and the new one is higher, so we don't need to add it
+              sortLastPartition();
+              return true;
+            }
+            // and the new one may be smaller, so this is going to be the last partition and we need to prepare the
+            // priority queue
+            buildPriorityQueue();
+            SelectionOperatorUtils.addToPriorityQueue(row, _queue, _maxPriorityQueueValues);
+            return false;
+          }
+          if (cmp > 0) {
+            sortLastPartition();
+            _lastPartitionRow = row;
+            result = true;
+          } else {
+            result = false;
+          }
+          _rows.add(row);
+          return result;
+        }
+      }
+    }
+
+    private void buildPriorityQueue() {
+      _maxPriorityQueueValues = _maxSize - _sortedPrefixSize;
+      _queue = new PriorityQueue<>(_maxPriorityQueueValues, _unsortedComparator.reversed());
+      for (int i = 0; i < _maxPriorityQueueValues; i++) {
+        int lastIdx = _rows.size() - 1;
+        _queue.add(_rows.get(lastIdx));
+        _rows.remove(lastIdx);
+      }
+    }
+
+    void sortLastPartition() {

Review Comment:
   Which interface are you referring to? There is no public interface, and everything should be performance driven. I agree the improvement of this PR is huge, but this sort can take majority of the time (check the difference between partial sort and full sort, which should be mostly contributed by it). The contract for the `ListBuilder` is also clear, essentially the sorted columns are guaranteed to be sorted, and the unsorted columns (partial sorted case) is not sorted



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] Jackie-Jiang commented on a diff in pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
Jackie-Jiang commented on code in PR #8979:
URL: https://github.com/apache/pinot/pull/8979#discussion_r981756231


##########
pinot-core/src/main/java/org/apache/pinot/core/operator/blocks/results/SelectionResultsBlock.java:
##########
@@ -45,6 +56,26 @@ public Collection<Object[]> getRows() {
     return _rows;
   }
 
+  public SelectionResultsBlock cloneWithInnerPriorityQueue() {
+    if (_rows instanceof PriorityQueue) {
+      return new SelectionResultsBlock(_dataSchema, new PriorityQueue<>(_rows));

Review Comment:
   I don't follow the advantage though. What I am suggesting is something like:
   ```suggestion
     public SelectionResultsBlock convertToPriorityQueueBased() {
       if (_rows instanceof PriorityQueue) {
         return this;
       }
       if (_comparator == null) {
         throw new IllegalStateException("This instance doesn't define an order on which be sorted");
       }
       PriorityQueue<Object[]> result = new PriorityQueue<>(_comparator);
       result.addAll(_rows);
       return new SelectionResultsBlock(_dataSchema, result);
     }
   ```
   
   The `SelectionResultsBlock` is still immutable. We just don't create a duplicate one when it is already backed by a priority queue.



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] gortiz commented on pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
gortiz commented on PR #8979:
URL: https://github.com/apache/pinot/pull/8979#issuecomment-1261352710

   @Jackie-Jiang I'm going to start a two weeks vacations today. It would be great to merge this PR soon, so if you have time to invest here, feel free to modify whatever you consider in order to merge it.


-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] gortiz commented on pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
gortiz commented on PR #8979:
URL: https://github.com/apache/pinot/pull/8979#issuecomment-1285040079

   I like most of the changes introduced by Jackie, and the ones I don't are mostly cosmetic and subjective, so I'm fine with that. :+1: 


-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] Jackie-Jiang commented on a diff in pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
Jackie-Jiang commented on code in PR #8979:
URL: https://github.com/apache/pinot/pull/8979#discussion_r999853860


##########
pinot-core/src/main/java/org/apache/pinot/core/operator/query/LinearSelectionOrderByOperator.java:
##########
@@ -0,0 +1,452 @@
+/**
+ * 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.pinot.core.operator.query;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+import java.util.PriorityQueue;
+import java.util.function.IntFunction;
+import java.util.function.Supplier;
+import javax.annotation.Nullable;
+import org.apache.pinot.common.request.context.ExpressionContext;
+import org.apache.pinot.common.request.context.OrderByExpressionContext;
+import org.apache.pinot.common.utils.DataSchema;
+import org.apache.pinot.core.common.BlockValSet;
+import org.apache.pinot.core.common.Operator;
+import org.apache.pinot.core.common.RowBasedBlockValueFetcher;
+import org.apache.pinot.core.operator.BaseOperator;
+import org.apache.pinot.core.operator.ExecutionStatistics;
+import org.apache.pinot.core.operator.blocks.TransformBlock;
+import org.apache.pinot.core.operator.blocks.results.SelectionResultsBlock;
+import org.apache.pinot.core.operator.transform.TransformOperator;
+import org.apache.pinot.core.operator.transform.TransformResultMetadata;
+import org.apache.pinot.core.query.request.context.QueryContext;
+import org.apache.pinot.core.query.selection.SelectionOperatorUtils;
+import org.apache.pinot.core.query.utils.OrderByComparatorFactory;
+import org.apache.pinot.segment.spi.IndexSegment;
+import org.roaringbitmap.RoaringBitmap;
+
+
+/**
+ * A selection Operator used when the first expressions in the order by are identifier expressions of columns that are
+ * already sorted (either ascendingly or descendingly), even if the tail of order by expressions are not sorted.
+ *
+ * ie: SELECT ... FROM Table WHERE predicates ORDER BY sorted_column DESC LIMIT 10 OFFSET 5
+ * or: SELECT ... FROM Table WHERE predicates ORDER BY sorted_column, not_sorted LIMIT 10 OFFSET 5
+ * but not SELECT ... FROM Table WHERE predicates ORDER BY not_sorted, sorted_column LIMIT 10 OFFSET 5
+ *
+ * Operators that derives from this class are going to have an almost linear cost instead of the usual NlogN when actual
+ * sorting must be done, where N is the number of rows in the segment.
+ * There is a degraded scenario when the cost is actually NlogL (where L is the limit of the query) when all the first L
+ * rows have the exact same value for the prefix of the sorted columns. Even in that case, L should be quite smaller
+ * than N, so this implementation is algorithmically better than the normal solution.
+ */
+public abstract class LinearSelectionOrderByOperator extends BaseOperator<SelectionResultsBlock> {
+  protected final IndexSegment _indexSegment;
+
+  protected final boolean _nullHandlingEnabled;
+  // Deduped order-by expressions followed by output expressions from SelectionOperatorUtils.extractExpressions()
+  protected final List<ExpressionContext> _expressions;
+  protected final List<ExpressionContext> _alreadySorted;
+  protected final List<ExpressionContext> _toSort;
+
+  protected final TransformOperator _transformOperator;
+  protected final List<OrderByExpressionContext> _orderByExpressions;
+  protected final TransformResultMetadata[] _expressionsMetadata;
+  protected final int _numRowsToKeep;
+  private final Supplier<ListBuilder> _listBuilderSupplier;
+  protected boolean _used = false;
+  /**
+   * The comparator used to build the resulting {@link SelectionResultsBlock}, which sorts rows in reverse order to the
+   * one specified in the query.
+   */
+  protected Comparator<Object[]> _comparator;
+
+  /**
+   *
+   * @param expressions order by expressions must be at the head of the list.
+   * @param sortedExpr How many expressions at the head of the expression list are going to be considered sorted by
+   * {@link #fetch(Supplier<ListBuilder>)}
+   */
+  public LinearSelectionOrderByOperator(IndexSegment indexSegment, QueryContext queryContext,
+      List<ExpressionContext> expressions, TransformOperator transformOperator,
+      int sortedExpr) {
+    _indexSegment = indexSegment;
+    _nullHandlingEnabled = queryContext.isNullHandlingEnabled();
+    _expressions = expressions;
+    _transformOperator = transformOperator;
+
+    _orderByExpressions = queryContext.getOrderByExpressions();
+    assert _orderByExpressions != null;
+    int numOrderByExpressions = _orderByExpressions.size();
+
+    _alreadySorted = expressions.subList(0, sortedExpr);
+    _toSort = expressions.subList(sortedExpr, numOrderByExpressions);
+
+    _expressionsMetadata = new TransformResultMetadata[_expressions.size()];
+    for (int i = 0; i < _expressionsMetadata.length; i++) {
+      ExpressionContext expression = _expressions.get(i);
+      _expressionsMetadata[i] = _transformOperator.getResultMetadata(expression);
+    }
+
+    _numRowsToKeep = queryContext.getOffset() + queryContext.getLimit();
+
+    if (_toSort.isEmpty()) {
+      int expectedSize = Math.min(SelectionOperatorUtils.MAX_ROW_HOLDER_INITIAL_CAPACITY, _numRowsToKeep);
+      _listBuilderSupplier = () -> new TotallySortedListBuilder(expectedSize);
+    } else {
+      int maxSize = Math.min(SelectionOperatorUtils.MAX_ROW_HOLDER_INITIAL_CAPACITY, _numRowsToKeep * 2);
+
+      Comparator<Object[]> sortedComparator = OrderByComparatorFactory.getComparator(_orderByExpressions,
+          _expressionsMetadata, false, _nullHandlingEnabled, 0, sortedExpr);
+      Comparator<Object[]> unsortedComparator = OrderByComparatorFactory.getComparator(_orderByExpressions,
+          _expressionsMetadata, false, _nullHandlingEnabled, sortedExpr, numOrderByExpressions);
+      _listBuilderSupplier = () -> new PartiallySortedListBuilder(maxSize, sortedComparator, unsortedComparator);
+    }
+
+    _comparator =
+        OrderByComparatorFactory.getComparator(_orderByExpressions, _expressionsMetadata, true, _nullHandlingEnabled);
+  }
+
+  @Override
+  public IndexSegment getIndexSegment() {
+    return _indexSegment;
+  }
+
+  @Override
+  public ExecutionStatistics getExecutionStatistics() {
+    long numEntriesScannedInFilter = _transformOperator.getExecutionStatistics().getNumEntriesScannedInFilter();
+    int numTotalDocs = _indexSegment.getSegmentMetadata().getTotalDocs();
+    return new ExecutionStatistics(getNumDocsScanned(), numEntriesScannedInFilter, getNumEntriesScannedPostFilter(),
+        numTotalDocs);
+  }
+
+  protected IntFunction<Object[]> fetchBlock(TransformBlock transformBlock, BlockValSet[] blockValSets) {
+    int numExpressions = _expressions.size();
+
+    for (int i = 0; i < numExpressions; i++) {
+      ExpressionContext expression = _expressions.get(i);
+      blockValSets[i] = transformBlock.getBlockValueSet(expression);
+    }
+    RowBasedBlockValueFetcher blockValueFetcher = new RowBasedBlockValueFetcher(blockValSets);
+
+    if (!_nullHandlingEnabled) {
+      return blockValueFetcher::getRow;
+    }
+    RoaringBitmap[] nullBitmaps = new RoaringBitmap[numExpressions];
+    for (int i = 0; i < numExpressions; i++) {
+      nullBitmaps[i] = blockValSets[i].getNullBitmap();
+    }
+    return (docId) -> {
+      Object[] row = blockValueFetcher.getRow(docId);
+      for (int colId = 0; colId < nullBitmaps.length; colId++) {
+        if (nullBitmaps[colId] != null && nullBitmaps[colId].contains(docId)) {
+          row[colId] = null;
+        }
+      }
+      return row;
+    };
+  }
+
+  protected abstract long getNumEntriesScannedPostFilter();
+
+  protected abstract int getNumDocsScanned();
+
+  /**
+   * Returns a list of rows sorted that:
+   * <ul>
+   *   <li>At least contains all the rows that fulfill the predicate</li>
+   *   <li>Rows are sorted in a way that is compatible with the given list builder supplier</li>
+   * </ul>
+   *
+   * That means that the result may contain more rows than required.
+   *
+   * @param listBuilderSupplier a {@link ListBuilder} supplier that should be used to create the result. Each time is
+   *                            called a new {@link ListBuilder} will be returned. All returned instances use the same
+   *                            comparator logic.
+   */
+  protected abstract List<Object[]> fetch(Supplier<ListBuilder> listBuilderSupplier);
+
+  @Override
+  public List<Operator> getChildOperators() {
+    return Collections.singletonList(_transformOperator);
+  }
+
+  protected abstract String getExplainName();
+
+  @Override
+  public String toExplainString() {
+    StringBuilder sb = new StringBuilder(getExplainName());
+
+    sb.append("(sortedList: ");
+    concatList(sb, _alreadySorted);
+
+    sb.append(", unsortedList: ");
+    concatList(sb, _toSort);
+
+    sb.append(", rest: ");
+    concatList(sb, _expressions.subList(_alreadySorted.size() + _toSort.size(), _expressions.size()));
+
+    sb.append(')');
+    return sb.toString();
+  }
+
+  private void concatList(StringBuilder sb, List<?> list) {
+    sb.append('(');
+    Iterator<?> it = list.iterator();
+    if (it.hasNext()) {
+      sb.append(it.next());
+      while (it.hasNext()) {
+        sb.append(", ").append(it.next());
+      }
+    }
+    sb.append(')');
+  }
+
+  @Override
+  protected SelectionResultsBlock getNextBlock() {
+    Preconditions.checkState(!_used, "nextBlock was called more than once");
+    _used = true;
+    List<Object[]> list = fetch(_listBuilderSupplier);
+
+    DataSchema dataSchema = createDataSchema();
+
+    if (list.size() > _numRowsToKeep) {
+      list = new ArrayList<>(list.subList(0, _numRowsToKeep));
+    }
+
+    SelectionResultsBlock resultsBlock = new SelectionResultsBlock(dataSchema, list, _comparator);
+
+    return resultsBlock;
+  }
+
+  protected DataSchema createDataSchema() {
+    int numExpressions = _expressions.size();
+
+    // Create the data schema
+    String[] columnNames = new String[numExpressions];
+    DataSchema.ColumnDataType[] columnDataTypes = new DataSchema.ColumnDataType[numExpressions];
+    for (int i = 0; i < columnNames.length; i++) {
+      columnNames[i] = _expressions.get(i).toString();
+    }
+    for (int i = 0; i < numExpressions; i++) {
+      TransformResultMetadata expressionMetadata = _expressionsMetadata[i];
+      columnDataTypes[i] =
+          DataSchema.ColumnDataType.fromDataType(expressionMetadata.getDataType(), expressionMetadata.isSingleValue());
+    }
+    return new DataSchema(columnNames, columnDataTypes);
+  }
+
+  /**
+   * A private class used to build a partially sorted list by adding partially sorted data.
+   *
+   * Specifically, this class has been designed to receive successive calls to {@link #add(Object[])} follow by a single
+   * call to {@link #build()}.
+   *
+   * Rows must be inserted in ascending order accordingly to the partial order specified by a comparator.
+   * This comparator will define <i>partitions</i> of rows. All the rows in the same partition same are considered equal
+   * by that comparator.
+   *
+   * When calling {@link #add(Object[])} with a row that doesn't belong to the current partition, the previous partition
+   * is <em>closed</em> and a new one is started.
+   *
+   * The method {@link #sortedSize()} returns the number of elements stored in all closed partitions.
+   */
+  protected interface ListBuilder {
+
+    /**
+     * Adds the given row to this object. The new column must be equal or higher than previous inserted elements
+     * according to the partition comparator.
+     *
+     * @param row The row to add. The values of the already sorted columns must be equal or higher than the last added
+     *           row, if any.
+     * @return true if and only if the previous partition was closed.
+     */
+    boolean add(Object[] row);
+
+    /**
+     * Builds the sorted list. The current partition will be <em>closed</em>.
+     *
+     * Once this method is called, the builder should not be used. There is no guaranteed on whether
+     * {@link #sortedSize()} is updated or not.
+     */
+    List<Object[]> build();
+
+    /**
+     * How many elements are actually sorted. This number is lower or equal to the number of elements that has been
+     * added.
+     */
+    int sortedSize();
+  }
+
+  /**
+   * This is the faster {@link ListBuilder} but also the most restrictive one. It can only be used when data is inserted
+   * in total order and therefore each element belong to its own partition.
+   *
+   * This builder cannot be used to implement order-by queries where there is at least one expression
+   * that is not sorted. In such case {@link PartiallySortedListBuilder} should be used.
+   *
+   * This implementation is just a wrapper over an ArrayList and therefore the average costs of its methods is constant.
+   */
+  protected static class TotallySortedListBuilder implements ListBuilder {
+    private final ArrayList<Object[]> _list;
+
+    public TotallySortedListBuilder(int expectedSize) {
+      _list = new ArrayList<>(expectedSize);
+    }
+
+    @Override
+    public boolean add(Object[] row) {
+      _list.add(row);
+      return true;
+    }
+
+    @Override
+    public List<Object[]> build() {
+      return _list;
+    }
+
+    @Override
+    public int sortedSize() {
+      return _list.size();
+    }
+  }
+
+  /**
+   * This {@link ListBuilder} is size bound and requires two comparators: The first defines the partitions and the
+   * second defines an order inside each partition.
+   *
+   * This class does never store more than the requested number of elements. In case more elements are inserted:
+   * <ul>
+   *   <li>If the new element belongs to a higher partition, it is discarded.</li>
+   *   <li>If the new element belongs to the last included partition, the last partition is treated as a priority queue
+   *   sorted by the in-partition comparator. If the new element is lower than some of the already inserted elements,
+   *   the new replace the older.</li>
+   * </ul>
+   *
+   * This class can be used to implement order-by queries that include one or more not sorted expressions.
+   * In cases where all expressions are sorted, {@link TotallySortedListBuilder} should be used because its performance
+   * is better.
+   *
+   * As usual, elements are sorted by partition and there is no order guarantee inside each partition. The second
+   * comparator is only used to keep the lower elements in the last partition.
+   */
+  private static class PartiallySortedListBuilder implements ListBuilder {
+    /**
+     * A list with all the elements that have been already sorted.
+     */
+    private final ArrayList<Object[]> _sorted;
+    /**
+     * This attribute is used to store the last partition when the builder already contains {@link #_maxSize} elements.
+     */
+    private PriorityQueue<Object[]> _lastPartitionQueue = null;
+    /**
+     * The comparator that defines the partitions and the one that impose in which order add has to be called.
+     */
+    private final Comparator<Object[]> _partitionComparator;
+    /**
+     * The comparator that sorts different rows on each partition.
+     */
+    private final Comparator<Object[]> _unsortedComparator;
+    @Nullable
+    private Object[] _lastPartitionRow;
+    private final int _maxSize;
+    private int _alreadySorted;
+
+    public PartiallySortedListBuilder(int maxSize, Comparator<Object[]> partitionComparator,
+        Comparator<Object[]> unsortedComparator) {
+      Preconditions.checkArgument(maxSize > 0, "Max size must be greater than 0");
+      _maxSize = maxSize;
+      _sorted = new ArrayList<>(maxSize);
+      _partitionComparator = partitionComparator;
+      _unsortedComparator = unsortedComparator;
+    }
+
+    @Override
+    public boolean add(Object[] row) {
+      if (_lastPartitionRow == null) {
+        _lastPartitionRow = row;
+        _sorted.add(row);
+        return false;
+      }
+      int cmp = _partitionComparator.compare(row, _lastPartitionRow);
+      if (cmp < 0) {
+        throw new IllegalArgumentException(
+            "Row with docId " + _sorted.size() + " is not sorted compared to the previous one");
+      }
+
+      boolean newPartition = cmp > 0;
+      if (_sorted.size() < _maxSize) { // we don't have _maxSize elements yet
+        if (newPartition) {
+          _lastPartitionRow = row;
+          _alreadySorted = _sorted.size();
+        }
+        // just add the new row to the result list
+        _sorted.add(row);
+        return newPartition;
+      }
+      // at least _maxSize have been added
+      if (newPartition) { // and the new element belongs to a new partition, so we can just ignore it
+        return true;
+      }
+      // new element doesn't belong to a new partition, so we may need to add it
+      if (_lastPartitionQueue == null) { // we have exactly _maxSize elements, and the new belongs to the last partition
+        // we need to prepare the priority queue
+        buildPriorityQueue();
+      }
+      // add the new element if it is lower than the greatest element stored in the partition

Review Comment:
   The logic of adding row to the priority queue is missing



##########
pinot-core/src/main/java/org/apache/pinot/core/operator/query/LinearSelectionOrderByOperator.java:
##########
@@ -0,0 +1,452 @@
+/**
+ * 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.pinot.core.operator.query;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+import java.util.PriorityQueue;
+import java.util.function.IntFunction;
+import java.util.function.Supplier;
+import javax.annotation.Nullable;
+import org.apache.pinot.common.request.context.ExpressionContext;
+import org.apache.pinot.common.request.context.OrderByExpressionContext;
+import org.apache.pinot.common.utils.DataSchema;
+import org.apache.pinot.core.common.BlockValSet;
+import org.apache.pinot.core.common.Operator;
+import org.apache.pinot.core.common.RowBasedBlockValueFetcher;
+import org.apache.pinot.core.operator.BaseOperator;
+import org.apache.pinot.core.operator.ExecutionStatistics;
+import org.apache.pinot.core.operator.blocks.TransformBlock;
+import org.apache.pinot.core.operator.blocks.results.SelectionResultsBlock;
+import org.apache.pinot.core.operator.transform.TransformOperator;
+import org.apache.pinot.core.operator.transform.TransformResultMetadata;
+import org.apache.pinot.core.query.request.context.QueryContext;
+import org.apache.pinot.core.query.selection.SelectionOperatorUtils;
+import org.apache.pinot.core.query.utils.OrderByComparatorFactory;
+import org.apache.pinot.segment.spi.IndexSegment;
+import org.roaringbitmap.RoaringBitmap;
+
+
+/**
+ * A selection Operator used when the first expressions in the order by are identifier expressions of columns that are
+ * already sorted (either ascendingly or descendingly), even if the tail of order by expressions are not sorted.
+ *
+ * ie: SELECT ... FROM Table WHERE predicates ORDER BY sorted_column DESC LIMIT 10 OFFSET 5
+ * or: SELECT ... FROM Table WHERE predicates ORDER BY sorted_column, not_sorted LIMIT 10 OFFSET 5
+ * but not SELECT ... FROM Table WHERE predicates ORDER BY not_sorted, sorted_column LIMIT 10 OFFSET 5
+ *
+ * Operators that derives from this class are going to have an almost linear cost instead of the usual NlogN when actual
+ * sorting must be done, where N is the number of rows in the segment.
+ * There is a degraded scenario when the cost is actually NlogL (where L is the limit of the query) when all the first L
+ * rows have the exact same value for the prefix of the sorted columns. Even in that case, L should be quite smaller
+ * than N, so this implementation is algorithmically better than the normal solution.
+ */
+public abstract class LinearSelectionOrderByOperator extends BaseOperator<SelectionResultsBlock> {
+  protected final IndexSegment _indexSegment;
+
+  protected final boolean _nullHandlingEnabled;
+  // Deduped order-by expressions followed by output expressions from SelectionOperatorUtils.extractExpressions()
+  protected final List<ExpressionContext> _expressions;
+  protected final List<ExpressionContext> _alreadySorted;
+  protected final List<ExpressionContext> _toSort;
+
+  protected final TransformOperator _transformOperator;
+  protected final List<OrderByExpressionContext> _orderByExpressions;
+  protected final TransformResultMetadata[] _expressionsMetadata;
+  protected final int _numRowsToKeep;
+  private final Supplier<ListBuilder> _listBuilderSupplier;
+  protected boolean _used = false;
+  /**
+   * The comparator used to build the resulting {@link SelectionResultsBlock}, which sorts rows in reverse order to the
+   * one specified in the query.
+   */
+  protected Comparator<Object[]> _comparator;
+
+  /**
+   *
+   * @param expressions order by expressions must be at the head of the list.
+   * @param sortedExpr How many expressions at the head of the expression list are going to be considered sorted by
+   * {@link #fetch(Supplier<ListBuilder>)}
+   */
+  public LinearSelectionOrderByOperator(IndexSegment indexSegment, QueryContext queryContext,
+      List<ExpressionContext> expressions, TransformOperator transformOperator,
+      int sortedExpr) {
+    _indexSegment = indexSegment;
+    _nullHandlingEnabled = queryContext.isNullHandlingEnabled();
+    _expressions = expressions;
+    _transformOperator = transformOperator;
+
+    _orderByExpressions = queryContext.getOrderByExpressions();
+    assert _orderByExpressions != null;
+    int numOrderByExpressions = _orderByExpressions.size();
+
+    _alreadySorted = expressions.subList(0, sortedExpr);
+    _toSort = expressions.subList(sortedExpr, numOrderByExpressions);
+
+    _expressionsMetadata = new TransformResultMetadata[_expressions.size()];
+    for (int i = 0; i < _expressionsMetadata.length; i++) {
+      ExpressionContext expression = _expressions.get(i);
+      _expressionsMetadata[i] = _transformOperator.getResultMetadata(expression);
+    }
+
+    _numRowsToKeep = queryContext.getOffset() + queryContext.getLimit();
+
+    if (_toSort.isEmpty()) {
+      int expectedSize = Math.min(SelectionOperatorUtils.MAX_ROW_HOLDER_INITIAL_CAPACITY, _numRowsToKeep);
+      _listBuilderSupplier = () -> new TotallySortedListBuilder(expectedSize);
+    } else {
+      int maxSize = Math.min(SelectionOperatorUtils.MAX_ROW_HOLDER_INITIAL_CAPACITY, _numRowsToKeep * 2);

Review Comment:
   Why do we need this `*2`?



##########
pinot-core/src/main/java/org/apache/pinot/core/operator/query/LinearSelectionOrderByOperator.java:
##########
@@ -0,0 +1,452 @@
+/**
+ * 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.pinot.core.operator.query;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+import java.util.PriorityQueue;
+import java.util.function.IntFunction;
+import java.util.function.Supplier;
+import javax.annotation.Nullable;
+import org.apache.pinot.common.request.context.ExpressionContext;
+import org.apache.pinot.common.request.context.OrderByExpressionContext;
+import org.apache.pinot.common.utils.DataSchema;
+import org.apache.pinot.core.common.BlockValSet;
+import org.apache.pinot.core.common.Operator;
+import org.apache.pinot.core.common.RowBasedBlockValueFetcher;
+import org.apache.pinot.core.operator.BaseOperator;
+import org.apache.pinot.core.operator.ExecutionStatistics;
+import org.apache.pinot.core.operator.blocks.TransformBlock;
+import org.apache.pinot.core.operator.blocks.results.SelectionResultsBlock;
+import org.apache.pinot.core.operator.transform.TransformOperator;
+import org.apache.pinot.core.operator.transform.TransformResultMetadata;
+import org.apache.pinot.core.query.request.context.QueryContext;
+import org.apache.pinot.core.query.selection.SelectionOperatorUtils;
+import org.apache.pinot.core.query.utils.OrderByComparatorFactory;
+import org.apache.pinot.segment.spi.IndexSegment;
+import org.roaringbitmap.RoaringBitmap;
+
+
+/**
+ * A selection Operator used when the first expressions in the order by are identifier expressions of columns that are
+ * already sorted (either ascendingly or descendingly), even if the tail of order by expressions are not sorted.
+ *
+ * ie: SELECT ... FROM Table WHERE predicates ORDER BY sorted_column DESC LIMIT 10 OFFSET 5
+ * or: SELECT ... FROM Table WHERE predicates ORDER BY sorted_column, not_sorted LIMIT 10 OFFSET 5
+ * but not SELECT ... FROM Table WHERE predicates ORDER BY not_sorted, sorted_column LIMIT 10 OFFSET 5
+ *
+ * Operators that derives from this class are going to have an almost linear cost instead of the usual NlogN when actual
+ * sorting must be done, where N is the number of rows in the segment.
+ * There is a degraded scenario when the cost is actually NlogL (where L is the limit of the query) when all the first L
+ * rows have the exact same value for the prefix of the sorted columns. Even in that case, L should be quite smaller
+ * than N, so this implementation is algorithmically better than the normal solution.
+ */
+public abstract class LinearSelectionOrderByOperator extends BaseOperator<SelectionResultsBlock> {
+  protected final IndexSegment _indexSegment;
+
+  protected final boolean _nullHandlingEnabled;
+  // Deduped order-by expressions followed by output expressions from SelectionOperatorUtils.extractExpressions()
+  protected final List<ExpressionContext> _expressions;
+  protected final List<ExpressionContext> _alreadySorted;
+  protected final List<ExpressionContext> _toSort;
+
+  protected final TransformOperator _transformOperator;
+  protected final List<OrderByExpressionContext> _orderByExpressions;
+  protected final TransformResultMetadata[] _expressionsMetadata;
+  protected final int _numRowsToKeep;
+  private final Supplier<ListBuilder> _listBuilderSupplier;
+  protected boolean _used = false;
+  /**
+   * The comparator used to build the resulting {@link SelectionResultsBlock}, which sorts rows in reverse order to the
+   * one specified in the query.
+   */
+  protected Comparator<Object[]> _comparator;
+
+  /**
+   *
+   * @param expressions order by expressions must be at the head of the list.
+   * @param sortedExpr How many expressions at the head of the expression list are going to be considered sorted by
+   * {@link #fetch(Supplier<ListBuilder>)}
+   */
+  public LinearSelectionOrderByOperator(IndexSegment indexSegment, QueryContext queryContext,
+      List<ExpressionContext> expressions, TransformOperator transformOperator,
+      int sortedExpr) {
+    _indexSegment = indexSegment;
+    _nullHandlingEnabled = queryContext.isNullHandlingEnabled();
+    _expressions = expressions;
+    _transformOperator = transformOperator;
+
+    _orderByExpressions = queryContext.getOrderByExpressions();
+    assert _orderByExpressions != null;
+    int numOrderByExpressions = _orderByExpressions.size();
+
+    _alreadySorted = expressions.subList(0, sortedExpr);
+    _toSort = expressions.subList(sortedExpr, numOrderByExpressions);
+
+    _expressionsMetadata = new TransformResultMetadata[_expressions.size()];
+    for (int i = 0; i < _expressionsMetadata.length; i++) {
+      ExpressionContext expression = _expressions.get(i);
+      _expressionsMetadata[i] = _transformOperator.getResultMetadata(expression);
+    }
+
+    _numRowsToKeep = queryContext.getOffset() + queryContext.getLimit();
+
+    if (_toSort.isEmpty()) {
+      int expectedSize = Math.min(SelectionOperatorUtils.MAX_ROW_HOLDER_INITIAL_CAPACITY, _numRowsToKeep);
+      _listBuilderSupplier = () -> new TotallySortedListBuilder(expectedSize);
+    } else {
+      int maxSize = Math.min(SelectionOperatorUtils.MAX_ROW_HOLDER_INITIAL_CAPACITY, _numRowsToKeep * 2);
+
+      Comparator<Object[]> sortedComparator = OrderByComparatorFactory.getComparator(_orderByExpressions,
+          _expressionsMetadata, false, _nullHandlingEnabled, 0, sortedExpr);
+      Comparator<Object[]> unsortedComparator = OrderByComparatorFactory.getComparator(_orderByExpressions,
+          _expressionsMetadata, false, _nullHandlingEnabled, sortedExpr, numOrderByExpressions);
+      _listBuilderSupplier = () -> new PartiallySortedListBuilder(maxSize, sortedComparator, unsortedComparator);
+    }
+
+    _comparator =
+        OrderByComparatorFactory.getComparator(_orderByExpressions, _expressionsMetadata, true, _nullHandlingEnabled);
+  }
+
+  @Override
+  public IndexSegment getIndexSegment() {
+    return _indexSegment;
+  }
+
+  @Override
+  public ExecutionStatistics getExecutionStatistics() {
+    long numEntriesScannedInFilter = _transformOperator.getExecutionStatistics().getNumEntriesScannedInFilter();
+    int numTotalDocs = _indexSegment.getSegmentMetadata().getTotalDocs();
+    return new ExecutionStatistics(getNumDocsScanned(), numEntriesScannedInFilter, getNumEntriesScannedPostFilter(),
+        numTotalDocs);
+  }
+
+  protected IntFunction<Object[]> fetchBlock(TransformBlock transformBlock, BlockValSet[] blockValSets) {
+    int numExpressions = _expressions.size();
+
+    for (int i = 0; i < numExpressions; i++) {
+      ExpressionContext expression = _expressions.get(i);
+      blockValSets[i] = transformBlock.getBlockValueSet(expression);
+    }
+    RowBasedBlockValueFetcher blockValueFetcher = new RowBasedBlockValueFetcher(blockValSets);
+
+    if (!_nullHandlingEnabled) {
+      return blockValueFetcher::getRow;
+    }
+    RoaringBitmap[] nullBitmaps = new RoaringBitmap[numExpressions];
+    for (int i = 0; i < numExpressions; i++) {
+      nullBitmaps[i] = blockValSets[i].getNullBitmap();
+    }
+    return (docId) -> {
+      Object[] row = blockValueFetcher.getRow(docId);
+      for (int colId = 0; colId < nullBitmaps.length; colId++) {
+        if (nullBitmaps[colId] != null && nullBitmaps[colId].contains(docId)) {
+          row[colId] = null;
+        }
+      }
+      return row;
+    };
+  }
+
+  protected abstract long getNumEntriesScannedPostFilter();
+
+  protected abstract int getNumDocsScanned();
+
+  /**
+   * Returns a list of rows sorted that:
+   * <ul>
+   *   <li>At least contains all the rows that fulfill the predicate</li>
+   *   <li>Rows are sorted in a way that is compatible with the given list builder supplier</li>
+   * </ul>
+   *
+   * That means that the result may contain more rows than required.
+   *
+   * @param listBuilderSupplier a {@link ListBuilder} supplier that should be used to create the result. Each time is
+   *                            called a new {@link ListBuilder} will be returned. All returned instances use the same
+   *                            comparator logic.
+   */
+  protected abstract List<Object[]> fetch(Supplier<ListBuilder> listBuilderSupplier);
+
+  @Override
+  public List<Operator> getChildOperators() {
+    return Collections.singletonList(_transformOperator);
+  }
+
+  protected abstract String getExplainName();
+
+  @Override
+  public String toExplainString() {
+    StringBuilder sb = new StringBuilder(getExplainName());
+
+    sb.append("(sortedList: ");
+    concatList(sb, _alreadySorted);
+
+    sb.append(", unsortedList: ");
+    concatList(sb, _toSort);
+
+    sb.append(", rest: ");
+    concatList(sb, _expressions.subList(_alreadySorted.size() + _toSort.size(), _expressions.size()));
+
+    sb.append(')');
+    return sb.toString();
+  }
+
+  private void concatList(StringBuilder sb, List<?> list) {
+    sb.append('(');
+    Iterator<?> it = list.iterator();
+    if (it.hasNext()) {
+      sb.append(it.next());
+      while (it.hasNext()) {
+        sb.append(", ").append(it.next());
+      }
+    }
+    sb.append(')');
+  }
+
+  @Override
+  protected SelectionResultsBlock getNextBlock() {
+    Preconditions.checkState(!_used, "nextBlock was called more than once");
+    _used = true;
+    List<Object[]> list = fetch(_listBuilderSupplier);
+
+    DataSchema dataSchema = createDataSchema();
+
+    if (list.size() > _numRowsToKeep) {
+      list = new ArrayList<>(list.subList(0, _numRowsToKeep));
+    }
+
+    SelectionResultsBlock resultsBlock = new SelectionResultsBlock(dataSchema, list, _comparator);
+
+    return resultsBlock;
+  }
+
+  protected DataSchema createDataSchema() {
+    int numExpressions = _expressions.size();
+
+    // Create the data schema
+    String[] columnNames = new String[numExpressions];
+    DataSchema.ColumnDataType[] columnDataTypes = new DataSchema.ColumnDataType[numExpressions];
+    for (int i = 0; i < columnNames.length; i++) {
+      columnNames[i] = _expressions.get(i).toString();
+    }
+    for (int i = 0; i < numExpressions; i++) {
+      TransformResultMetadata expressionMetadata = _expressionsMetadata[i];
+      columnDataTypes[i] =
+          DataSchema.ColumnDataType.fromDataType(expressionMetadata.getDataType(), expressionMetadata.isSingleValue());
+    }
+    return new DataSchema(columnNames, columnDataTypes);
+  }
+
+  /**
+   * A private class used to build a partially sorted list by adding partially sorted data.
+   *
+   * Specifically, this class has been designed to receive successive calls to {@link #add(Object[])} follow by a single
+   * call to {@link #build()}.
+   *
+   * Rows must be inserted in ascending order accordingly to the partial order specified by a comparator.
+   * This comparator will define <i>partitions</i> of rows. All the rows in the same partition same are considered equal
+   * by that comparator.
+   *
+   * When calling {@link #add(Object[])} with a row that doesn't belong to the current partition, the previous partition
+   * is <em>closed</em> and a new one is started.
+   *
+   * The method {@link #sortedSize()} returns the number of elements stored in all closed partitions.
+   */
+  protected interface ListBuilder {
+
+    /**
+     * Adds the given row to this object. The new column must be equal or higher than previous inserted elements
+     * according to the partition comparator.
+     *
+     * @param row The row to add. The values of the already sorted columns must be equal or higher than the last added
+     *           row, if any.
+     * @return true if and only if the previous partition was closed.
+     */
+    boolean add(Object[] row);
+
+    /**
+     * Builds the sorted list. The current partition will be <em>closed</em>.
+     *
+     * Once this method is called, the builder should not be used. There is no guaranteed on whether
+     * {@link #sortedSize()} is updated or not.
+     */
+    List<Object[]> build();
+
+    /**
+     * How many elements are actually sorted. This number is lower or equal to the number of elements that has been
+     * added.
+     */
+    int sortedSize();
+  }
+
+  /**
+   * This is the faster {@link ListBuilder} but also the most restrictive one. It can only be used when data is inserted
+   * in total order and therefore each element belong to its own partition.
+   *
+   * This builder cannot be used to implement order-by queries where there is at least one expression
+   * that is not sorted. In such case {@link PartiallySortedListBuilder} should be used.
+   *
+   * This implementation is just a wrapper over an ArrayList and therefore the average costs of its methods is constant.
+   */
+  protected static class TotallySortedListBuilder implements ListBuilder {
+    private final ArrayList<Object[]> _list;
+
+    public TotallySortedListBuilder(int expectedSize) {
+      _list = new ArrayList<>(expectedSize);
+    }
+
+    @Override
+    public boolean add(Object[] row) {
+      _list.add(row);
+      return true;
+    }
+
+    @Override
+    public List<Object[]> build() {
+      return _list;
+    }
+
+    @Override
+    public int sortedSize() {
+      return _list.size();
+    }
+  }
+
+  /**
+   * This {@link ListBuilder} is size bound and requires two comparators: The first defines the partitions and the
+   * second defines an order inside each partition.
+   *
+   * This class does never store more than the requested number of elements. In case more elements are inserted:
+   * <ul>
+   *   <li>If the new element belongs to a higher partition, it is discarded.</li>
+   *   <li>If the new element belongs to the last included partition, the last partition is treated as a priority queue
+   *   sorted by the in-partition comparator. If the new element is lower than some of the already inserted elements,
+   *   the new replace the older.</li>
+   * </ul>
+   *
+   * This class can be used to implement order-by queries that include one or more not sorted expressions.
+   * In cases where all expressions are sorted, {@link TotallySortedListBuilder} should be used because its performance
+   * is better.
+   *
+   * As usual, elements are sorted by partition and there is no order guarantee inside each partition. The second
+   * comparator is only used to keep the lower elements in the last partition.
+   */
+  private static class PartiallySortedListBuilder implements ListBuilder {
+    /**
+     * A list with all the elements that have been already sorted.
+     */
+    private final ArrayList<Object[]> _sorted;
+    /**
+     * This attribute is used to store the last partition when the builder already contains {@link #_maxSize} elements.
+     */
+    private PriorityQueue<Object[]> _lastPartitionQueue = null;
+    /**
+     * The comparator that defines the partitions and the one that impose in which order add has to be called.
+     */
+    private final Comparator<Object[]> _partitionComparator;
+    /**
+     * The comparator that sorts different rows on each partition.
+     */
+    private final Comparator<Object[]> _unsortedComparator;
+    @Nullable
+    private Object[] _lastPartitionRow;
+    private final int _maxSize;
+    private int _alreadySorted;
+
+    public PartiallySortedListBuilder(int maxSize, Comparator<Object[]> partitionComparator,
+        Comparator<Object[]> unsortedComparator) {
+      Preconditions.checkArgument(maxSize > 0, "Max size must be greater than 0");
+      _maxSize = maxSize;
+      _sorted = new ArrayList<>(maxSize);
+      _partitionComparator = partitionComparator;
+      _unsortedComparator = unsortedComparator;
+    }
+
+    @Override
+    public boolean add(Object[] row) {
+      if (_lastPartitionRow == null) {
+        _lastPartitionRow = row;
+        _sorted.add(row);
+        return false;
+      }
+      int cmp = _partitionComparator.compare(row, _lastPartitionRow);
+      if (cmp < 0) {
+        throw new IllegalArgumentException(
+            "Row with docId " + _sorted.size() + " is not sorted compared to the previous one");
+      }
+
+      boolean newPartition = cmp > 0;
+      if (_sorted.size() < _maxSize) { // we don't have _maxSize elements yet
+        if (newPartition) {
+          _lastPartitionRow = row;
+          _alreadySorted = _sorted.size();
+        }
+        // just add the new row to the result list
+        _sorted.add(row);
+        return newPartition;
+      }
+      // at least _maxSize have been added
+      if (newPartition) { // and the new element belongs to a new partition, so we can just ignore it
+        return true;

Review Comment:
   `_alreadySorted` is not updated, which can cause the while check for `sortedSize()` never able to reach



##########
pinot-core/src/main/java/org/apache/pinot/core/operator/query/LinearSelectionOrderByOperator.java:
##########
@@ -0,0 +1,452 @@
+/**
+ * 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.pinot.core.operator.query;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+import java.util.PriorityQueue;
+import java.util.function.IntFunction;
+import java.util.function.Supplier;
+import javax.annotation.Nullable;
+import org.apache.pinot.common.request.context.ExpressionContext;
+import org.apache.pinot.common.request.context.OrderByExpressionContext;
+import org.apache.pinot.common.utils.DataSchema;
+import org.apache.pinot.core.common.BlockValSet;
+import org.apache.pinot.core.common.Operator;
+import org.apache.pinot.core.common.RowBasedBlockValueFetcher;
+import org.apache.pinot.core.operator.BaseOperator;
+import org.apache.pinot.core.operator.ExecutionStatistics;
+import org.apache.pinot.core.operator.blocks.TransformBlock;
+import org.apache.pinot.core.operator.blocks.results.SelectionResultsBlock;
+import org.apache.pinot.core.operator.transform.TransformOperator;
+import org.apache.pinot.core.operator.transform.TransformResultMetadata;
+import org.apache.pinot.core.query.request.context.QueryContext;
+import org.apache.pinot.core.query.selection.SelectionOperatorUtils;
+import org.apache.pinot.core.query.utils.OrderByComparatorFactory;
+import org.apache.pinot.segment.spi.IndexSegment;
+import org.roaringbitmap.RoaringBitmap;
+
+
+/**
+ * A selection Operator used when the first expressions in the order by are identifier expressions of columns that are
+ * already sorted (either ascendingly or descendingly), even if the tail of order by expressions are not sorted.
+ *
+ * ie: SELECT ... FROM Table WHERE predicates ORDER BY sorted_column DESC LIMIT 10 OFFSET 5
+ * or: SELECT ... FROM Table WHERE predicates ORDER BY sorted_column, not_sorted LIMIT 10 OFFSET 5
+ * but not SELECT ... FROM Table WHERE predicates ORDER BY not_sorted, sorted_column LIMIT 10 OFFSET 5
+ *
+ * Operators that derives from this class are going to have an almost linear cost instead of the usual NlogN when actual
+ * sorting must be done, where N is the number of rows in the segment.
+ * There is a degraded scenario when the cost is actually NlogL (where L is the limit of the query) when all the first L
+ * rows have the exact same value for the prefix of the sorted columns. Even in that case, L should be quite smaller
+ * than N, so this implementation is algorithmically better than the normal solution.
+ */
+public abstract class LinearSelectionOrderByOperator extends BaseOperator<SelectionResultsBlock> {
+  protected final IndexSegment _indexSegment;
+
+  protected final boolean _nullHandlingEnabled;
+  // Deduped order-by expressions followed by output expressions from SelectionOperatorUtils.extractExpressions()
+  protected final List<ExpressionContext> _expressions;
+  protected final List<ExpressionContext> _alreadySorted;
+  protected final List<ExpressionContext> _toSort;
+
+  protected final TransformOperator _transformOperator;
+  protected final List<OrderByExpressionContext> _orderByExpressions;
+  protected final TransformResultMetadata[] _expressionsMetadata;
+  protected final int _numRowsToKeep;
+  private final Supplier<ListBuilder> _listBuilderSupplier;
+  protected boolean _used = false;
+  /**
+   * The comparator used to build the resulting {@link SelectionResultsBlock}, which sorts rows in reverse order to the
+   * one specified in the query.
+   */
+  protected Comparator<Object[]> _comparator;
+
+  /**
+   *
+   * @param expressions order by expressions must be at the head of the list.
+   * @param sortedExpr How many expressions at the head of the expression list are going to be considered sorted by
+   * {@link #fetch(Supplier<ListBuilder>)}
+   */
+  public LinearSelectionOrderByOperator(IndexSegment indexSegment, QueryContext queryContext,
+      List<ExpressionContext> expressions, TransformOperator transformOperator,
+      int sortedExpr) {
+    _indexSegment = indexSegment;
+    _nullHandlingEnabled = queryContext.isNullHandlingEnabled();
+    _expressions = expressions;
+    _transformOperator = transformOperator;
+
+    _orderByExpressions = queryContext.getOrderByExpressions();
+    assert _orderByExpressions != null;
+    int numOrderByExpressions = _orderByExpressions.size();
+
+    _alreadySorted = expressions.subList(0, sortedExpr);
+    _toSort = expressions.subList(sortedExpr, numOrderByExpressions);
+
+    _expressionsMetadata = new TransformResultMetadata[_expressions.size()];
+    for (int i = 0; i < _expressionsMetadata.length; i++) {
+      ExpressionContext expression = _expressions.get(i);
+      _expressionsMetadata[i] = _transformOperator.getResultMetadata(expression);
+    }
+
+    _numRowsToKeep = queryContext.getOffset() + queryContext.getLimit();
+
+    if (_toSort.isEmpty()) {
+      int expectedSize = Math.min(SelectionOperatorUtils.MAX_ROW_HOLDER_INITIAL_CAPACITY, _numRowsToKeep);
+      _listBuilderSupplier = () -> new TotallySortedListBuilder(expectedSize);
+    } else {
+      int maxSize = Math.min(SelectionOperatorUtils.MAX_ROW_HOLDER_INITIAL_CAPACITY, _numRowsToKeep * 2);
+
+      Comparator<Object[]> sortedComparator = OrderByComparatorFactory.getComparator(_orderByExpressions,
+          _expressionsMetadata, false, _nullHandlingEnabled, 0, sortedExpr);
+      Comparator<Object[]> unsortedComparator = OrderByComparatorFactory.getComparator(_orderByExpressions,
+          _expressionsMetadata, false, _nullHandlingEnabled, sortedExpr, numOrderByExpressions);
+      _listBuilderSupplier = () -> new PartiallySortedListBuilder(maxSize, sortedComparator, unsortedComparator);
+    }
+
+    _comparator =
+        OrderByComparatorFactory.getComparator(_orderByExpressions, _expressionsMetadata, true, _nullHandlingEnabled);
+  }
+
+  @Override
+  public IndexSegment getIndexSegment() {
+    return _indexSegment;
+  }
+
+  @Override
+  public ExecutionStatistics getExecutionStatistics() {
+    long numEntriesScannedInFilter = _transformOperator.getExecutionStatistics().getNumEntriesScannedInFilter();
+    int numTotalDocs = _indexSegment.getSegmentMetadata().getTotalDocs();
+    return new ExecutionStatistics(getNumDocsScanned(), numEntriesScannedInFilter, getNumEntriesScannedPostFilter(),
+        numTotalDocs);
+  }
+
+  protected IntFunction<Object[]> fetchBlock(TransformBlock transformBlock, BlockValSet[] blockValSets) {
+    int numExpressions = _expressions.size();
+
+    for (int i = 0; i < numExpressions; i++) {
+      ExpressionContext expression = _expressions.get(i);
+      blockValSets[i] = transformBlock.getBlockValueSet(expression);
+    }
+    RowBasedBlockValueFetcher blockValueFetcher = new RowBasedBlockValueFetcher(blockValSets);
+
+    if (!_nullHandlingEnabled) {
+      return blockValueFetcher::getRow;
+    }
+    RoaringBitmap[] nullBitmaps = new RoaringBitmap[numExpressions];
+    for (int i = 0; i < numExpressions; i++) {
+      nullBitmaps[i] = blockValSets[i].getNullBitmap();
+    }
+    return (docId) -> {
+      Object[] row = blockValueFetcher.getRow(docId);
+      for (int colId = 0; colId < nullBitmaps.length; colId++) {
+        if (nullBitmaps[colId] != null && nullBitmaps[colId].contains(docId)) {
+          row[colId] = null;
+        }
+      }
+      return row;
+    };
+  }
+
+  protected abstract long getNumEntriesScannedPostFilter();
+
+  protected abstract int getNumDocsScanned();
+
+  /**
+   * Returns a list of rows sorted that:
+   * <ul>
+   *   <li>At least contains all the rows that fulfill the predicate</li>
+   *   <li>Rows are sorted in a way that is compatible with the given list builder supplier</li>
+   * </ul>
+   *
+   * That means that the result may contain more rows than required.
+   *
+   * @param listBuilderSupplier a {@link ListBuilder} supplier that should be used to create the result. Each time is
+   *                            called a new {@link ListBuilder} will be returned. All returned instances use the same
+   *                            comparator logic.
+   */
+  protected abstract List<Object[]> fetch(Supplier<ListBuilder> listBuilderSupplier);
+
+  @Override
+  public List<Operator> getChildOperators() {
+    return Collections.singletonList(_transformOperator);
+  }
+
+  protected abstract String getExplainName();
+
+  @Override
+  public String toExplainString() {
+    StringBuilder sb = new StringBuilder(getExplainName());
+
+    sb.append("(sortedList: ");
+    concatList(sb, _alreadySorted);
+
+    sb.append(", unsortedList: ");
+    concatList(sb, _toSort);
+
+    sb.append(", rest: ");
+    concatList(sb, _expressions.subList(_alreadySorted.size() + _toSort.size(), _expressions.size()));
+
+    sb.append(')');
+    return sb.toString();
+  }
+
+  private void concatList(StringBuilder sb, List<?> list) {
+    sb.append('(');
+    Iterator<?> it = list.iterator();
+    if (it.hasNext()) {
+      sb.append(it.next());
+      while (it.hasNext()) {
+        sb.append(", ").append(it.next());
+      }
+    }
+    sb.append(')');
+  }
+
+  @Override
+  protected SelectionResultsBlock getNextBlock() {
+    Preconditions.checkState(!_used, "nextBlock was called more than once");
+    _used = true;
+    List<Object[]> list = fetch(_listBuilderSupplier);
+
+    DataSchema dataSchema = createDataSchema();
+
+    if (list.size() > _numRowsToKeep) {
+      list = new ArrayList<>(list.subList(0, _numRowsToKeep));
+    }
+
+    SelectionResultsBlock resultsBlock = new SelectionResultsBlock(dataSchema, list, _comparator);
+
+    return resultsBlock;
+  }
+
+  protected DataSchema createDataSchema() {
+    int numExpressions = _expressions.size();
+
+    // Create the data schema
+    String[] columnNames = new String[numExpressions];
+    DataSchema.ColumnDataType[] columnDataTypes = new DataSchema.ColumnDataType[numExpressions];
+    for (int i = 0; i < columnNames.length; i++) {
+      columnNames[i] = _expressions.get(i).toString();
+    }
+    for (int i = 0; i < numExpressions; i++) {
+      TransformResultMetadata expressionMetadata = _expressionsMetadata[i];
+      columnDataTypes[i] =
+          DataSchema.ColumnDataType.fromDataType(expressionMetadata.getDataType(), expressionMetadata.isSingleValue());
+    }
+    return new DataSchema(columnNames, columnDataTypes);
+  }
+
+  /**
+   * A private class used to build a partially sorted list by adding partially sorted data.
+   *
+   * Specifically, this class has been designed to receive successive calls to {@link #add(Object[])} follow by a single
+   * call to {@link #build()}.
+   *
+   * Rows must be inserted in ascending order accordingly to the partial order specified by a comparator.
+   * This comparator will define <i>partitions</i> of rows. All the rows in the same partition same are considered equal
+   * by that comparator.
+   *
+   * When calling {@link #add(Object[])} with a row that doesn't belong to the current partition, the previous partition
+   * is <em>closed</em> and a new one is started.
+   *
+   * The method {@link #sortedSize()} returns the number of elements stored in all closed partitions.
+   */
+  protected interface ListBuilder {
+
+    /**
+     * Adds the given row to this object. The new column must be equal or higher than previous inserted elements
+     * according to the partition comparator.
+     *
+     * @param row The row to add. The values of the already sorted columns must be equal or higher than the last added
+     *           row, if any.
+     * @return true if and only if the previous partition was closed.
+     */
+    boolean add(Object[] row);
+
+    /**
+     * Builds the sorted list. The current partition will be <em>closed</em>.
+     *
+     * Once this method is called, the builder should not be used. There is no guaranteed on whether
+     * {@link #sortedSize()} is updated or not.
+     */
+    List<Object[]> build();
+
+    /**
+     * How many elements are actually sorted. This number is lower or equal to the number of elements that has been
+     * added.
+     */
+    int sortedSize();
+  }
+
+  /**
+   * This is the faster {@link ListBuilder} but also the most restrictive one. It can only be used when data is inserted
+   * in total order and therefore each element belong to its own partition.
+   *
+   * This builder cannot be used to implement order-by queries where there is at least one expression
+   * that is not sorted. In such case {@link PartiallySortedListBuilder} should be used.
+   *
+   * This implementation is just a wrapper over an ArrayList and therefore the average costs of its methods is constant.
+   */
+  protected static class TotallySortedListBuilder implements ListBuilder {
+    private final ArrayList<Object[]> _list;
+
+    public TotallySortedListBuilder(int expectedSize) {
+      _list = new ArrayList<>(expectedSize);
+    }
+
+    @Override
+    public boolean add(Object[] row) {
+      _list.add(row);
+      return true;
+    }
+
+    @Override
+    public List<Object[]> build() {
+      return _list;
+    }
+
+    @Override
+    public int sortedSize() {
+      return _list.size();
+    }
+  }
+
+  /**
+   * This {@link ListBuilder} is size bound and requires two comparators: The first defines the partitions and the
+   * second defines an order inside each partition.
+   *
+   * This class does never store more than the requested number of elements. In case more elements are inserted:
+   * <ul>
+   *   <li>If the new element belongs to a higher partition, it is discarded.</li>
+   *   <li>If the new element belongs to the last included partition, the last partition is treated as a priority queue
+   *   sorted by the in-partition comparator. If the new element is lower than some of the already inserted elements,
+   *   the new replace the older.</li>
+   * </ul>
+   *
+   * This class can be used to implement order-by queries that include one or more not sorted expressions.
+   * In cases where all expressions are sorted, {@link TotallySortedListBuilder} should be used because its performance
+   * is better.
+   *
+   * As usual, elements are sorted by partition and there is no order guarantee inside each partition. The second
+   * comparator is only used to keep the lower elements in the last partition.
+   */
+  private static class PartiallySortedListBuilder implements ListBuilder {
+    /**
+     * A list with all the elements that have been already sorted.
+     */
+    private final ArrayList<Object[]> _sorted;
+    /**
+     * This attribute is used to store the last partition when the builder already contains {@link #_maxSize} elements.
+     */
+    private PriorityQueue<Object[]> _lastPartitionQueue = null;
+    /**
+     * The comparator that defines the partitions and the one that impose in which order add has to be called.
+     */
+    private final Comparator<Object[]> _partitionComparator;
+    /**
+     * The comparator that sorts different rows on each partition.
+     */
+    private final Comparator<Object[]> _unsortedComparator;
+    @Nullable
+    private Object[] _lastPartitionRow;
+    private final int _maxSize;
+    private int _alreadySorted;
+
+    public PartiallySortedListBuilder(int maxSize, Comparator<Object[]> partitionComparator,
+        Comparator<Object[]> unsortedComparator) {
+      Preconditions.checkArgument(maxSize > 0, "Max size must be greater than 0");
+      _maxSize = maxSize;
+      _sorted = new ArrayList<>(maxSize);
+      _partitionComparator = partitionComparator;
+      _unsortedComparator = unsortedComparator;
+    }
+
+    @Override
+    public boolean add(Object[] row) {
+      if (_lastPartitionRow == null) {
+        _lastPartitionRow = row;
+        _sorted.add(row);
+        return false;
+      }
+      int cmp = _partitionComparator.compare(row, _lastPartitionRow);
+      if (cmp < 0) {
+        throw new IllegalArgumentException(
+            "Row with docId " + _sorted.size() + " is not sorted compared to the previous one");
+      }
+
+      boolean newPartition = cmp > 0;
+      if (_sorted.size() < _maxSize) { // we don't have _maxSize elements yet
+        if (newPartition) {
+          _lastPartitionRow = row;
+          _alreadySorted = _sorted.size();
+        }
+        // just add the new row to the result list
+        _sorted.add(row);
+        return newPartition;
+      }
+      // at least _maxSize have been added
+      if (newPartition) { // and the new element belongs to a new partition, so we can just ignore it
+        return true;
+      }
+      // new element doesn't belong to a new partition, so we may need to add it
+      if (_lastPartitionQueue == null) { // we have exactly _maxSize elements, and the new belongs to the last partition
+        // we need to prepare the priority queue
+        buildPriorityQueue();
+      }
+      // add the new element if it is lower than the greatest element stored in the partition
+      return false;
+    }
+
+    private void buildPriorityQueue() {
+      int maxPriorityQueueValues = _maxSize - _alreadySorted;
+      _lastPartitionQueue = new PriorityQueue<>(maxPriorityQueueValues, _unsortedComparator.reversed());
+      _lastPartitionQueue.addAll(_sorted.subList(_alreadySorted, _sorted.size()));
+    }
+
+    /**
+     * Sorts the rows and returns the sorted list.
+     *
+     * This object should not be used once this method is called.
+     *
+     * @return the list of all added rows, sorted by {@link #_partitionComparator} and then by
+     * {@link #_unsortedComparator}
+     */
+    @Override
+    public List<Object[]> build() {
+      if (_lastPartitionQueue != null) {
+        assert _lastPartitionQueue.size() == _sorted.size() - _alreadySorted;
+        Iterator<Object[]> lastPartitionIt = _lastPartitionQueue.iterator();
+        for (int i = _alreadySorted; i < _sorted.size(); i++) {
+          _sorted.set(i, lastPartitionIt.next());
+        }
+      }
+      return _sorted;
+    }
+
+    @Override
+    public int sortedSize() {

Review Comment:
   Tracking this on the caller side and use it to decide whether to add more rows can be hard to manage. Instead, this logic can be managed internally



##########
pinot-core/src/main/java/org/apache/pinot/core/operator/query/SelectionPartiallyOrderedByDescOperation.java:
##########
@@ -0,0 +1,126 @@
+/**
+ * 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.pinot.core.operator.query;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.function.IntFunction;
+import java.util.function.Supplier;
+import org.apache.pinot.common.request.context.ExpressionContext;
+import org.apache.pinot.core.common.BlockValSet;
+import org.apache.pinot.core.operator.blocks.TransformBlock;
+import org.apache.pinot.core.operator.transform.TransformOperator;
+import org.apache.pinot.core.query.request.context.QueryContext;
+import org.apache.pinot.segment.spi.IndexSegment;
+
+
+/**
+ * An operator for order-by queries DESC that are partially sorted over the sorting keys.
+ *
+ * @see LinearSelectionOrderByOperator
+ */
+public class SelectionPartiallyOrderedByDescOperation extends LinearSelectionOrderByOperator {
+
+  private static final String EXPLAIN_NAME = "SELECT_PARTIAL_ORDER_BY_DESC";
+
+  private int _numDocsScanned = 0;
+  private long _numEntriesScannedPostFilter = 0;
+
+  public SelectionPartiallyOrderedByDescOperation(IndexSegment indexSegment, QueryContext queryContext,
+      List<ExpressionContext> expressions, TransformOperator transformOperator, int sortedExpr) {
+    super(indexSegment, queryContext, expressions, transformOperator, sortedExpr);
+    assert queryContext.getOrderByExpressions() != null;
+    Preconditions.checkArgument(queryContext.getOrderByExpressions().stream()
+            .filter(expr -> expr.getExpression().getType() == ExpressionContext.Type.IDENTIFIER)
+            .findFirst()
+            .orElseThrow(() -> new IllegalArgumentException("The query is not order by identifiers"))
+            .isDesc(),
+        "%s can only be used when the first column in order by is DESC", EXPLAIN_NAME);
+  }
+
+  @Override
+  protected List<Object[]> fetch(Supplier<ListBuilder> listBuilderSupplier) {
+
+    // Ideally we would use a descending cursor, but we don't actually have them
+    // Alternatively, we could store all blocks in a list and iterate them in reverse order, but ProjectionBlocks share
+    // the same DataBlockCache, so they may be ephemeral and being overridden by the next block.
+    // The only alternative we have right now is to retrieve the last LIMIT elements from each block
+
+    TransformBlock block;
+    int numColumnsProjected = _transformOperator.getNumColumnsProjected();
+    int numExpressions = _expressions.size();
+    BlockValSet[] blockValSets = new BlockValSet[numExpressions];
+
+    List<Object[]> localBestRows = new ArrayList<>();
+
+    try {
+      while ((block = _transformOperator.nextBlock()) != null) {
+        int numDocsFetched = block.getNumDocs();
+        _numDocsScanned += numDocsFetched;
+
+        IntFunction<Object[]> rowFetcher = fetchBlock(block, blockValSets);
+
+        ListBuilder listBuilder = listBuilderSupplier.get();
+
+        if (block.getNumDocs() == 0) {
+          continue;
+        }
+
+        // first, calculate the best rows on this block
+        boolean newPartition = false;
+        for (int docId = block.getNumDocs() - 1; docId >= 0; docId--) {
+          newPartition = listBuilder.add(rowFetcher.apply(docId));
+          if (newPartition && listBuilder.sortedSize() >= _numRowsToKeep) {
+            // We changed to a new partition and we have more values than required.
+            // Therefore, we can stop the execution of this block here.
+            break;
+          }
+        }
+        // then try to add the best rows from previous block
+        Iterator<Object[]> localBestRowIt = localBestRows.iterator();
+        while (localBestRowIt.hasNext() && !newPartition && listBuilder.sortedSize() < _numRowsToKeep) {

Review Comment:
   This logic doesn't seem correct to me. E.g. when it is new partition, but not enough rows collected, we should still add the row.



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] gortiz commented on pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
gortiz commented on PR #8979:
URL: https://github.com/apache/pinot/pull/8979#issuecomment-1198911033

   > For descending order, ideally we should implement an iterator which can read rows in reverse order
   
   That was my first approach and for sure it would be better. But the cursor interface specifies that iteration must be done in ascending order. I tried to add a new reverse cursor that doesn't do that, but I wasn't sure about its implications. If there is some out code there that assumes all cursor iterations are going to be ascending, we may have problems. Therefore I prefer to initially add an implementation that is more conservative.


-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] gortiz commented on a diff in pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
gortiz commented on code in PR #8979:
URL: https://github.com/apache/pinot/pull/8979#discussion_r973917527


##########
pinot-core/src/main/java/org/apache/pinot/core/plan/SelectionPlanNode.java:
##########
@@ -50,67 +52,113 @@ public Operator<IntermediateResultsBlock> run() {
     List<ExpressionContext> expressions = SelectionOperatorUtils.extractExpressions(_queryContext, _indexSegment);
     int limit = _queryContext.getLimit();
 
-    if (limit > 0) {
-      List<OrderByExpressionContext> orderByExpressions = _queryContext.getOrderByExpressions();
-      if (orderByExpressions == null) {
-        // Selection only
-        TransformOperator transformOperator = new TransformPlanNode(_indexSegment, _queryContext, expressions,
-            Math.min(limit, DocIdSetPlanNode.MAX_DOC_PER_CALL)).run();
-        return new SelectionOnlyOperator(_indexSegment, _queryContext, expressions, transformOperator);
-      } else {
-        // Selection order-by
-        if (isAllOrderByColumnsSorted(orderByExpressions)) {
-          // All order-by columns are sorted, no need to sort the records
-          TransformOperator transformOperator = new TransformPlanNode(_indexSegment, _queryContext, expressions,
-              Math.min(limit + _queryContext.getOffset(), DocIdSetPlanNode.MAX_DOC_PER_CALL)).run();
-          return new SelectionOrderByOperator(_indexSegment, _queryContext, expressions, transformOperator, true);
-        } else if (orderByExpressions.size() == expressions.size()) {
-          // All output expressions are ordered
-          TransformOperator transformOperator =
-              new TransformPlanNode(_indexSegment, _queryContext, expressions, DocIdSetPlanNode.MAX_DOC_PER_CALL).run();
-          return new SelectionOrderByOperator(_indexSegment, _queryContext, expressions, transformOperator, false);
-        } else {
-          // Not all output expressions are ordered, only fetch the order-by expressions and docId to avoid the
-          // unnecessary data fetch
-          List<ExpressionContext> expressionsToTransform = new ArrayList<>(orderByExpressions.size());
-          for (OrderByExpressionContext orderByExpression : orderByExpressions) {
-            expressionsToTransform.add(orderByExpression.getExpression());
-          }
-          TransformOperator transformOperator =
-              new TransformPlanNode(_indexSegment, _queryContext, expressionsToTransform,
-                  DocIdSetPlanNode.MAX_DOC_PER_CALL).run();
-          return new SelectionOrderByOperator(_indexSegment, _queryContext, expressions, transformOperator, false);
-        }
-      }
-    } else {
+    if (limit == 0) {
       // Empty selection (LIMIT 0)
       TransformOperator transformOperator = new TransformPlanNode(_indexSegment, _queryContext, expressions, 0).run();
       return new EmptySelectionOperator(_indexSegment, expressions, transformOperator);
     }
+    List<OrderByExpressionContext> orderByExpressions = _queryContext.getOrderByExpressions();
+
+    if (orderByExpressions == null) {
+      // Selection only
+      // ie: SELECT ... FROM Table WHERE ... LIMIT 10
+      int actualLimit = Math.min(limit, DocIdSetPlanNode.MAX_DOC_PER_CALL);
+      TransformPlanNode planNode = new TransformPlanNode(_indexSegment, _queryContext, expressions, actualLimit);
+      TransformOperator transformOperator = planNode.run();
+
+      return new SelectionOnlyOperator(_indexSegment, _queryContext, expressions, transformOperator);
+    }
+    int numOrderByExpressions = orderByExpressions.size();
+    // Although it is a break of abstraction, some code, specially merging, assumes that if there is an order by
+    // expression the operator will return a block whose selection result is a priority queue.
+    int sortedColumnsPrefixSize = getSortedColumnsPrefix(orderByExpressions);

Review Comment:
   > So what we can do here is deciding whether to use this optimization at query time, and not use it when null handling is enabled and the column contains null values
   
   What I did was to change the method that checks whether an expression is sorted or not by adding the following condition:
   ```java
           // If there are null values, we cannot trust DataSourceMetadata.isSorted
           if (isNullHandlingEnabled) {
             NullValueVectorReader nullValueVector = dataSource.getNullValueVector();
             if (nullValueVector != null && !nullValueVector.getNullBitmap().isEmpty()) {
               return false;
             }
           }
   ```
   
   AFAIK that is the most precise way to check if the column has a null value. I'm open to change that to other better ways if exists.
   
   It would be great if we could do something like that directly in DataSourceMetadata, but we don't have the null vector there.



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] gortiz commented on a diff in pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
gortiz commented on code in PR #8979:
URL: https://github.com/apache/pinot/pull/8979#discussion_r977493729


##########
pinot-core/src/main/java/org/apache/pinot/core/operator/combine/BaseCombineOperator.java:
##########
@@ -162,7 +162,7 @@ protected void processSegments() {
         if (operator instanceof AcquireReleaseColumnsSegmentOperator) {
           ((AcquireReleaseColumnsSegmentOperator) operator).acquire();
         }
-        resultsBlock = (T) operator.nextBlock();
+        resultsBlock = createInitialResultBlock((T) operator.nextBlock());

Review Comment:
   Yeah, the naming wasn't good.



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] gortiz commented on a diff in pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
gortiz commented on code in PR #8979:
URL: https://github.com/apache/pinot/pull/8979#discussion_r979756324


##########
pinot-core/src/main/java/org/apache/pinot/core/operator/combine/BaseCombineOperator.java:
##########
@@ -162,7 +162,7 @@ protected void processSegments() {
         if (operator instanceof AcquireReleaseColumnsSegmentOperator) {
           ((AcquireReleaseColumnsSegmentOperator) operator).acquire();
         }
-        resultsBlock = (T) operator.nextBlock();
+        resultsBlock = convertToMergeableBlock((BaseResultsBlock) operator.nextBlock());

Review Comment:
   Good catch, but by simply changing `resultBlock` to `BaseResultsBlock` we cannot call `isQuerySatisfied` because it demands a `T`. I've applied some extra modifications, please check if they are good enough



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] Jackie-Jiang commented on a diff in pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
Jackie-Jiang commented on code in PR #8979:
URL: https://github.com/apache/pinot/pull/8979#discussion_r981783624


##########
pinot-core/src/main/java/org/apache/pinot/core/plan/SelectionPlanNode.java:
##########
@@ -50,67 +55,119 @@ public Operator<SelectionResultsBlock> run() {
     List<ExpressionContext> expressions = SelectionOperatorUtils.extractExpressions(_queryContext, _indexSegment);
     int limit = _queryContext.getLimit();
 
-    if (limit > 0) {
-      List<OrderByExpressionContext> orderByExpressions = _queryContext.getOrderByExpressions();
-      if (orderByExpressions == null) {
-        // Selection only
-        TransformOperator transformOperator = new TransformPlanNode(_indexSegment, _queryContext, expressions,
-            Math.min(limit, DocIdSetPlanNode.MAX_DOC_PER_CALL)).run();
-        return new SelectionOnlyOperator(_indexSegment, _queryContext, expressions, transformOperator);
-      } else {
-        // Selection order-by
-        if (isAllOrderByColumnsSorted(orderByExpressions)) {
-          // All order-by columns are sorted, no need to sort the records
-          TransformOperator transformOperator = new TransformPlanNode(_indexSegment, _queryContext, expressions,
-              Math.min(limit + _queryContext.getOffset(), DocIdSetPlanNode.MAX_DOC_PER_CALL)).run();
-          return new SelectionOrderByOperator(_indexSegment, _queryContext, expressions, transformOperator, true);
-        } else if (orderByExpressions.size() == expressions.size()) {
-          // All output expressions are ordered
-          TransformOperator transformOperator =
-              new TransformPlanNode(_indexSegment, _queryContext, expressions, DocIdSetPlanNode.MAX_DOC_PER_CALL).run();
-          return new SelectionOrderByOperator(_indexSegment, _queryContext, expressions, transformOperator, false);
-        } else {
-          // Not all output expressions are ordered, only fetch the order-by expressions and docId to avoid the
-          // unnecessary data fetch
-          List<ExpressionContext> expressionsToTransform = new ArrayList<>(orderByExpressions.size());
-          for (OrderByExpressionContext orderByExpression : orderByExpressions) {
-            expressionsToTransform.add(orderByExpression.getExpression());
-          }
-          TransformOperator transformOperator =
-              new TransformPlanNode(_indexSegment, _queryContext, expressionsToTransform,
-                  DocIdSetPlanNode.MAX_DOC_PER_CALL).run();
-          return new SelectionOrderByOperator(_indexSegment, _queryContext, expressions, transformOperator, false);
-        }
-      }
-    } else {
+    if (limit == 0) {
       // Empty selection (LIMIT 0)
       TransformOperator transformOperator = new TransformPlanNode(_indexSegment, _queryContext, expressions, 0).run();
       return new EmptySelectionOperator(_indexSegment, expressions, transformOperator);
     }
+    List<OrderByExpressionContext> orderByExpressions = _queryContext.getOrderByExpressions();
+    if (orderByExpressions == null) {
+      // Selection only
+      // ie: SELECT ... FROM Table WHERE ... LIMIT 10
+      int maxDocsPerCall = Math.min(limit, DocIdSetPlanNode.MAX_DOC_PER_CALL);
+      TransformPlanNode planNode = new TransformPlanNode(_indexSegment, _queryContext, expressions, maxDocsPerCall);
+      TransformOperator transformOperator = planNode.run();
+
+      return new SelectionOnlyOperator(_indexSegment, _queryContext, expressions, transformOperator);
+    }
+    int numOrderByExpressions = orderByExpressions.size();
+    // Although it is a break of abstraction, some code, specially merging, assumes that if there is an order by
+    // expression the operator will return a block whose selection result is a priority queue.
+    int sortedColumnsPrefixSize = getSortedColumnsPrefix(orderByExpressions, _queryContext.isNullHandlingEnabled());
+    if (sortedColumnsPrefixSize > 0 && !isSkipOrderByOptimization()) {
+      // The first order by expressions are sorted (either asc or desc).
+      // ie: SELECT ... FROM Table WHERE predicates ORDER BY sorted_column DESC LIMIT 10 OFFSET 5
+      // or: SELECT ... FROM Table WHERE predicates ORDER BY sorted_column, not_sorted LIMIT 10 OFFSET 5
+      // but not SELECT ... FROM Table WHERE predicates ORDER BY not_sorted, sorted_column LIMIT 10 OFFSET 5
+      if (orderByExpressions.get(0).isAsc()) {
+        int maxDocsPerCall = Math.min(limit + _queryContext.getOffset(), DocIdSetPlanNode.MAX_DOC_PER_CALL);
+        TransformPlanNode planNode = new TransformPlanNode(_indexSegment, _queryContext, expressions, maxDocsPerCall);
+        TransformOperator transformOperator = planNode.run();
+        return new SelectionPartiallyOrderedByAscOperator(_indexSegment, _queryContext, expressions,
+            transformOperator, sortedColumnsPrefixSize);
+      } else {
+        int maxDocsPerCall = DocIdSetPlanNode.MAX_DOC_PER_CALL;

Review Comment:
   Oh, I see why it is still faster than the naive one even when we need to scan all the records. The naive one will keep pushing new element into the PQ, which is an O(nlogk) where k is the limit. The new algorithm is O(n)



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] gortiz commented on a diff in pull request #8979: optimize `order by sorted ASC, unsorted` case

Posted by GitBox <gi...@apache.org>.
gortiz commented on code in PR #8979:
URL: https://github.com/apache/pinot/pull/8979#discussion_r913463570


##########
pinot-core/src/main/java/org/apache/pinot/core/operator/query/SelectionPartiallyOrderedByOperator.java:
##########
@@ -0,0 +1,303 @@
+/**
+ * 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.pinot.core.operator.query;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+import javax.annotation.Nullable;
+import org.apache.pinot.common.request.context.ExpressionContext;
+import org.apache.pinot.common.request.context.OrderByExpressionContext;
+import org.apache.pinot.common.utils.DataSchema;
+import org.apache.pinot.core.common.BlockValSet;
+import org.apache.pinot.core.common.Operator;
+import org.apache.pinot.core.common.RowBasedBlockValueFetcher;
+import org.apache.pinot.core.operator.BaseOperator;
+import org.apache.pinot.core.operator.ExecutionStatistics;
+import org.apache.pinot.core.operator.blocks.IntermediateResultsBlock;
+import org.apache.pinot.core.operator.blocks.TransformBlock;
+import org.apache.pinot.core.operator.transform.TransformOperator;
+import org.apache.pinot.core.operator.transform.TransformResultMetadata;
+import org.apache.pinot.core.query.request.context.QueryContext;
+import org.apache.pinot.core.query.selection.SelectionOperatorUtils;
+import org.apache.pinot.segment.spi.IndexSegment;
+
+
+/**
+ * An operator for order-by queries that are partially sorted over the sorting keys.
+ */
+public class SelectionPartiallyOrderedByOperator extends BaseOperator<IntermediateResultsBlock> {
+
+  private static final String EXPLAIN_NAME = "SELECT_PARTIAL_ORDERBY";
+
+  private final IndexSegment _indexSegment;
+
+  // Deduped order-by expressions followed by output expressions from SelectionOperatorUtils.extractExpressions()
+  private final List<ExpressionContext> _expressions;
+  private final List<ExpressionContext> _alreadySorted;
+  private final List<ExpressionContext> _toSort;
+
+  private final TransformOperator _transformOperator;
+  private final List<OrderByExpressionContext> _orderByExpressions;
+  private final TransformResultMetadata[] _expressionsMetadata;
+  private final int _numRowsToKeep;
+  private final PartiallySortedListBuilder _sorter;
+
+  private int _numDocsScanned = 0;
+  private long _numEntriesScannedPostFilter = 0;
+  private boolean _used = false;
+  private Comparator<Object[]> _comparator;
+
+  public SelectionPartiallyOrderedByOperator(IndexSegment indexSegment, QueryContext queryContext,
+      List<ExpressionContext> expressions, TransformOperator transformOperator, int sortedExpr) {
+    Preconditions.checkArgument(sortedExpr > 0,
+        "This operator should not be used when sorting expressions doesn't start with sorted expressions");
+    _indexSegment = indexSegment;
+    _expressions = expressions;
+    _transformOperator = transformOperator;
+
+    _orderByExpressions = queryContext.getOrderByExpressions();
+    assert _orderByExpressions != null;
+    int numOrderByExpressions = _orderByExpressions.size();
+
+    _alreadySorted = expressions.subList(0, sortedExpr);
+    _toSort = expressions.subList(sortedExpr, numOrderByExpressions);
+
+    Preconditions.checkArgument(!_toSort.isEmpty(),
+        "This operator should not be used when all sorting expressions are sorted. "
+            + "Use %s instead", SelectionOrderByOperator.class.getName());
+
+    _expressionsMetadata = new TransformResultMetadata[_expressions.size()];
+    for (int i = 0; i < _expressionsMetadata.length; i++) {
+      ExpressionContext expression = _expressions.get(i);
+      _expressionsMetadata[i] = _transformOperator.getResultMetadata(expression);
+    }
+
+    _numRowsToKeep = queryContext.getOffset() + queryContext.getLimit();
+
+    int expectedSize = Math.min(_numRowsToKeep * 2, SelectionOperatorUtils.MAX_ROW_HOLDER_INITIAL_CAPACITY);
+    Comparator<Object[]> sortedComparator =
+        SelectionOrderByOperator.getComparator(_orderByExpressions, _expressionsMetadata, true, 0, sortedExpr);
+    Comparator<Object[]> unsortedComparator =
+        SelectionOrderByOperator.getComparator(_orderByExpressions, _expressionsMetadata, true, sortedExpr,
+            numOrderByExpressions);
+    _sorter = new PartiallySortedListBuilder(expectedSize, sortedComparator, unsortedComparator);
+    _comparator = SelectionOrderByOperator.getComparator(_orderByExpressions, _expressionsMetadata, false);
+  }
+
+  @Override
+  public List<Operator> getChildOperators() {
+    return Collections.singletonList(_transformOperator);
+  }
+
+  @Override
+  protected IntermediateResultsBlock getNextBlock() {
+    if (!_used) {
+      _used = true;
+      fetch();
+
+      DataSchema dataSchema = createDataSchema();
+
+      return new IntermediateResultsBlock.ListSelection(dataSchema, _sorter.build(), _comparator);

Review Comment:
   We create one `SelectionPartiallyOrderedByOperator` per segment, right? So yeah, we build one of this `sorter`s for every segment.
   
   Remember that `_sorter.build()` does not generate memory, it just returns the list it used internally and it shouldn't be used again.



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] jackjlli commented on a diff in pull request #8979: optimize `order by sorted ASC, unsorted` case

Posted by GitBox <gi...@apache.org>.
jackjlli commented on code in PR #8979:
URL: https://github.com/apache/pinot/pull/8979#discussion_r910422736


##########
pinot-core/src/main/java/org/apache/pinot/core/operator/query/SelectionPartiallyOrderedByOperator.java:
##########
@@ -0,0 +1,303 @@
+/**
+ * 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.pinot.core.operator.query;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+import javax.annotation.Nullable;
+import org.apache.pinot.common.request.context.ExpressionContext;
+import org.apache.pinot.common.request.context.OrderByExpressionContext;
+import org.apache.pinot.common.utils.DataSchema;
+import org.apache.pinot.core.common.BlockValSet;
+import org.apache.pinot.core.common.Operator;
+import org.apache.pinot.core.common.RowBasedBlockValueFetcher;
+import org.apache.pinot.core.operator.BaseOperator;
+import org.apache.pinot.core.operator.ExecutionStatistics;
+import org.apache.pinot.core.operator.blocks.IntermediateResultsBlock;
+import org.apache.pinot.core.operator.blocks.TransformBlock;
+import org.apache.pinot.core.operator.transform.TransformOperator;
+import org.apache.pinot.core.operator.transform.TransformResultMetadata;
+import org.apache.pinot.core.query.request.context.QueryContext;
+import org.apache.pinot.core.query.selection.SelectionOperatorUtils;
+import org.apache.pinot.segment.spi.IndexSegment;
+
+
+/**
+ * An operator for order-by queries that are partially sorted over the sorting keys.
+ */
+public class SelectionPartiallyOrderedByOperator extends BaseOperator<IntermediateResultsBlock> {
+
+  private static final String EXPLAIN_NAME = "SELECT_PARTIAL_ORDERBY";
+
+  private final IndexSegment _indexSegment;
+
+  // Deduped order-by expressions followed by output expressions from SelectionOperatorUtils.extractExpressions()
+  private final List<ExpressionContext> _expressions;
+  private final List<ExpressionContext> _alreadySorted;
+  private final List<ExpressionContext> _toSort;
+
+  private final TransformOperator _transformOperator;
+  private final List<OrderByExpressionContext> _orderByExpressions;
+  private final TransformResultMetadata[] _expressionsMetadata;
+  private final int _numRowsToKeep;
+  private final PartiallySortedListBuilder _sorter;
+
+  private int _numDocsScanned = 0;
+  private long _numEntriesScannedPostFilter = 0;
+  private boolean _used = false;

Review Comment:
   What's the purpose of this `_used` variable?



##########
pinot-core/src/main/java/org/apache/pinot/core/operator/query/SelectionPartiallyOrderedByOperator.java:
##########
@@ -0,0 +1,303 @@
+/**
+ * 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.pinot.core.operator.query;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+import javax.annotation.Nullable;
+import org.apache.pinot.common.request.context.ExpressionContext;
+import org.apache.pinot.common.request.context.OrderByExpressionContext;
+import org.apache.pinot.common.utils.DataSchema;
+import org.apache.pinot.core.common.BlockValSet;
+import org.apache.pinot.core.common.Operator;
+import org.apache.pinot.core.common.RowBasedBlockValueFetcher;
+import org.apache.pinot.core.operator.BaseOperator;
+import org.apache.pinot.core.operator.ExecutionStatistics;
+import org.apache.pinot.core.operator.blocks.IntermediateResultsBlock;
+import org.apache.pinot.core.operator.blocks.TransformBlock;
+import org.apache.pinot.core.operator.transform.TransformOperator;
+import org.apache.pinot.core.operator.transform.TransformResultMetadata;
+import org.apache.pinot.core.query.request.context.QueryContext;
+import org.apache.pinot.core.query.selection.SelectionOperatorUtils;
+import org.apache.pinot.segment.spi.IndexSegment;
+
+
+/**
+ * An operator for order-by queries that are partially sorted over the sorting keys.
+ */
+public class SelectionPartiallyOrderedByOperator extends BaseOperator<IntermediateResultsBlock> {
+
+  private static final String EXPLAIN_NAME = "SELECT_PARTIAL_ORDERBY";
+
+  private final IndexSegment _indexSegment;
+
+  // Deduped order-by expressions followed by output expressions from SelectionOperatorUtils.extractExpressions()
+  private final List<ExpressionContext> _expressions;
+  private final List<ExpressionContext> _alreadySorted;
+  private final List<ExpressionContext> _toSort;
+
+  private final TransformOperator _transformOperator;
+  private final List<OrderByExpressionContext> _orderByExpressions;
+  private final TransformResultMetadata[] _expressionsMetadata;
+  private final int _numRowsToKeep;
+  private final PartiallySortedListBuilder _sorter;
+
+  private int _numDocsScanned = 0;
+  private long _numEntriesScannedPostFilter = 0;
+  private boolean _used = false;
+  private Comparator<Object[]> _comparator;
+
+  public SelectionPartiallyOrderedByOperator(IndexSegment indexSegment, QueryContext queryContext,
+      List<ExpressionContext> expressions, TransformOperator transformOperator, int sortedExpr) {
+    Preconditions.checkArgument(sortedExpr > 0,
+        "This operator should not be used when sorting expressions doesn't start with sorted expressions");
+    _indexSegment = indexSegment;
+    _expressions = expressions;
+    _transformOperator = transformOperator;
+
+    _orderByExpressions = queryContext.getOrderByExpressions();
+    assert _orderByExpressions != null;
+    int numOrderByExpressions = _orderByExpressions.size();
+
+    _alreadySorted = expressions.subList(0, sortedExpr);
+    _toSort = expressions.subList(sortedExpr, numOrderByExpressions);
+
+    Preconditions.checkArgument(!_toSort.isEmpty(),
+        "This operator should not be used when all sorting expressions are sorted. "
+            + "Use %s instead", SelectionOrderByOperator.class.getName());
+
+    _expressionsMetadata = new TransformResultMetadata[_expressions.size()];
+    for (int i = 0; i < _expressionsMetadata.length; i++) {
+      ExpressionContext expression = _expressions.get(i);
+      _expressionsMetadata[i] = _transformOperator.getResultMetadata(expression);
+    }
+
+    _numRowsToKeep = queryContext.getOffset() + queryContext.getLimit();
+
+    int expectedSize = Math.min(_numRowsToKeep * 2, SelectionOperatorUtils.MAX_ROW_HOLDER_INITIAL_CAPACITY);
+    Comparator<Object[]> sortedComparator =
+        SelectionOrderByOperator.getComparator(_orderByExpressions, _expressionsMetadata, true, 0, sortedExpr);
+    Comparator<Object[]> unsortedComparator =
+        SelectionOrderByOperator.getComparator(_orderByExpressions, _expressionsMetadata, true, sortedExpr,
+            numOrderByExpressions);
+    _sorter = new PartiallySortedListBuilder(expectedSize, sortedComparator, unsortedComparator);
+    _comparator = SelectionOrderByOperator.getComparator(_orderByExpressions, _expressionsMetadata, false);
+  }
+
+  @Override
+  public List<Operator> getChildOperators() {
+    return Collections.singletonList(_transformOperator);
+  }
+
+  @Override
+  protected IntermediateResultsBlock getNextBlock() {
+    if (!_used) {
+      _used = true;
+      fetch();
+
+      DataSchema dataSchema = createDataSchema();
+
+      return new IntermediateResultsBlock.ListSelection(dataSchema, _sorter.build(), _comparator);
+    }
+    return null;
+  }
+
+  private DataSchema createDataSchema() {
+
+    int numExpressions = _expressions.size();
+
+    // Create the data schema
+    String[] columnNames = new String[numExpressions];
+    DataSchema.ColumnDataType[] columnDataTypes = new DataSchema.ColumnDataType[numExpressions];
+    for (int i = 0; i < columnNames.length; i++) {
+      columnNames[i] = _expressions.get(i).toString();
+    }
+    for (int i = 0; i < numExpressions; i++) {
+      TransformResultMetadata expressionMetadata = _expressionsMetadata[i];
+      columnDataTypes[i] =
+          DataSchema.ColumnDataType.fromDataType(expressionMetadata.getDataType(), expressionMetadata.isSingleValue());
+    }
+    return new DataSchema(columnNames, columnDataTypes);
+  }
+
+  /**
+   * Fetches the rows that are needed into {@link #_sorter} and updated the metrics.
+   *
+   * The sorter can still be used.
+   */
+  private void fetch() {
+    int numExpressions = _expressions.size();
+    BlockValSet[] blockValSets = new BlockValSet[numExpressions];
+
+    TransformBlock transformBlock;
+    int numColumnsProjected = _transformOperator.getNumColumnsProjected();
+    try {
+      while ((transformBlock = _transformOperator.nextBlock()) != null) {
+        for (int i = 0; i < numExpressions; i++) {
+          ExpressionContext expression = _expressions.get(i);
+          blockValSets[i] = transformBlock.getBlockValueSet(expression);
+        }
+        RowBasedBlockValueFetcher blockValueFetcher = new RowBasedBlockValueFetcher(blockValSets);
+        int numDocsFetched = transformBlock.getNumDocs();
+        _numDocsScanned += numDocsFetched;
+        for (int i = 0; i < numDocsFetched; i++) {
+          boolean newBlock = _sorter.add(blockValueFetcher.getRow(i));
+          if (newBlock && _sorter.sortedSize() >= _numRowsToKeep) {
+            // We changed to a new section to ordered sorted values and we have more values than required.
+            // Therefore, we can stop the execution here.
+            return;
+          }
+        }
+      }
+    } finally {
+      _numEntriesScannedPostFilter = (long) _numDocsScanned * numColumnsProjected;
+    }
+  }
+
+  @Override
+  public String toExplainString() {
+    StringBuilder sb = new StringBuilder(EXPLAIN_NAME);
+
+    sb.append("(sortedList: ");
+    concatList(sb, _alreadySorted);
+
+    sb.append(", unsortedList: ");
+    concatList(sb, _toSort);
+
+    sb.append(", rest: ");
+    concatList(sb, _expressions.subList(_alreadySorted.size() + _toSort.size(), _expressions.size()));
+
+    sb.append(')');
+    return sb.toString();
+  }
+
+  private void concatList(StringBuilder sb, List<?> list) {
+    sb.append('(');
+    Iterator<?> it = list.iterator();
+    if (it.hasNext()) {
+      sb.append(it.next());
+      while (it.hasNext()) {
+        sb.append(", ").append(it.next());
+      }
+    }
+    sb.append(')');
+  }
+
+  @Override
+  public ExecutionStatistics getExecutionStatistics() {
+    long numEntriesScannedInFilter = _transformOperator.getExecutionStatistics().getNumEntriesScannedInFilter();
+    int numTotalDocs = _indexSegment.getSegmentMetadata().getTotalDocs();
+    return new ExecutionStatistics(_numDocsScanned, numEntriesScannedInFilter, _numEntriesScannedPostFilter,
+        numTotalDocs);
+  }
+
+  /**
+   * A private class used to build a sorted list by adding partially sorted data.
+   *
+   * Specifically, this class has been designed to receive successive calls to {@link #add(Object[])} follow by a single
+   * call to {@link #build()}. Once this method is called, the behavior of this object is undefined and therefore it
+   * should not be used.
+   *
+   * Rows must be inserted in ascending order accordingly to the partial order specified by {@link #_sortedComparator}.
+   * This comparator will define <i>partitions</i> of rows. All the rows in the same partition same are considered equal
+   * by that comparator.
+   *
+   * There is a second comparator called {@link #_unsortedComparator} that is used to sort rows inside each partition.
+   * When calling {@link #add(Object[])} with a row that doesn't belong to the current partition, a new one is started
+   * and the previous one is sorted. Therefore, this object maintains the invariant that at any moment there are at
+   * least {@link #sortedSize()} elements that are completely sorted, which means that no matter which elements are
+   * added after that, these elements are going to be smallest.
+   */
+  private static class PartiallySortedListBuilder {
+    private final ArrayList<Object[]> _rows;
+    private final Comparator<Object[]> _sortedComparator;
+    private final Comparator<Object[]> _unsortedComparator;
+
+    public PartiallySortedListBuilder(int expectedSize, Comparator<Object[]> sortedComparator,
+        Comparator<Object[]> unsortedComparator) {
+      _rows = new ArrayList<>(expectedSize);
+      _sortedComparator = sortedComparator;
+      _unsortedComparator = unsortedComparator;
+    }
+
+    @Nullable
+    private Object[] _lastBlockRow;
+    private int _lastSorted;
+
+    /**
+     * Adds the given row to this object. The new column must be equal or higher than the last added row in relation to
+     * {@link #_sortedComparator}.
+     *
+     * @param row The row to add. The values of the already sorted columns must be equal or higher than the last added
+     *           row, if any.
+     * @return true if and only if the previous block was closed.
+     */
+    boolean add(Object[] row) {
+      boolean result;
+      if (_lastBlockRow == null) {
+        _lastSorted = 0;
+        _lastBlockRow = row;
+        result = false;
+      } else {
+        int cmp = _sortedComparator.compare(_lastBlockRow, row);
+        assert cmp >= 0 : "Row " + Arrays.toString(row) + " is lower than previously added row"

Review Comment:
   Consider using Preconditions class?



##########
pinot-core/src/main/java/org/apache/pinot/core/operator/query/SelectionPartiallyOrderedByOperator.java:
##########
@@ -0,0 +1,303 @@
+/**
+ * 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.pinot.core.operator.query;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+import javax.annotation.Nullable;
+import org.apache.pinot.common.request.context.ExpressionContext;
+import org.apache.pinot.common.request.context.OrderByExpressionContext;
+import org.apache.pinot.common.utils.DataSchema;
+import org.apache.pinot.core.common.BlockValSet;
+import org.apache.pinot.core.common.Operator;
+import org.apache.pinot.core.common.RowBasedBlockValueFetcher;
+import org.apache.pinot.core.operator.BaseOperator;
+import org.apache.pinot.core.operator.ExecutionStatistics;
+import org.apache.pinot.core.operator.blocks.IntermediateResultsBlock;
+import org.apache.pinot.core.operator.blocks.TransformBlock;
+import org.apache.pinot.core.operator.transform.TransformOperator;
+import org.apache.pinot.core.operator.transform.TransformResultMetadata;
+import org.apache.pinot.core.query.request.context.QueryContext;
+import org.apache.pinot.core.query.selection.SelectionOperatorUtils;
+import org.apache.pinot.segment.spi.IndexSegment;
+
+
+/**
+ * An operator for order-by queries that are partially sorted over the sorting keys.
+ */
+public class SelectionPartiallyOrderedByOperator extends BaseOperator<IntermediateResultsBlock> {
+
+  private static final String EXPLAIN_NAME = "SELECT_PARTIAL_ORDERBY";
+
+  private final IndexSegment _indexSegment;
+
+  // Deduped order-by expressions followed by output expressions from SelectionOperatorUtils.extractExpressions()
+  private final List<ExpressionContext> _expressions;
+  private final List<ExpressionContext> _alreadySorted;
+  private final List<ExpressionContext> _toSort;
+
+  private final TransformOperator _transformOperator;
+  private final List<OrderByExpressionContext> _orderByExpressions;
+  private final TransformResultMetadata[] _expressionsMetadata;
+  private final int _numRowsToKeep;
+  private final PartiallySortedListBuilder _sorter;
+
+  private int _numDocsScanned = 0;
+  private long _numEntriesScannedPostFilter = 0;
+  private boolean _used = false;
+  private Comparator<Object[]> _comparator;
+
+  public SelectionPartiallyOrderedByOperator(IndexSegment indexSegment, QueryContext queryContext,
+      List<ExpressionContext> expressions, TransformOperator transformOperator, int sortedExpr) {
+    Preconditions.checkArgument(sortedExpr > 0,
+        "This operator should not be used when sorting expressions doesn't start with sorted expressions");
+    _indexSegment = indexSegment;
+    _expressions = expressions;
+    _transformOperator = transformOperator;
+
+    _orderByExpressions = queryContext.getOrderByExpressions();
+    assert _orderByExpressions != null;
+    int numOrderByExpressions = _orderByExpressions.size();
+
+    _alreadySorted = expressions.subList(0, sortedExpr);
+    _toSort = expressions.subList(sortedExpr, numOrderByExpressions);
+
+    Preconditions.checkArgument(!_toSort.isEmpty(),
+        "This operator should not be used when all sorting expressions are sorted. "
+            + "Use %s instead", SelectionOrderByOperator.class.getName());
+
+    _expressionsMetadata = new TransformResultMetadata[_expressions.size()];
+    for (int i = 0; i < _expressionsMetadata.length; i++) {
+      ExpressionContext expression = _expressions.get(i);
+      _expressionsMetadata[i] = _transformOperator.getResultMetadata(expression);
+    }
+
+    _numRowsToKeep = queryContext.getOffset() + queryContext.getLimit();
+
+    int expectedSize = Math.min(_numRowsToKeep * 2, SelectionOperatorUtils.MAX_ROW_HOLDER_INITIAL_CAPACITY);
+    Comparator<Object[]> sortedComparator =
+        SelectionOrderByOperator.getComparator(_orderByExpressions, _expressionsMetadata, true, 0, sortedExpr);
+    Comparator<Object[]> unsortedComparator =
+        SelectionOrderByOperator.getComparator(_orderByExpressions, _expressionsMetadata, true, sortedExpr,
+            numOrderByExpressions);
+    _sorter = new PartiallySortedListBuilder(expectedSize, sortedComparator, unsortedComparator);
+    _comparator = SelectionOrderByOperator.getComparator(_orderByExpressions, _expressionsMetadata, false);
+  }
+
+  @Override
+  public List<Operator> getChildOperators() {
+    return Collections.singletonList(_transformOperator);
+  }
+
+  @Override
+  protected IntermediateResultsBlock getNextBlock() {
+    if (!_used) {
+      _used = true;
+      fetch();
+
+      DataSchema dataSchema = createDataSchema();
+
+      return new IntermediateResultsBlock.ListSelection(dataSchema, _sorter.build(), _comparator);

Review Comment:
   Does it mean we have to build the sorter for every query per segment?



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] gortiz commented on a diff in pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
gortiz commented on code in PR #8979:
URL: https://github.com/apache/pinot/pull/8979#discussion_r932898409


##########
pinot-core/src/main/java/org/apache/pinot/core/operator/query/SelectionPartiallyOrderedByDescOperation.java:
##########
@@ -0,0 +1,105 @@
+/**
+ * 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.pinot.core.operator.query;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.List;
+import org.apache.pinot.common.request.context.ExpressionContext;
+import org.apache.pinot.core.common.BlockValSet;
+import org.apache.pinot.core.common.RowBasedBlockValueFetcher;
+import org.apache.pinot.core.operator.blocks.TransformBlock;
+import org.apache.pinot.core.operator.transform.TransformOperator;
+import org.apache.pinot.core.query.request.context.QueryContext;
+import org.apache.pinot.segment.spi.IndexSegment;
+
+
+/**
+ * An operator for order-by queries DESC that are partially sorted over the sorting keys.
+ *
+ * @see LinearSelectionOrderByOperator
+ */
+public class SelectionPartiallyOrderedByDescOperation extends LinearSelectionOrderByOperator {
+
+  private static final String EXPLAIN_NAME = "SELECT_PARTIAL_ORDER_BY_DESC";
+
+  private int _numDocsScanned = 0;
+  private long _numEntriesScannedPostFilter = 0;
+
+  public SelectionPartiallyOrderedByDescOperation(IndexSegment indexSegment, QueryContext queryContext,
+      List<ExpressionContext> expressions, TransformOperator transformOperator, int sortedExpr) {
+    super(indexSegment, queryContext, expressions, transformOperator, sortedExpr);
+    assert queryContext.getOrderByExpressions() != null;
+    Preconditions.checkArgument(queryContext.getOrderByExpressions().stream()
+            .filter(expr -> expr.getExpression().getType() == ExpressionContext.Type.IDENTIFIER)
+            .findFirst()
+            .orElseThrow(() -> new IllegalArgumentException("The query is not order by identifiers"))
+            .isDesc(),
+        "%s can only be used when the first column in order by is DESC", EXPLAIN_NAME);
+  }
+
+  @Override
+  protected void fetch(ListBuilder listBuilder) {
+
+    List<TransformBlock> blocks = new ArrayList<>();
+
+    TransformBlock transformBlock;
+    int numColumnsProjected = _transformOperator.getNumColumnsProjected();
+    try {
+      while ((transformBlock = _transformOperator.nextBlock()) != null) {
+        int numDocsFetched = transformBlock.getNumDocs();
+        _numDocsScanned += numDocsFetched;
+        blocks.add(transformBlock);

Review Comment:
   That is sad. In that case it may not make sense to apply this optimization. Should we wait to have descending iterators/cursors?



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] Jackie-Jiang commented on a diff in pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
Jackie-Jiang commented on code in PR #8979:
URL: https://github.com/apache/pinot/pull/8979#discussion_r976047150


##########
pinot-core/src/main/java/org/apache/pinot/core/operator/blocks/results/SelectionResultsBlock.java:
##########
@@ -45,6 +56,18 @@ public Collection<Object[]> getRows() {
     return _rows;
   }
 
+  public PriorityQueue<Object[]> getRowsAsPriorityQueue() {

Review Comment:
   With the initial results block, we shouldn't need to use this API



##########
pinot-core/src/main/java/org/apache/pinot/core/operator/combine/BaseCombineOperator.java:
##########
@@ -162,7 +162,7 @@ protected void processSegments() {
         if (operator instanceof AcquireReleaseColumnsSegmentOperator) {
           ((AcquireReleaseColumnsSegmentOperator) operator).acquire();
         }
-        resultsBlock = (T) operator.nextBlock();
+        resultsBlock = createInitialResultBlock((T) operator.nextBlock());

Review Comment:
   We should not create initial result block here



##########
pinot-core/src/main/java/org/apache/pinot/core/operator/combine/MinMaxValueBasedSelectionOrderByCombineOperator.java:
##########
@@ -205,7 +205,7 @@ protected void processSegments() {
           ((AcquireReleaseColumnsSegmentOperator) operator).release();
         }
       }
-      PriorityQueue<Object[]> selectionResult = (PriorityQueue<Object[]>) resultsBlock.getRows();
+      PriorityQueue<Object[]> selectionResult = resultsBlock.getRowsAsPriorityQueue();

Review Comment:
   We should be able to directly get the boundary value from the list. Converting it to PQ will eliminate the performance gain of keeping list



##########
pinot-core/src/main/java/org/apache/pinot/core/operator/combine/BaseCombineOperator.java:
##########
@@ -250,6 +250,18 @@ protected boolean isQuerySatisfied(T resultsBlock) {
    */
   protected abstract void mergeResultsBlocks(T mergedBlock, T blockToMerge);
 
+  /**
+   * Converts the given generic IntermediateResultBlock into the specific type of IntermediateResultBlock that is
+   * supported by this combine operator.
+   *
+   * This operator may return the same object if the runtime type of the given block already matches which what it is
+   * expected.
+   *
+   * The returned object will usually be the one received as first argument of
+   * {@link #mergeResultsBlocks(BaseResultsBlock, BaseResultsBlock)}.
+   */
+  protected abstract T createInitialResultBlock(BaseResultsBlock block);

Review Comment:
   We can provide a default implementation. Also suggest renaming it to be more specific. We should be able to take T as the input
   ```suggestion
     protected T convertToMergableBlock(T resultsBlock) {
       return resultsBlock;
     }
   ```



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] gortiz commented on a diff in pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
gortiz commented on code in PR #8979:
URL: https://github.com/apache/pinot/pull/8979#discussion_r960764456


##########
pinot-core/src/main/java/org/apache/pinot/core/operator/query/SelectionPartiallyOrderedByDescOperation.java:
##########
@@ -0,0 +1,132 @@
+/**
+ * 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.pinot.core.operator.query;
+
+import com.google.common.base.Preconditions;
+import com.google.common.base.Supplier;
+import java.util.ArrayList;
+import java.util.List;
+import org.apache.pinot.common.request.context.ExpressionContext;
+import org.apache.pinot.core.common.BlockValSet;
+import org.apache.pinot.core.common.RowBasedBlockValueFetcher;
+import org.apache.pinot.core.operator.blocks.TransformBlock;
+import org.apache.pinot.core.operator.transform.TransformOperator;
+import org.apache.pinot.core.query.request.context.QueryContext;
+import org.apache.pinot.segment.spi.IndexSegment;
+
+
+/**
+ * An operator for order-by queries DESC that are partially sorted over the sorting keys.
+ *
+ * @see LinearSelectionOrderByOperator
+ */
+public class SelectionPartiallyOrderedByDescOperation extends LinearSelectionOrderByOperator {
+
+  private static final String EXPLAIN_NAME = "SELECT_PARTIAL_ORDER_BY_DESC";
+
+  private int _numDocsScanned = 0;
+  private long _numEntriesScannedPostFilter = 0;
+
+  public SelectionPartiallyOrderedByDescOperation(IndexSegment indexSegment, QueryContext queryContext,
+      List<ExpressionContext> expressions, TransformOperator transformOperator, int sortedExpr) {
+    super(indexSegment, queryContext, expressions, transformOperator, sortedExpr);
+    assert queryContext.getOrderByExpressions() != null;
+    Preconditions.checkArgument(queryContext.getOrderByExpressions().stream()
+            .filter(expr -> expr.getExpression().getType() == ExpressionContext.Type.IDENTIFIER)
+            .findFirst()
+            .orElseThrow(() -> new IllegalArgumentException("The query is not order by identifiers"))
+            .isDesc(),
+        "%s can only be used when the first column in order by is DESC", EXPLAIN_NAME);
+  }
+
+  @Override
+  protected List<Object[]> fetch(Supplier<ListBuilder> listBuilderSupplier) {
+
+    // Ideally we would use a descending cursor, but we don't actually have them
+    // Alternatively, we could store all blocks in a list and iterate them in reverse order, but ProjectionBlocks share
+    // the same DataBlockCache, so they may be ephemeral and being overridden by the next block.
+    // The only alternative we have right now is to retrieve the last LIMIT elements from each block
+
+    TransformBlock block;
+    int numColumnsProjected = _transformOperator.getNumColumnsProjected();
+    int numExpressions = _expressions.size();
+    BlockValSet[] blockValSets = new BlockValSet[numExpressions];
+
+    List<List<Object[]>> rowsPerBlock = new ArrayList<>();

Review Comment:
   This should be fixed in the current and future versions. Now what we do is to keep at most 2 `ListBuilder`s whose size is limited by the number of rows the segment must conserve. One of this structures starts empty and contains the best values calculated so far. 
   
   On the loop that iterates over the blocks in docId order, a new ListBuilder is created and populated with the best rows in the block. After that, still in the loop, the `localBest` elements are added to the new one and becomes the new best values we have. Not all elements in `localBest` have to be added. We can stop when a new partition is discovered and we reached the desired number of rows. Then this newly created ListBuilder substitutes the older `localBest`.
   
   This algorithm is easier to understand and it has a cost in memory close to `2 * max(L, min(B, P))` where B is the number of rows in the block, L is `_numRowsToKeep` and P is how many rows are in the larger partition. In the worse case scenario, where all elements are in the same partition and the limit is very large, the consumed memory is close to double the one used by the algorithm we were using before, but it is quite less CPU intensive (and produce less garbage).
   
   Please @Jackie-Jiang take a look in case I miss something else.



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] gortiz commented on a diff in pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
gortiz commented on code in PR #8979:
URL: https://github.com/apache/pinot/pull/8979#discussion_r951357408


##########
pinot-core/src/main/java/org/apache/pinot/core/operator/query/LinearSelectionOrderByOperator.java:
##########
@@ -0,0 +1,388 @@
+/**
+ * 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.pinot.core.operator.query;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+import javax.annotation.Nullable;
+import org.apache.pinot.common.request.context.ExpressionContext;
+import org.apache.pinot.common.request.context.OrderByExpressionContext;
+import org.apache.pinot.common.utils.DataSchema;
+import org.apache.pinot.core.common.BlockValSet;
+import org.apache.pinot.core.common.Operator;
+import org.apache.pinot.core.common.RowBasedBlockValueFetcher;
+import org.apache.pinot.core.operator.BaseOperator;
+import org.apache.pinot.core.operator.ExecutionStatistics;
+import org.apache.pinot.core.operator.blocks.IntermediateResultsBlock;
+import org.apache.pinot.core.operator.blocks.TransformBlock;
+import org.apache.pinot.core.operator.transform.TransformOperator;
+import org.apache.pinot.core.operator.transform.TransformResultMetadata;
+import org.apache.pinot.core.query.request.context.QueryContext;
+import org.apache.pinot.core.query.selection.SelectionOperatorUtils;
+import org.apache.pinot.segment.spi.IndexSegment;
+
+
+/**
+ * A selection Operator used when the first expressions in the order by are identifier expressions of columns that are
+ * already sorted (either ascendingly or descendingly), even if the tail of order by expressions are not sorted.
+ *
+ * ie: SELECT ... FROM Table WHERE predicates ORDER BY sorted_column DESC LIMIT 10 OFFSET 5
+ * or: SELECT ... FROM Table WHERE predicates ORDER BY sorted_column, not_sorted LIMIT 10 OFFSET 5
+ * but not SELECT ... FROM Table WHERE predicates ORDER BY not_sorted, sorted_column LIMIT 10 OFFSET 5
+ *
+ * Operators that derives from this class are going to have an almost linear cost instead of the usual NlogN when actual
+ * sorting must be done, where N is the number of rows in the segment.
+ * There is a degraded scenario when the cost is actually NlogL (where L is the limit of the query) when all the first L
+ * rows have the exact same value for the prefix of the sorted columns. Even in that case, L should be quite smaller
+ * than N, so this implementation is algorithmically better than the normal solution.
+ */
+public abstract class LinearSelectionOrderByOperator extends BaseOperator<IntermediateResultsBlock> {
+  protected final IndexSegment _indexSegment;
+
+  // Deduped order-by expressions followed by output expressions from SelectionOperatorUtils.extractExpressions()
+  protected final List<ExpressionContext> _expressions;
+  protected final List<ExpressionContext> _alreadySorted;
+  protected final List<ExpressionContext> _toSort;
+
+  protected final TransformOperator _transformOperator;
+  protected final List<OrderByExpressionContext> _orderByExpressions;
+  protected final TransformResultMetadata[] _expressionsMetadata;
+  protected final int _numRowsToKeep;
+  private final ListBuilder _listBuilder;
+  protected boolean _used = false;
+  protected Comparator<Object[]> _comparator;
+
+  /**
+   *
+   * @param expressions order by expressions must be at the head of the list.
+   * @param sortedExpr How many expressions at the head of the expression list are going to be considered sorted by
+   * {@link #fetch(ListBuilder)}
+   */
+  public LinearSelectionOrderByOperator(IndexSegment indexSegment, QueryContext queryContext,
+      List<ExpressionContext> expressions, TransformOperator transformOperator,
+      int sortedExpr) {
+    _indexSegment = indexSegment;
+    _expressions = expressions;
+    _transformOperator = transformOperator;
+
+    _orderByExpressions = queryContext.getOrderByExpressions();
+    assert _orderByExpressions != null;
+    int numOrderByExpressions = _orderByExpressions.size();
+
+    _alreadySorted = expressions.subList(0, sortedExpr);
+    _toSort = expressions.subList(sortedExpr, numOrderByExpressions);
+
+    _expressionsMetadata = new TransformResultMetadata[_expressions.size()];
+    for (int i = 0; i < _expressionsMetadata.length; i++) {
+      ExpressionContext expression = _expressions.get(i);
+      _expressionsMetadata[i] = _transformOperator.getResultMetadata(expression);
+    }
+
+    _numRowsToKeep = queryContext.getOffset() + queryContext.getLimit();
+
+    if (_toSort.isEmpty()) {
+      int expectedSize = Math.min(SelectionOperatorUtils.MAX_ROW_HOLDER_INITIAL_CAPACITY, _numRowsToKeep);
+      _listBuilder = new TotallySortedListBuilder(expectedSize);
+    } else {
+      int expectedSize = Math.min(SelectionOperatorUtils.MAX_ROW_HOLDER_INITIAL_CAPACITY, _numRowsToKeep * 2);
+
+      Comparator<Object[]> sortedComparator =
+          OrderByComparatorFactory.getComparator(_orderByExpressions, _expressionsMetadata, true, 0, sortedExpr);
+      Comparator<Object[]> unsortedComparator =
+          OrderByComparatorFactory.getComparator(_orderByExpressions, _expressionsMetadata, true, sortedExpr,
+              numOrderByExpressions);
+      _listBuilder = new PartiallySortedListBuilder(expectedSize, sortedComparator, unsortedComparator);
+    }
+
+    _comparator = OrderByComparatorFactory.getComparator(_orderByExpressions, _expressionsMetadata, false);
+  }
+
+  @Override
+  public IndexSegment getIndexSegment() {
+    return _indexSegment;
+  }
+
+  @Override
+  public ExecutionStatistics getExecutionStatistics() {
+    long numEntriesScannedInFilter = _transformOperator.getExecutionStatistics().getNumEntriesScannedInFilter();
+    int numTotalDocs = _indexSegment.getSegmentMetadata().getTotalDocs();
+    return new ExecutionStatistics(getNumDocsScanned(), numEntriesScannedInFilter, getNumEntriesScannedPostFilter(),
+        numTotalDocs);
+  }
+
+  protected RowBasedBlockValueFetcher fetchBlock(TransformBlock transformBlock, BlockValSet[] blockValSets) {
+    int numExpressions = _expressions.size();
+
+    for (int i = 0; i < numExpressions; i++) {
+      ExpressionContext expression = _expressions.get(i);
+      blockValSets[i] = transformBlock.getBlockValueSet(expression);
+    }
+    return new RowBasedBlockValueFetcher(blockValSets);
+  }
+
+  protected abstract long getNumEntriesScannedPostFilter();
+
+  protected abstract int getNumDocsScanned();
+
+  /**
+   * Modifies the given {@link ListBuilder} adding rows in an order compatible with the constructor used until the
+   * implementation considers that no more rows need to be added.
+   */
+  protected abstract void fetch(ListBuilder listBuilder);
+
+  @Override
+  public List<Operator> getChildOperators() {
+    return Collections.singletonList(_transformOperator);
+  }
+
+  protected abstract String getExplainName();
+
+  @Override
+  public String toExplainString() {
+    StringBuilder sb = new StringBuilder(getExplainName());
+
+    sb.append("(sortedList: ");
+    concatList(sb, _alreadySorted);
+
+    sb.append(", unsortedList: ");
+    concatList(sb, _toSort);
+
+    sb.append(", rest: ");
+    concatList(sb, _expressions.subList(_alreadySorted.size() + _toSort.size(), _expressions.size()));
+
+    sb.append(')');
+    return sb.toString();
+  }
+
+  private void concatList(StringBuilder sb, List<?> list) {
+    sb.append('(');
+    Iterator<?> it = list.iterator();
+    if (it.hasNext()) {
+      sb.append(it.next());
+      while (it.hasNext()) {
+        sb.append(", ").append(it.next());
+      }
+    }
+    sb.append(')');
+  }
+
+  @Override
+  protected IntermediateResultsBlock getNextBlock() {
+    Preconditions.checkState(!_used, "nextBlock was called more than once");
+    _used = true;
+    fetch(_listBuilder);
+
+    DataSchema dataSchema = createDataSchema();
+
+    List<Object[]> list = _listBuilder.build();
+    if (list.size() > _numRowsToKeep) {
+      list = new ArrayList<>(list.subList(0, _numRowsToKeep));
+    }
+
+    return new IntermediateResultsBlock.ListSelection(dataSchema, list, _comparator);
+  }
+
+  protected DataSchema createDataSchema() {
+    int numExpressions = _expressions.size();
+
+    // Create the data schema
+    String[] columnNames = new String[numExpressions];
+    DataSchema.ColumnDataType[] columnDataTypes = new DataSchema.ColumnDataType[numExpressions];
+    for (int i = 0; i < columnNames.length; i++) {
+      columnNames[i] = _expressions.get(i).toString();
+    }
+    for (int i = 0; i < numExpressions; i++) {
+      TransformResultMetadata expressionMetadata = _expressionsMetadata[i];
+      columnDataTypes[i] =
+          DataSchema.ColumnDataType.fromDataType(expressionMetadata.getDataType(), expressionMetadata.isSingleValue());
+    }
+    return new DataSchema(columnNames, columnDataTypes);
+  }
+
+  /**
+   * A private class used to build a sorted list by adding partially sorted data.
+   *
+   * Specifically, this class has been designed to receive successive calls to {@link #add(Object[])} follow by a single
+   * call to {@link #build()}. Once this method is called, the behavior of this object is undefined and therefore it
+   * should not be used.
+   *
+   * Rows must be inserted in ascending order accordingly to the partial order specified by a comparator.
+   * This comparator will define <i>partitions</i> of rows. All the rows in the same partition same are considered equal
+   * by that comparator.
+   *
+   * Some implementations, like {@link PartiallySortedListBuilder} accepts a second comparator that is used to sort rows
+   * inside each partition.
+   * When calling {@link #add(Object[])} with a row that doesn't belong to the current partition, a new one is started
+   * and the previous one is sorted. Therefore, this object maintains the invariant that at any moment there are at
+   * least {@link #sortedSize()} elements that are completely sorted, which means that no matter which elements are
+   * added after that, these elements are going to be smallest.
+   */
+  protected interface ListBuilder {
+
+    /**
+     * Adds the given row to this object. The new column must be equal or higher than the partition comparator.
+     *
+     * @param row The row to add. The values of the already sorted columns must be equal or higher than the last added
+     *           row, if any.
+     * @return true if and only if the previous partition was closed.
+     */
+    boolean add(Object[] row);
+
+    /**
+     * Builds the sorted list. The returned list will be sorted, even if a previous call t o {@link #sortedSize()}
+     * returned a number lower than the number of elements that have been added.
+     *
+     * Once this method is called, the builder should not be used. There is no guaranteed on whether
+     * {@link #sortedSize()} is updated or not.
+     */
+    List<Object[]> build();
+
+    /**
+     * How many elements are actually sorted. This number is lower or equal to the number of elements that has been
+     * added.
+     */
+    int sortedSize();
+  }
+
+  /**
+   * This is the faster {@link ListBuilder} but also the most restrictive one. It can only be used when data is inserted
+   * in total order. Therefore it cannot be used to implement order-by queries where there is at least one expression
+   * that is not sorted. In such case {@link PartiallySortedListBuilder} should be used.
+   *
+   * This implementation is just a wrapper over an ArrayList and therefore the average costs of its methods is constant.
+   */
+  protected static class TotallySortedListBuilder implements ListBuilder {
+    private final ArrayList<Object[]> _list;
+
+    public TotallySortedListBuilder(int expectedSize) {
+      _list = new ArrayList<>(expectedSize);
+    }
+
+    @Override
+    public boolean add(Object[] row) {
+      _list.add(row);
+      return true;
+    }
+
+    @Override
+    public List<Object[]> build() {
+      return _list;
+    }
+
+    @Override
+    public int sortedSize() {
+      return _list.size();
+    }
+  }
+
+  /**
+   * This is the more versatile {@link ListBuilder} that requires two comparators: The first defines the order on which
+   * {@link #add(Object[])} is called and defines the partitions. The second one is used to sort rows in the same
+   * paritition. This class can be used to implement order-by queries that include one or more not sorted expressions.
+   * In cases where all expressions are sorted, {@link TotallySortedListBuilder} should be used because its performance
+   * is better.
+   *
+   * In this implementation the {@link #add(Object[])} method has a log(P) cost, where P is the number of elements in
+   * each partition. In normal cases we can consider P a constant. In some degenerated cases like having an ordering by
+   * a sorted column whose values are all equal, P may tend to the number of elements in the segment, which would make
+   * the cost of this method log(N).
+   */
+  private static class PartiallySortedListBuilder implements ListBuilder {
+    private final ArrayList<Object[]> _rows;
+    /**
+     * The comparator that defines the partitions and the one that impose in which order add has to be called.
+     */
+    private final Comparator<Object[]> _partitionComparator;
+    /**
+     * The comparator that sorts different rows on each partition.
+     */
+    private final Comparator<Object[]> _unsortedComparator;
+    @Nullable
+    private Object[] _lastPartitionRow;
+    /**
+     * The index where the current (and still not sorted) partition starts.
+     */
+    private int _lastSorted;
+
+    public PartiallySortedListBuilder(int expectedSize, Comparator<Object[]> partitionComparator,
+        Comparator<Object[]> unsortedComparator) {
+      _rows = new ArrayList<>(expectedSize);
+      _partitionComparator = partitionComparator;
+      _unsortedComparator = unsortedComparator;
+    }
+
+    @Override
+    public boolean add(Object[] row) {
+      boolean result;
+      if (_lastPartitionRow == null) {
+        _lastSorted = 0;
+        _lastPartitionRow = row;
+        result = false;
+      } else {
+        int cmp = _partitionComparator.compare(row, _lastPartitionRow);
+        if (cmp < 0) {
+          throw new IllegalArgumentException("Row " + Arrays.toString(row) + " is lower than previously added row"
+              + Arrays.toString(_lastPartitionRow));
+        }
+        if (cmp > 0) {

Review Comment:
   I've created a new version that in case more than <maxElements> are found, the last partition is stored in a PriorityQueue



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] gortiz commented on a diff in pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
gortiz commented on code in PR #8979:
URL: https://github.com/apache/pinot/pull/8979#discussion_r951356880


##########
pinot-core/src/main/java/org/apache/pinot/core/operator/query/SelectionPartiallyOrderedByDescOperation.java:
##########
@@ -0,0 +1,105 @@
+/**
+ * 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.pinot.core.operator.query;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.List;
+import org.apache.pinot.common.request.context.ExpressionContext;
+import org.apache.pinot.core.common.BlockValSet;
+import org.apache.pinot.core.common.RowBasedBlockValueFetcher;
+import org.apache.pinot.core.operator.blocks.TransformBlock;
+import org.apache.pinot.core.operator.transform.TransformOperator;
+import org.apache.pinot.core.query.request.context.QueryContext;
+import org.apache.pinot.segment.spi.IndexSegment;
+
+
+/**
+ * An operator for order-by queries DESC that are partially sorted over the sorting keys.
+ *
+ * @see LinearSelectionOrderByOperator
+ */
+public class SelectionPartiallyOrderedByDescOperation extends LinearSelectionOrderByOperator {
+
+  private static final String EXPLAIN_NAME = "SELECT_PARTIAL_ORDER_BY_DESC";
+
+  private int _numDocsScanned = 0;
+  private long _numEntriesScannedPostFilter = 0;
+
+  public SelectionPartiallyOrderedByDescOperation(IndexSegment indexSegment, QueryContext queryContext,
+      List<ExpressionContext> expressions, TransformOperator transformOperator, int sortedExpr) {
+    super(indexSegment, queryContext, expressions, transformOperator, sortedExpr);
+    assert queryContext.getOrderByExpressions() != null;
+    Preconditions.checkArgument(queryContext.getOrderByExpressions().stream()
+            .filter(expr -> expr.getExpression().getType() == ExpressionContext.Type.IDENTIFIER)
+            .findFirst()
+            .orElseThrow(() -> new IllegalArgumentException("The query is not order by identifiers"))
+            .isDesc(),
+        "%s can only be used when the first column in order by is DESC", EXPLAIN_NAME);
+  }
+
+  @Override
+  protected void fetch(ListBuilder listBuilder) {
+
+    List<TransformBlock> blocks = new ArrayList<>();
+
+    TransformBlock transformBlock;
+    int numColumnsProjected = _transformOperator.getNumColumnsProjected();
+    try {
+      while ((transformBlock = _transformOperator.nextBlock()) != null) {
+        int numDocsFetched = transformBlock.getNumDocs();
+        _numDocsScanned += numDocsFetched;
+        blocks.add(transformBlock);

Review Comment:
   I've just changed the code so it fetchs the last <limit> rows of each block.



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] gortiz commented on a diff in pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
gortiz commented on code in PR #8979:
URL: https://github.com/apache/pinot/pull/8979#discussion_r978533200


##########
pinot-core/src/main/java/org/apache/pinot/core/operator/combine/MinMaxValueBasedSelectionOrderByCombineOperator.java:
##########
@@ -205,7 +205,7 @@ protected void processSegments() {
           ((AcquireReleaseColumnsSegmentOperator) operator).release();
         }
       }
-      PriorityQueue<Object[]> selectionResult = (PriorityQueue<Object[]>) resultsBlock.getRows();
+      PriorityQueue<Object[]> selectionResult = resultsBlock.getRowsAsPriorityQueue();

Review Comment:
   I've uploaded a new version that retrieves the boundary in different ways depending on the data structure used in rows.



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] gortiz commented on a diff in pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
gortiz commented on code in PR #8979:
URL: https://github.com/apache/pinot/pull/8979#discussion_r980796867


##########
pinot-core/src/main/java/org/apache/pinot/core/operator/query/LinearSelectionOrderByOperator.java:
##########
@@ -0,0 +1,476 @@
+/**
+ * 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.pinot.core.operator.query;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+import java.util.PriorityQueue;
+import java.util.function.IntFunction;
+import java.util.function.Supplier;
+import javax.annotation.Nullable;
+import org.apache.pinot.common.request.context.ExpressionContext;
+import org.apache.pinot.common.request.context.OrderByExpressionContext;
+import org.apache.pinot.common.utils.DataSchema;
+import org.apache.pinot.core.common.BlockValSet;
+import org.apache.pinot.core.common.Operator;
+import org.apache.pinot.core.common.RowBasedBlockValueFetcher;
+import org.apache.pinot.core.operator.BaseOperator;
+import org.apache.pinot.core.operator.ExecutionStatistics;
+import org.apache.pinot.core.operator.blocks.TransformBlock;
+import org.apache.pinot.core.operator.blocks.results.SelectionResultsBlock;
+import org.apache.pinot.core.operator.transform.TransformOperator;
+import org.apache.pinot.core.operator.transform.TransformResultMetadata;
+import org.apache.pinot.core.query.request.context.QueryContext;
+import org.apache.pinot.core.query.selection.SelectionOperatorUtils;
+import org.apache.pinot.segment.spi.IndexSegment;
+import org.roaringbitmap.RoaringBitmap;
+
+
+/**
+ * A selection Operator used when the first expressions in the order by are identifier expressions of columns that are
+ * already sorted (either ascendingly or descendingly), even if the tail of order by expressions are not sorted.
+ *
+ * ie: SELECT ... FROM Table WHERE predicates ORDER BY sorted_column DESC LIMIT 10 OFFSET 5
+ * or: SELECT ... FROM Table WHERE predicates ORDER BY sorted_column, not_sorted LIMIT 10 OFFSET 5
+ * but not SELECT ... FROM Table WHERE predicates ORDER BY not_sorted, sorted_column LIMIT 10 OFFSET 5
+ *
+ * Operators that derives from this class are going to have an almost linear cost instead of the usual NlogN when actual
+ * sorting must be done, where N is the number of rows in the segment.
+ * There is a degraded scenario when the cost is actually NlogL (where L is the limit of the query) when all the first L
+ * rows have the exact same value for the prefix of the sorted columns. Even in that case, L should be quite smaller
+ * than N, so this implementation is algorithmically better than the normal solution.
+ */
+public abstract class LinearSelectionOrderByOperator extends BaseOperator<SelectionResultsBlock> {
+  protected final IndexSegment _indexSegment;
+
+  protected final boolean _nullHandlingEnabled;
+  // Deduped order-by expressions followed by output expressions from SelectionOperatorUtils.extractExpressions()
+  protected final List<ExpressionContext> _expressions;
+  protected final List<ExpressionContext> _alreadySorted;
+  protected final List<ExpressionContext> _toSort;
+
+  protected final TransformOperator _transformOperator;
+  protected final List<OrderByExpressionContext> _orderByExpressions;
+  protected final TransformResultMetadata[] _expressionsMetadata;
+  protected final int _numRowsToKeep;
+  private final Supplier<ListBuilder> _listBuilderSupplier;
+  protected boolean _used = false;
+  protected Comparator<Object[]> _comparator;
+
+  /**
+   *
+   * @param expressions order by expressions must be at the head of the list.
+   * @param sortedExpr How many expressions at the head of the expression list are going to be considered sorted by
+   * {@link #fetch(Supplier<ListBuilder>)}
+   */
+  public LinearSelectionOrderByOperator(IndexSegment indexSegment, QueryContext queryContext,
+      List<ExpressionContext> expressions, TransformOperator transformOperator,
+      int sortedExpr) {
+    _indexSegment = indexSegment;
+    _nullHandlingEnabled = queryContext.isNullHandlingEnabled();
+    _expressions = expressions;
+    _transformOperator = transformOperator;
+
+    _orderByExpressions = queryContext.getOrderByExpressions();
+    assert _orderByExpressions != null;
+    int numOrderByExpressions = _orderByExpressions.size();
+
+    _alreadySorted = expressions.subList(0, sortedExpr);
+    _toSort = expressions.subList(sortedExpr, numOrderByExpressions);
+
+    _expressionsMetadata = new TransformResultMetadata[_expressions.size()];
+    for (int i = 0; i < _expressionsMetadata.length; i++) {
+      ExpressionContext expression = _expressions.get(i);
+      _expressionsMetadata[i] = _transformOperator.getResultMetadata(expression);
+    }
+
+    _numRowsToKeep = queryContext.getOffset() + queryContext.getLimit();
+
+    if (_toSort.isEmpty()) {
+      int expectedSize = Math.min(SelectionOperatorUtils.MAX_ROW_HOLDER_INITIAL_CAPACITY, _numRowsToKeep);
+      _listBuilderSupplier = () -> new TotallySortedListBuilder(expectedSize);
+    } else {
+      int maxSize = Math.min(SelectionOperatorUtils.MAX_ROW_HOLDER_INITIAL_CAPACITY, _numRowsToKeep * 2);
+
+      Comparator<Object[]> sortedComparator = OrderByComparatorFactory.getComparator(_orderByExpressions,
+          _expressionsMetadata, true, _nullHandlingEnabled, 0, sortedExpr);
+      Comparator<Object[]> unsortedComparator = OrderByComparatorFactory.getComparator(_orderByExpressions,
+          _expressionsMetadata, true, _nullHandlingEnabled, sortedExpr, numOrderByExpressions);
+      _listBuilderSupplier = () -> new PartiallySortedListBuilder(maxSize, sortedComparator, unsortedComparator);
+    }
+
+    _comparator =
+        OrderByComparatorFactory.getComparator(_orderByExpressions, _expressionsMetadata, false, _nullHandlingEnabled);
+  }
+
+  @Override
+  public IndexSegment getIndexSegment() {
+    return _indexSegment;
+  }
+
+  @Override
+  public ExecutionStatistics getExecutionStatistics() {
+    long numEntriesScannedInFilter = _transformOperator.getExecutionStatistics().getNumEntriesScannedInFilter();
+    int numTotalDocs = _indexSegment.getSegmentMetadata().getTotalDocs();
+    return new ExecutionStatistics(getNumDocsScanned(), numEntriesScannedInFilter, getNumEntriesScannedPostFilter(),
+        numTotalDocs);
+  }
+
+  protected IntFunction<Object[]> fetchBlock(TransformBlock transformBlock, BlockValSet[] blockValSets) {
+    int numExpressions = _expressions.size();
+
+    for (int i = 0; i < numExpressions; i++) {
+      ExpressionContext expression = _expressions.get(i);
+      blockValSets[i] = transformBlock.getBlockValueSet(expression);
+    }
+    RowBasedBlockValueFetcher blockValueFetcher = new RowBasedBlockValueFetcher(blockValSets);
+
+    if (!_nullHandlingEnabled) {
+      return blockValueFetcher::getRow;
+    }
+    RoaringBitmap[] nullBitmaps = new RoaringBitmap[numExpressions];
+    for (int i = 0; i < numExpressions; i++) {
+      nullBitmaps[i] = blockValSets[i].getNullBitmap();
+    }
+    return (docId) -> {
+      Object[] row = blockValueFetcher.getRow(docId);
+      for (int colId = 0; colId < nullBitmaps.length; colId++) {
+        if (nullBitmaps[colId] != null && nullBitmaps[colId].contains(docId)) {
+          row[colId] = null;
+        }
+      }
+      return row;
+    };
+  }
+
+  protected abstract long getNumEntriesScannedPostFilter();
+
+  protected abstract int getNumDocsScanned();
+
+  /**
+   * Returns a list of rows sorted that:
+   * <ul>
+   *   <li>At least contains all the rows that fulfill the predicate</li>
+   *   <li>Rows are sorted in a way that is compatible with the given list builder supplier</li>
+   * </ul>
+   *
+   * That means that the result may contain more rows than required.
+   *
+   * @param listBuilderSupplier a {@link ListBuilder} supplier that should be used to create the result. Each time is
+   *                            called a new {@link ListBuilder} will be returned. All returned instances use the same
+   *                            comparator logic.
+   */
+  protected abstract List<Object[]> fetch(Supplier<ListBuilder> listBuilderSupplier);
+
+  @Override
+  public List<Operator> getChildOperators() {
+    return Collections.singletonList(_transformOperator);
+  }
+
+  protected abstract String getExplainName();
+
+  @Override
+  public String toExplainString() {
+    StringBuilder sb = new StringBuilder(getExplainName());
+
+    sb.append("(sortedList: ");
+    concatList(sb, _alreadySorted);
+
+    sb.append(", unsortedList: ");
+    concatList(sb, _toSort);
+
+    sb.append(", rest: ");
+    concatList(sb, _expressions.subList(_alreadySorted.size() + _toSort.size(), _expressions.size()));
+
+    sb.append(')');
+    return sb.toString();
+  }
+
+  private void concatList(StringBuilder sb, List<?> list) {
+    sb.append('(');
+    Iterator<?> it = list.iterator();
+    if (it.hasNext()) {
+      sb.append(it.next());
+      while (it.hasNext()) {
+        sb.append(", ").append(it.next());
+      }
+    }
+    sb.append(')');
+  }
+
+  @Override
+  protected SelectionResultsBlock getNextBlock() {
+    Preconditions.checkState(!_used, "nextBlock was called more than once");
+    _used = true;
+    List<Object[]> list = fetch(_listBuilderSupplier);
+
+    DataSchema dataSchema = createDataSchema();
+
+    if (list.size() > _numRowsToKeep) {
+      list = new ArrayList<>(list.subList(0, _numRowsToKeep));
+    }
+
+    SelectionResultsBlock resultsBlock = new SelectionResultsBlock(dataSchema, list, _comparator);
+
+    return resultsBlock;
+  }
+
+  protected DataSchema createDataSchema() {
+    int numExpressions = _expressions.size();
+
+    // Create the data schema
+    String[] columnNames = new String[numExpressions];
+    DataSchema.ColumnDataType[] columnDataTypes = new DataSchema.ColumnDataType[numExpressions];
+    for (int i = 0; i < columnNames.length; i++) {
+      columnNames[i] = _expressions.get(i).toString();
+    }
+    for (int i = 0; i < numExpressions; i++) {
+      TransformResultMetadata expressionMetadata = _expressionsMetadata[i];
+      columnDataTypes[i] =
+          DataSchema.ColumnDataType.fromDataType(expressionMetadata.getDataType(), expressionMetadata.isSingleValue());
+    }
+    return new DataSchema(columnNames, columnDataTypes);
+  }
+
+  /**
+   * A private class used to build a sorted list by adding partially sorted data.
+   *
+   * Specifically, this class has been designed to receive successive calls to {@link #add(Object[])} follow by a single
+   * call to {@link #build()}. Once this method is called, the behavior of this object is undefined and therefore it
+   * should not be used.
+   *
+   * Rows must be inserted in ascending order accordingly to the partial order specified by a comparator.
+   * This comparator will define <i>partitions</i> of rows. All the rows in the same partition same are considered equal
+   * by that comparator.
+   *
+   * Some implementations, like {@link PartiallySortedListBuilder} accepts a second comparator that is used to sort rows
+   * inside each partition.
+   * When calling {@link #add(Object[])} with a row that doesn't belong to the current partition, a new one is started
+   * and the previous one is sorted. Therefore, this object maintains the invariant that at any moment there are at
+   * least {@link #sortedSize()} elements that are completely sorted, which means that no matter which elements are
+   * added after that, these elements are going to be smallest.
+   */
+  protected interface ListBuilder {
+
+    /**
+     * Adds the given row to this object. The new column must be equal or higher than the partition comparator.
+     *
+     * @param row The row to add. The values of the already sorted columns must be equal or higher than the last added
+     *           row, if any.
+     * @return true if and only if the previous partition was closed.
+     */
+    boolean add(Object[] row);
+
+    /**
+     * Builds the sorted list. The returned list will be sorted, even if a previous call t o {@link #sortedSize()}
+     * returned a number lower than the number of elements that have been added.
+     *
+     * Once this method is called, the builder should not be used. There is no guaranteed on whether
+     * {@link #sortedSize()} is updated or not.
+     */
+    List<Object[]> build();
+
+    /**
+     * How many elements are actually sorted. This number is lower or equal to the number of elements that has been
+     * added.
+     */
+    int sortedSize();
+  }
+
+  /**
+   * This is the faster {@link ListBuilder} but also the most restrictive one. It can only be used when data is inserted
+   * in total order. Therefore it cannot be used to implement order-by queries where there is at least one expression
+   * that is not sorted. In such case {@link PartiallySortedListBuilder} should be used.
+   *
+   * This implementation is just a wrapper over an ArrayList and therefore the average costs of its methods is constant.
+   */
+  protected static class TotallySortedListBuilder implements ListBuilder {
+    private final ArrayList<Object[]> _list;
+
+    public TotallySortedListBuilder(int expectedSize) {
+      _list = new ArrayList<>(expectedSize);
+    }
+
+    @Override
+    public boolean add(Object[] row) {
+      _list.add(row);
+      return true;
+    }
+
+    @Override
+    public List<Object[]> build() {
+      return _list;
+    }
+
+    @Override
+    public int sortedSize() {
+      return _list.size();
+    }
+  }
+
+  /**
+   * This is the more versatile {@link ListBuilder} that requires two comparators: The first defines the order on which
+   * {@link #add(Object[])} is called and defines the partitions. The second one is used to sort rows in the same
+   * partition. This class can be used to implement order-by queries that include one or more not sorted expressions.
+   * In cases where all expressions are sorted, {@link TotallySortedListBuilder} should be used because its performance
+   * is better.
+   *
+   * In this implementation the {@link #add(Object[])} method has a log(P) cost, where P is the number of elements in
+   * each partition. In normal cases we can consider P a constant. In some degenerated cases like having an ordering by
+   * a sorted column whose values are all equal, P may tend to the number of elements in the segment, which would make
+   * the cost of this method log(N).
+   *
+   * This class is optimized for scenarios where the partitions are smaller than the limit. In that case, the partition
+   * is only sorted once it is closed (aka when a new element for the other partition is found), so each insertion has
+   * an average cost of log(P) (where P-1 insertions are cost O(1) and the last one is O(PlogP)). In cases where at
+   * least one partition is larger than the limit, this implementation delegates the last partition to a
+   * {@link PriorityQueue}.
+   */
+  private static class PartiallySortedListBuilder implements ListBuilder {
+    private final ArrayList<Object[]> _rows;
+    /**
+     * The comparator that defines the partitions and the one that impose in which order add has to be called.
+     */
+    private final Comparator<Object[]> _partitionComparator;
+    /**
+     * The comparator that sorts different rows on each partition.
+     */
+    private final Comparator<Object[]> _unsortedComparator;
+    @Nullable
+    private Object[] _lastPartitionRow;
+    /**
+     * How many elements are already sorted. This is also the index where the last (and still not sorted) partition
+     * starts or should start.
+     */
+    private int _sortedPrefixSize;
+    private final int _maxSize;
+    private PriorityQueue<Object[]> _queue = null;
+    private int _maxPriorityQueueValues;
+
+    public PartiallySortedListBuilder(int maxSize, Comparator<Object[]> partitionComparator,
+        Comparator<Object[]> unsortedComparator) {
+      Preconditions.checkArgument(maxSize > 0, "Max size must be greater than 0");
+      _maxSize = maxSize;
+      _rows = new ArrayList<>(maxSize);
+      _partitionComparator = partitionComparator;
+      _unsortedComparator = unsortedComparator;
+    }
+
+    @Override
+    public boolean add(Object[] row) {
+      boolean result;
+      if (_lastPartitionRow == null) {
+        _sortedPrefixSize = 0;
+        _lastPartitionRow = row;
+        _rows.add(row);
+        return false;
+      } else {
+        int cmp = _partitionComparator.compare(row, _lastPartitionRow);
+        if (cmp < 0) {
+          throw new IllegalArgumentException("Row " + Arrays.toString(row) + " is lower than previously added row"
+              + Arrays.toString(_lastPartitionRow));
+        }
+
+        if (_queue != null) {
+          if (cmp > 0) {
+            // the new row is in a greater partition, just don't add it and continue
+            return true;
+          }
+          // otherwise they are equal by the already sorted columns. Let's check the other columns and evict the higher
+          // also, we have the higher value at the last position
+          SelectionOperatorUtils.addToPriorityQueue(row, _queue, _maxPriorityQueueValues);
+          return false;
+        } else {
+          if (_rows.size() == _maxSize) { // we already have _maxSize results
+            if (cmp > 0) {
+              // and the new one is higher, so we don't need to add it
+              sortLastPartition();
+              return true;
+            }
+            // and the new one may be smaller, so this is going to be the last partition and we need to prepare the
+            // priority queue
+            buildPriorityQueue();
+            SelectionOperatorUtils.addToPriorityQueue(row, _queue, _maxPriorityQueueValues);
+            return false;
+          }
+          if (cmp > 0) {
+            sortLastPartition();
+            _lastPartitionRow = row;
+            result = true;
+          } else {
+            result = false;
+          }
+          _rows.add(row);
+          return result;
+        }
+      }
+    }
+
+    private void buildPriorityQueue() {
+      _maxPriorityQueueValues = _maxSize - _sortedPrefixSize;
+      _queue = new PriorityQueue<>(_maxPriorityQueueValues, _unsortedComparator.reversed());
+      for (int i = 0; i < _maxPriorityQueueValues; i++) {
+        int lastIdx = _rows.size() - 1;
+        _queue.add(_rows.get(lastIdx));
+        _rows.remove(lastIdx);
+      }
+    }
+
+    void sortLastPartition() {

Review Comment:
   We do need to sort to fulfill the contract of the interface we implement. It may be true that in the specific case where we are using this class right now it may not be necessary but we cannot break the contract of an interface we use. Given that this is a new interface, we could its semantics, but I think that is not a good idea. It would make the semantics very unclear.
   
   The cost of sorting the last part is negligible when compared with the improvements of this PR and the problems that may be associated with a very complex interface semantic



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] gortiz commented on a diff in pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
gortiz commented on code in PR #8979:
URL: https://github.com/apache/pinot/pull/8979#discussion_r979744101


##########
pinot-core/src/main/java/org/apache/pinot/core/operator/blocks/results/SelectionResultsBlock.java:
##########
@@ -45,6 +56,26 @@ public Collection<Object[]> getRows() {
     return _rows;
   }
 
+  public SelectionResultsBlock cloneWithInnerPriorityQueue() {
+    if (_rows instanceof PriorityQueue) {
+      return new SelectionResultsBlock(_dataSchema, new PriorityQueue<>(_rows));

Review Comment:
   I will involve extra overhead, but it won't be that hard. `PriorityQueue(Collection)` is linear when the argument is another Priority queue. In fact it is a call to Arrays.copy(), which is very fast.
   
   And that cost comes with a legibility advantage: `SelectionResultsBlock` now treats blocks generated by children operators as they were immutable.



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] gortiz commented on a diff in pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
gortiz commented on code in PR #8979:
URL: https://github.com/apache/pinot/pull/8979#discussion_r1000205202


##########
pinot-core/src/main/java/org/apache/pinot/core/operator/query/LinearSelectionOrderByOperator.java:
##########
@@ -0,0 +1,452 @@
+/**
+ * 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.pinot.core.operator.query;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+import java.util.PriorityQueue;
+import java.util.function.IntFunction;
+import java.util.function.Supplier;
+import javax.annotation.Nullable;
+import org.apache.pinot.common.request.context.ExpressionContext;
+import org.apache.pinot.common.request.context.OrderByExpressionContext;
+import org.apache.pinot.common.utils.DataSchema;
+import org.apache.pinot.core.common.BlockValSet;
+import org.apache.pinot.core.common.Operator;
+import org.apache.pinot.core.common.RowBasedBlockValueFetcher;
+import org.apache.pinot.core.operator.BaseOperator;
+import org.apache.pinot.core.operator.ExecutionStatistics;
+import org.apache.pinot.core.operator.blocks.TransformBlock;
+import org.apache.pinot.core.operator.blocks.results.SelectionResultsBlock;
+import org.apache.pinot.core.operator.transform.TransformOperator;
+import org.apache.pinot.core.operator.transform.TransformResultMetadata;
+import org.apache.pinot.core.query.request.context.QueryContext;
+import org.apache.pinot.core.query.selection.SelectionOperatorUtils;
+import org.apache.pinot.core.query.utils.OrderByComparatorFactory;
+import org.apache.pinot.segment.spi.IndexSegment;
+import org.roaringbitmap.RoaringBitmap;
+
+
+/**
+ * A selection Operator used when the first expressions in the order by are identifier expressions of columns that are
+ * already sorted (either ascendingly or descendingly), even if the tail of order by expressions are not sorted.
+ *
+ * ie: SELECT ... FROM Table WHERE predicates ORDER BY sorted_column DESC LIMIT 10 OFFSET 5
+ * or: SELECT ... FROM Table WHERE predicates ORDER BY sorted_column, not_sorted LIMIT 10 OFFSET 5
+ * but not SELECT ... FROM Table WHERE predicates ORDER BY not_sorted, sorted_column LIMIT 10 OFFSET 5
+ *
+ * Operators that derives from this class are going to have an almost linear cost instead of the usual NlogN when actual
+ * sorting must be done, where N is the number of rows in the segment.
+ * There is a degraded scenario when the cost is actually NlogL (where L is the limit of the query) when all the first L
+ * rows have the exact same value for the prefix of the sorted columns. Even in that case, L should be quite smaller
+ * than N, so this implementation is algorithmically better than the normal solution.
+ */
+public abstract class LinearSelectionOrderByOperator extends BaseOperator<SelectionResultsBlock> {
+  protected final IndexSegment _indexSegment;
+
+  protected final boolean _nullHandlingEnabled;
+  // Deduped order-by expressions followed by output expressions from SelectionOperatorUtils.extractExpressions()
+  protected final List<ExpressionContext> _expressions;
+  protected final List<ExpressionContext> _alreadySorted;
+  protected final List<ExpressionContext> _toSort;
+
+  protected final TransformOperator _transformOperator;
+  protected final List<OrderByExpressionContext> _orderByExpressions;
+  protected final TransformResultMetadata[] _expressionsMetadata;
+  protected final int _numRowsToKeep;
+  private final Supplier<ListBuilder> _listBuilderSupplier;
+  protected boolean _used = false;
+  /**
+   * The comparator used to build the resulting {@link SelectionResultsBlock}, which sorts rows in reverse order to the
+   * one specified in the query.
+   */
+  protected Comparator<Object[]> _comparator;
+
+  /**
+   *
+   * @param expressions order by expressions must be at the head of the list.
+   * @param sortedExpr How many expressions at the head of the expression list are going to be considered sorted by
+   * {@link #fetch(Supplier<ListBuilder>)}
+   */
+  public LinearSelectionOrderByOperator(IndexSegment indexSegment, QueryContext queryContext,
+      List<ExpressionContext> expressions, TransformOperator transformOperator,
+      int sortedExpr) {
+    _indexSegment = indexSegment;
+    _nullHandlingEnabled = queryContext.isNullHandlingEnabled();
+    _expressions = expressions;
+    _transformOperator = transformOperator;
+
+    _orderByExpressions = queryContext.getOrderByExpressions();
+    assert _orderByExpressions != null;
+    int numOrderByExpressions = _orderByExpressions.size();
+
+    _alreadySorted = expressions.subList(0, sortedExpr);
+    _toSort = expressions.subList(sortedExpr, numOrderByExpressions);
+
+    _expressionsMetadata = new TransformResultMetadata[_expressions.size()];
+    for (int i = 0; i < _expressionsMetadata.length; i++) {
+      ExpressionContext expression = _expressions.get(i);
+      _expressionsMetadata[i] = _transformOperator.getResultMetadata(expression);
+    }
+
+    _numRowsToKeep = queryContext.getOffset() + queryContext.getLimit();
+
+    if (_toSort.isEmpty()) {
+      int expectedSize = Math.min(SelectionOperatorUtils.MAX_ROW_HOLDER_INITIAL_CAPACITY, _numRowsToKeep);
+      _listBuilderSupplier = () -> new TotallySortedListBuilder(expectedSize);
+    } else {
+      int maxSize = Math.min(SelectionOperatorUtils.MAX_ROW_HOLDER_INITIAL_CAPACITY, _numRowsToKeep * 2);

Review Comment:
   We don't actually needed it, but previous implementations used that list to add unsorted elements, so it was useful to increase the size a little bit to avoid resizings.



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] Jackie-Jiang commented on pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
Jackie-Jiang commented on PR #8979:
URL: https://github.com/apache/pinot/pull/8979#issuecomment-1201838643

   For the `assert` statement, personally I usually use it for documentation purpose to indicate that a condition should always be met based on the calling tree (e.g. a condition is already checked before calling a method), especially in performance critical path. If a condition might not be met when the input is illegal, we can use `Preconditions` instead.
   
   For the descending order case, the final solution should be using the reverse iterator. I'd suggest modifying the current PR to optimize ascending order only, and then open a separate PR to add the reverse iterator and optimize the descending order case.


-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] gortiz commented on a diff in pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
gortiz commented on code in PR #8979:
URL: https://github.com/apache/pinot/pull/8979#discussion_r959208614


##########
pinot-core/src/main/java/org/apache/pinot/core/operator/query/SelectionPartiallyOrderedByDescOperation.java:
##########
@@ -0,0 +1,132 @@
+/**
+ * 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.pinot.core.operator.query;
+
+import com.google.common.base.Preconditions;
+import com.google.common.base.Supplier;
+import java.util.ArrayList;
+import java.util.List;
+import org.apache.pinot.common.request.context.ExpressionContext;
+import org.apache.pinot.core.common.BlockValSet;
+import org.apache.pinot.core.common.RowBasedBlockValueFetcher;
+import org.apache.pinot.core.operator.blocks.TransformBlock;
+import org.apache.pinot.core.operator.transform.TransformOperator;
+import org.apache.pinot.core.query.request.context.QueryContext;
+import org.apache.pinot.segment.spi.IndexSegment;
+
+
+/**
+ * An operator for order-by queries DESC that are partially sorted over the sorting keys.
+ *
+ * @see LinearSelectionOrderByOperator
+ */
+public class SelectionPartiallyOrderedByDescOperation extends LinearSelectionOrderByOperator {
+
+  private static final String EXPLAIN_NAME = "SELECT_PARTIAL_ORDER_BY_DESC";
+
+  private int _numDocsScanned = 0;
+  private long _numEntriesScannedPostFilter = 0;
+
+  public SelectionPartiallyOrderedByDescOperation(IndexSegment indexSegment, QueryContext queryContext,
+      List<ExpressionContext> expressions, TransformOperator transformOperator, int sortedExpr) {
+    super(indexSegment, queryContext, expressions, transformOperator, sortedExpr);
+    assert queryContext.getOrderByExpressions() != null;
+    Preconditions.checkArgument(queryContext.getOrderByExpressions().stream()
+            .filter(expr -> expr.getExpression().getType() == ExpressionContext.Type.IDENTIFIER)
+            .findFirst()
+            .orElseThrow(() -> new IllegalArgumentException("The query is not order by identifiers"))
+            .isDesc(),
+        "%s can only be used when the first column in order by is DESC", EXPLAIN_NAME);
+  }
+
+  @Override
+  protected List<Object[]> fetch(Supplier<ListBuilder> listBuilderSupplier) {
+
+    // Ideally we would use a descending cursor, but we don't actually have them
+    // Alternatively, we could store all blocks in a list and iterate them in reverse order, but ProjectionBlocks share
+    // the same DataBlockCache, so they may be ephemeral and being overridden by the next block.
+    // The only alternative we have right now is to retrieve the last LIMIT elements from each block
+
+    TransformBlock block;
+    int numColumnsProjected = _transformOperator.getNumColumnsProjected();
+    int numExpressions = _expressions.size();
+    BlockValSet[] blockValSets = new BlockValSet[numExpressions];
+
+    List<List<Object[]>> rowsPerBlock = new ArrayList<>();

Review Comment:
   Also, reading the code now, it seems to me that the solution is incorrect. If elements at the end of one block have the same sorted columns than the elements at the beginning of the next they are in the same partition, but they are never sorted by their unsorted columns



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] gortiz commented on a diff in pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
gortiz commented on code in PR #8979:
URL: https://github.com/apache/pinot/pull/8979#discussion_r959230201


##########
pinot-core/src/main/java/org/apache/pinot/core/plan/SelectionPlanNode.java:
##########
@@ -50,67 +52,113 @@ public Operator<IntermediateResultsBlock> run() {
     List<ExpressionContext> expressions = SelectionOperatorUtils.extractExpressions(_queryContext, _indexSegment);
     int limit = _queryContext.getLimit();
 
-    if (limit > 0) {
-      List<OrderByExpressionContext> orderByExpressions = _queryContext.getOrderByExpressions();
-      if (orderByExpressions == null) {
-        // Selection only
-        TransformOperator transformOperator = new TransformPlanNode(_indexSegment, _queryContext, expressions,
-            Math.min(limit, DocIdSetPlanNode.MAX_DOC_PER_CALL)).run();
-        return new SelectionOnlyOperator(_indexSegment, _queryContext, expressions, transformOperator);
-      } else {
-        // Selection order-by
-        if (isAllOrderByColumnsSorted(orderByExpressions)) {
-          // All order-by columns are sorted, no need to sort the records
-          TransformOperator transformOperator = new TransformPlanNode(_indexSegment, _queryContext, expressions,
-              Math.min(limit + _queryContext.getOffset(), DocIdSetPlanNode.MAX_DOC_PER_CALL)).run();
-          return new SelectionOrderByOperator(_indexSegment, _queryContext, expressions, transformOperator, true);
-        } else if (orderByExpressions.size() == expressions.size()) {
-          // All output expressions are ordered
-          TransformOperator transformOperator =
-              new TransformPlanNode(_indexSegment, _queryContext, expressions, DocIdSetPlanNode.MAX_DOC_PER_CALL).run();
-          return new SelectionOrderByOperator(_indexSegment, _queryContext, expressions, transformOperator, false);
-        } else {
-          // Not all output expressions are ordered, only fetch the order-by expressions and docId to avoid the
-          // unnecessary data fetch
-          List<ExpressionContext> expressionsToTransform = new ArrayList<>(orderByExpressions.size());
-          for (OrderByExpressionContext orderByExpression : orderByExpressions) {
-            expressionsToTransform.add(orderByExpression.getExpression());
-          }
-          TransformOperator transformOperator =
-              new TransformPlanNode(_indexSegment, _queryContext, expressionsToTransform,
-                  DocIdSetPlanNode.MAX_DOC_PER_CALL).run();
-          return new SelectionOrderByOperator(_indexSegment, _queryContext, expressions, transformOperator, false);
-        }
-      }
-    } else {
+    if (limit == 0) {
       // Empty selection (LIMIT 0)
       TransformOperator transformOperator = new TransformPlanNode(_indexSegment, _queryContext, expressions, 0).run();
       return new EmptySelectionOperator(_indexSegment, expressions, transformOperator);
     }
+    List<OrderByExpressionContext> orderByExpressions = _queryContext.getOrderByExpressions();
+
+    if (orderByExpressions == null) {
+      // Selection only
+      // ie: SELECT ... FROM Table WHERE ... LIMIT 10
+      int actualLimit = Math.min(limit, DocIdSetPlanNode.MAX_DOC_PER_CALL);
+      TransformPlanNode planNode = new TransformPlanNode(_indexSegment, _queryContext, expressions, actualLimit);
+      TransformOperator transformOperator = planNode.run();
+
+      return new SelectionOnlyOperator(_indexSegment, _queryContext, expressions, transformOperator);
+    }
+    int numOrderByExpressions = orderByExpressions.size();
+    // Although it is a break of abstraction, some code, specially merging, assumes that if there is an order by
+    // expression the operator will return a block whose selection result is a priority queue.
+    int sortedColumnsPrefixSize = getSortedColumnsPrefix(orderByExpressions);

Review Comment:
   I don't get it. What do you mean with _null value can be stored as any default value_? The SQL standard doesn't define whether `null` is considered smaller or larger than non-null values (and offers the `ORDER BY <x> <ASC/DESC> NULL <FIRST/LAST>` to deal with it) but I guess we should be consistent.
   
   If Pinot were added to this page, which mode would it use? https://learnsql.com/blog/how-to-order-rows-with-nulls/



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] gortiz commented on a diff in pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
gortiz commented on code in PR #8979:
URL: https://github.com/apache/pinot/pull/8979#discussion_r959225492


##########
pinot-core/src/main/java/org/apache/pinot/core/common/NullableRowBasedBlockValueFetcher.java:
##########
@@ -0,0 +1,53 @@
+/**
+ * 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.pinot.core.common;
+
+import org.roaringbitmap.RoaringBitmap;
+
+
+public class NullableRowBasedBlockValueFetcher extends RowBasedBlockValueFetcher {

Review Comment:
   The reason to create a subclass here is to do not affect the hot path if possible. `RowBasedBlockValueFetcher.getRow` is in the hot path and therefore the simpler the code, the better. If we move the code to `RowBasedBlockValueFetcher`, we will need to check whether there are nulls or not on every `RowBasedBlockValueFetcher.getRow`.
   
   With the `NullableRowBasedBlockValueFetcher` approach, there is not explicit condition: Either the value fetcher will be nullable or not. Of course there is an implicit condition: we transformed the explicit `if` into a polymorphic call. Given that we only have two classes that are `RowBasedBlockValueFetcher` (the base one and the nullable one) the JIT will optimize that quite well.
   
   I assume that most of the time either a almost all queries will enable or disable null handling (in other words, I don't expect changing the null handling value very often in production). Therefore the JIT will see that almost always the class that is used is `NullableRowBasedBlockValueFetcher` or `RowBasedBlockValueFetcher` and will compile the code accordingly.
   
   I have to say that this is a guess and I don't have empiric data, but I'm sure either using polymorphism as I suggest or adding a condition, as you do, is always going to be better (in performance and readability) than the solution we are using right now where `_nullBitmaps` is associated with each operator and the conditional logic is replicated in several places



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] gortiz commented on a diff in pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
gortiz commented on code in PR #8979:
URL: https://github.com/apache/pinot/pull/8979#discussion_r960736068


##########
pinot-core/src/main/java/org/apache/pinot/core/operator/blocks/IntermediateResultsBlock.java:
##########
@@ -587,4 +600,101 @@ public BlockDocIdValueSet getBlockDocIdValueSet() {
   public BlockMetadata getMetadata() {
     throw new UnsupportedOperationException();
   }
+
+  public static class ListSelection extends IntermediateResultsBlock {

Review Comment:
   I still don't like this solution because we don't have any type safety when ordered results are required. To be honest, I don't even like that the comparator is stored in this class instead of being part of the combinator. But I'm going to just add the comparator and pray for correctness in order to have this merged sooner.



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] Jackie-Jiang commented on a diff in pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
Jackie-Jiang commented on code in PR #8979:
URL: https://github.com/apache/pinot/pull/8979#discussion_r959860447


##########
pinot-core/src/main/java/org/apache/pinot/core/plan/SelectionPlanNode.java:
##########
@@ -50,67 +52,113 @@ public Operator<IntermediateResultsBlock> run() {
     List<ExpressionContext> expressions = SelectionOperatorUtils.extractExpressions(_queryContext, _indexSegment);
     int limit = _queryContext.getLimit();
 
-    if (limit > 0) {
-      List<OrderByExpressionContext> orderByExpressions = _queryContext.getOrderByExpressions();
-      if (orderByExpressions == null) {
-        // Selection only
-        TransformOperator transformOperator = new TransformPlanNode(_indexSegment, _queryContext, expressions,
-            Math.min(limit, DocIdSetPlanNode.MAX_DOC_PER_CALL)).run();
-        return new SelectionOnlyOperator(_indexSegment, _queryContext, expressions, transformOperator);
-      } else {
-        // Selection order-by
-        if (isAllOrderByColumnsSorted(orderByExpressions)) {
-          // All order-by columns are sorted, no need to sort the records
-          TransformOperator transformOperator = new TransformPlanNode(_indexSegment, _queryContext, expressions,
-              Math.min(limit + _queryContext.getOffset(), DocIdSetPlanNode.MAX_DOC_PER_CALL)).run();
-          return new SelectionOrderByOperator(_indexSegment, _queryContext, expressions, transformOperator, true);
-        } else if (orderByExpressions.size() == expressions.size()) {
-          // All output expressions are ordered
-          TransformOperator transformOperator =
-              new TransformPlanNode(_indexSegment, _queryContext, expressions, DocIdSetPlanNode.MAX_DOC_PER_CALL).run();
-          return new SelectionOrderByOperator(_indexSegment, _queryContext, expressions, transformOperator, false);
-        } else {
-          // Not all output expressions are ordered, only fetch the order-by expressions and docId to avoid the
-          // unnecessary data fetch
-          List<ExpressionContext> expressionsToTransform = new ArrayList<>(orderByExpressions.size());
-          for (OrderByExpressionContext orderByExpression : orderByExpressions) {
-            expressionsToTransform.add(orderByExpression.getExpression());
-          }
-          TransformOperator transformOperator =
-              new TransformPlanNode(_indexSegment, _queryContext, expressionsToTransform,
-                  DocIdSetPlanNode.MAX_DOC_PER_CALL).run();
-          return new SelectionOrderByOperator(_indexSegment, _queryContext, expressions, transformOperator, false);
-        }
-      }
-    } else {
+    if (limit == 0) {
       // Empty selection (LIMIT 0)
       TransformOperator transformOperator = new TransformPlanNode(_indexSegment, _queryContext, expressions, 0).run();
       return new EmptySelectionOperator(_indexSegment, expressions, transformOperator);
     }
+    List<OrderByExpressionContext> orderByExpressions = _queryContext.getOrderByExpressions();
+
+    if (orderByExpressions == null) {
+      // Selection only
+      // ie: SELECT ... FROM Table WHERE ... LIMIT 10
+      int actualLimit = Math.min(limit, DocIdSetPlanNode.MAX_DOC_PER_CALL);
+      TransformPlanNode planNode = new TransformPlanNode(_indexSegment, _queryContext, expressions, actualLimit);
+      TransformOperator transformOperator = planNode.run();
+
+      return new SelectionOnlyOperator(_indexSegment, _queryContext, expressions, transformOperator);
+    }
+    int numOrderByExpressions = orderByExpressions.size();
+    // Although it is a break of abstraction, some code, specially merging, assumes that if there is an order by
+    // expression the operator will return a block whose selection result is a priority queue.
+    int sortedColumnsPrefixSize = getSortedColumnsPrefix(orderByExpressions);
+    if (sortedColumnsPrefixSize > 0 && isOrderByOptimizationEnabled()) {
+      // The first order by expressions are sorted (either asc or desc).
+      // ie: SELECT ... FROM Table WHERE predicates ORDER BY sorted_column DESC LIMIT 10 OFFSET 5
+      // or: SELECT ... FROM Table WHERE predicates ORDER BY sorted_column, not_sorted LIMIT 10 OFFSET 5
+      // but not SELECT ... FROM Table WHERE predicates ORDER BY not_sorted, sorted_column LIMIT 10 OFFSET 5
+      if (orderByExpressions.get(0).isAsc()) {
+        int actualLimit = Math.min(limit + _queryContext.getOffset(), DocIdSetPlanNode.MAX_DOC_PER_CALL);
+        TransformPlanNode planNode = new TransformPlanNode(_indexSegment, _queryContext, expressions, actualLimit);
+        TransformOperator transformOperator = planNode.run();
+        return new SelectionPartiallyOrderedByAscOperator(_indexSegment, _queryContext, expressions,
+            transformOperator, sortedColumnsPrefixSize);
+      } else {
+        int actualLimit = DocIdSetPlanNode.MAX_DOC_PER_CALL;
+        TransformPlanNode planNode = new TransformPlanNode(_indexSegment, _queryContext, expressions, actualLimit);
+        TransformOperator transformOperator = planNode.run();
+        return new SelectionPartiallyOrderedByDescOperation(_indexSegment, _queryContext, expressions,
+            transformOperator, sortedColumnsPrefixSize);
+      }
+    }
+    if (numOrderByExpressions == expressions.size()) {
+      // All output expressions are ordered
+      // ie: SELECT not_sorted1, not_sorted2 FROM Table WHERE ... ORDER BY not_sorted1, not_sorted2 LIMIT 10 OFFSET 5
+      TransformOperator transformOperator =
+          new TransformPlanNode(_indexSegment, _queryContext, expressions, DocIdSetPlanNode.MAX_DOC_PER_CALL).run();
+      return new SelectionOrderByOperator(_indexSegment, _queryContext, expressions, transformOperator);
+    }
+    // Not all output expressions are ordered, only fetch the order-by expressions and docId to avoid the
+    // unnecessary data fetch
+    // ie: SELECT ... FROM Table WHERE ... ORDER BY not_sorted1, not_sorted2 LIMIT 10
+    List<ExpressionContext> expressionsToTransform = new ArrayList<>(numOrderByExpressions);
+    for (OrderByExpressionContext orderByExpression : orderByExpressions) {
+      expressionsToTransform.add(orderByExpression.getExpression());
+    }
+    TransformOperator transformOperator =
+        new TransformPlanNode(_indexSegment, _queryContext, expressionsToTransform,
+            DocIdSetPlanNode.MAX_DOC_PER_CALL).run();
+    return new SelectionOrderByOperator(_indexSegment, _queryContext, expressions, transformOperator);
   }
 
   /**
-   *  This function checks whether all columns in order by clause are pre-sorted.
-   *  This is used to optimize order by limit clauses.
-   *  For eg:
-   *  A query like "select * from table order by col1, col2 limit 10"
-   *  will take all the n matching rows and add it to a priority queue of size 10.
-   *  This is nlogk operation which can be quite expensive for a large n.
-   *  In the above example, if the docs in the segment are already sorted by col1 and col2 then there is no need for
-   *  sorting at all (only limit is needed).
-   * @return true is all columns in order by clause are sorted . False otherwise
+   * This functions returns the number of expressions that are sorted by the implicit order in the index.
+   *
+   * This means that query that uses these expressions in its order by doesn't actually need to sort from 0 to the
+   * given number (excluded) of expressions, as they are returned in the correct order.
+   *
+   * This method supports ASC and DESC order and ensures that all prefix expressions follow the same order. For example,
+   * ORDER BY sorted_col1 ASC, sorted_col2 ASC and ORDER BY sorted_col1 DESC, sorted_col2 DESC will return 2 but
+   * ORDER BY sorted_col1 DESC, sorted_col2 ASC and ORDER BY sorted_col1 ASC, sorted_col2 DESC will return 1 while
+   * ORDER BY not_sorted, sorted_col1 will return 0 because the first column is not sorted.
+   *
+   * It doesn't make sense to add literal expressions in an order by expression, but if they are included, they are
+   * considered sorted and its ASC/DESC is ignored.
+   *
+   * @return the max number that guarantees that from the first expression to the returned number, the index is already
+   * sorted.
    */
-  private boolean isAllOrderByColumnsSorted(List<OrderByExpressionContext> orderByExpressions) {
-    for (OrderByExpressionContext orderByExpression : orderByExpressions) {
-      if (!(orderByExpression.getExpression().getType() == ExpressionContext.Type.IDENTIFIER)
-          || !orderByExpression.isAsc()) {
-        return false;
+  private int getSortedColumnsPrefix(List<OrderByExpressionContext> orderByExpressions) {
+    boolean asc = orderByExpressions.get(0).isAsc();
+    for (int i = 0; i < orderByExpressions.size(); i++) {
+      if (!isSorted(orderByExpressions.get(i), asc)) {
+        return i;
       }
-      String column = orderByExpression.getExpression().getIdentifier();
-      if (!_indexSegment.getDataSource(column).getDataSourceMetadata().isSorted()) {
+    }
+    // If we reach here, all are sorted
+    return orderByExpressions.size();
+  }
+
+  private boolean isSorted(OrderByExpressionContext orderByExpression, boolean asc) {
+    switch (orderByExpression.getExpression().getType()) {
+      case LITERAL: {
+        return true;
+      }
+      case IDENTIFIER: {
+        if (!orderByExpression.isAsc() == asc) {
+          return false;
+        }
+        String column = orderByExpression.getExpression().getIdentifier();
+        return _indexSegment.getDataSource(column).getDataSourceMetadata().isSorted();
+      }
+      case FUNCTION: // we could optimize monotonically increasing functions
+      default: {
         return false;
       }
     }
-    return true;
+  }
+
+  private boolean isOrderByOptimizationEnabled() {

Review Comment:
   What I meant is that since this is on by default, we can choose to not have it (always on).
   
   If you feel it is useful to have the ability to turn it off, we can put it in the `QueryOptionsUtils` (which you already did), and store the key in the constant for easier tracking. For the existing naming convention, suggest changing it to `skipOrderByOptimization` and make it default to `false`



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] gortiz commented on a diff in pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
gortiz commented on code in PR #8979:
URL: https://github.com/apache/pinot/pull/8979#discussion_r977481626


##########
pinot-core/src/main/java/org/apache/pinot/core/operator/combine/BaseCombineOperator.java:
##########
@@ -250,6 +250,18 @@ protected boolean isQuerySatisfied(T resultsBlock) {
    */
   protected abstract void mergeResultsBlocks(T mergedBlock, T blockToMerge);
 
+  /**
+   * Converts the given generic IntermediateResultBlock into the specific type of IntermediateResultBlock that is
+   * supported by this combine operator.
+   *
+   * This operator may return the same object if the runtime type of the given block already matches which what it is
+   * expected.
+   *
+   * The returned object will usually be the one received as first argument of
+   * {@link #mergeResultsBlocks(BaseResultsBlock, BaseResultsBlock)}.
+   */
+  protected abstract T createInitialResultBlock(BaseResultsBlock block);

Review Comment:
   I don't think we should use T here because it may be the case that the child operator returns a different block type than the one used in the BaseCombineOperator. By adding T here we:
   - Need to cast the child operator, whose static type is usually Block or BaseResultBlock, to T before calling this method.
   - Couple the child operator and the combine operator when it is not needed.
   
   I've just changed the code a little bit make this explicit by adding another method such as:
   
   ```java
     /**
      * Converts the given generic BaseResultsBlock into the specific type of BaseResultsBlock that is supported by this
      * operator.
      *
      * This operator may return the same object if the runtime type of the given block already matches which what it is
      * expected.
      *
      * The returned object will usually be the one received as second argument of
      * {@link #mergeResultsBlocks(T, T)}
      */
     protected T convertToAppendableBlock(BaseResultsBlock block) {
       return (T) block;
     }
   ```



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] gortiz commented on a diff in pull request #8979: optimize `order by sorted ASC, unsorted` case

Posted by GitBox <gi...@apache.org>.
gortiz commented on code in PR #8979:
URL: https://github.com/apache/pinot/pull/8979#discussion_r913456989


##########
pinot-core/src/main/java/org/apache/pinot/core/operator/query/SelectionPartiallyOrderedByOperator.java:
##########
@@ -0,0 +1,303 @@
+/**
+ * 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.pinot.core.operator.query;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+import javax.annotation.Nullable;
+import org.apache.pinot.common.request.context.ExpressionContext;
+import org.apache.pinot.common.request.context.OrderByExpressionContext;
+import org.apache.pinot.common.utils.DataSchema;
+import org.apache.pinot.core.common.BlockValSet;
+import org.apache.pinot.core.common.Operator;
+import org.apache.pinot.core.common.RowBasedBlockValueFetcher;
+import org.apache.pinot.core.operator.BaseOperator;
+import org.apache.pinot.core.operator.ExecutionStatistics;
+import org.apache.pinot.core.operator.blocks.IntermediateResultsBlock;
+import org.apache.pinot.core.operator.blocks.TransformBlock;
+import org.apache.pinot.core.operator.transform.TransformOperator;
+import org.apache.pinot.core.operator.transform.TransformResultMetadata;
+import org.apache.pinot.core.query.request.context.QueryContext;
+import org.apache.pinot.core.query.selection.SelectionOperatorUtils;
+import org.apache.pinot.segment.spi.IndexSegment;
+
+
+/**
+ * An operator for order-by queries that are partially sorted over the sorting keys.
+ */
+public class SelectionPartiallyOrderedByOperator extends BaseOperator<IntermediateResultsBlock> {
+
+  private static final String EXPLAIN_NAME = "SELECT_PARTIAL_ORDERBY";
+
+  private final IndexSegment _indexSegment;
+
+  // Deduped order-by expressions followed by output expressions from SelectionOperatorUtils.extractExpressions()
+  private final List<ExpressionContext> _expressions;
+  private final List<ExpressionContext> _alreadySorted;
+  private final List<ExpressionContext> _toSort;
+
+  private final TransformOperator _transformOperator;
+  private final List<OrderByExpressionContext> _orderByExpressions;
+  private final TransformResultMetadata[] _expressionsMetadata;
+  private final int _numRowsToKeep;
+  private final PartiallySortedListBuilder _sorter;
+
+  private int _numDocsScanned = 0;
+  private long _numEntriesScannedPostFilter = 0;
+  private boolean _used = false;

Review Comment:
   Just to check that the method is not called twice. I hope it is more clear now.



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] gortiz commented on a diff in pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
gortiz commented on code in PR #8979:
URL: https://github.com/apache/pinot/pull/8979#discussion_r950061067


##########
pinot-core/src/main/java/org/apache/pinot/core/operator/blocks/IntermediateResultsBlock.java:
##########
@@ -80,9 +81,8 @@ public IntermediateResultsBlock() {
   /**
    * Constructor for selection result.
    */
-  public IntermediateResultsBlock(DataSchema dataSchema, Collection<Object[]> selectionResult) {
+  public IntermediateResultsBlock(DataSchema dataSchema) {

Review Comment:
   I understand that. The change is quite large, but it provides type safety at compile time. For example, now it is clear that `MinMaxValueBasedSelectionOrderByCombineOperator` or `SelectionOrderByOperator` require priority queues.
   
   Anyway, I understand that this change is the most subjective one, so I'm open to change it



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] Jackie-Jiang commented on a diff in pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
Jackie-Jiang commented on code in PR #8979:
URL: https://github.com/apache/pinot/pull/8979#discussion_r925008347


##########
pinot-core/src/main/java/org/apache/pinot/core/operator/blocks/IntermediateResultsBlock.java:
##########
@@ -80,9 +81,8 @@ public IntermediateResultsBlock() {
   /**
    * Constructor for selection result.
    */
-  public IntermediateResultsBlock(DataSchema dataSchema, Collection<Object[]> selectionResult) {
+  public IntermediateResultsBlock(DataSchema dataSchema) {

Review Comment:
   The change in this class can be simplified by adding a `@Nullable Comparator<? super Object[]> comparator`, then we may add a new method `public PriorityQueue<Object[]> getSelectionResultAsPriorityQueue()`. I feel the current change is a little bit too complicated, and we might not want to extend this block



##########
pinot-core/src/main/java/org/apache/pinot/core/operator/query/SelectionPartiallyOrderedByDescOperation.java:
##########
@@ -0,0 +1,105 @@
+/**
+ * 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.pinot.core.operator.query;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.List;
+import org.apache.pinot.common.request.context.ExpressionContext;
+import org.apache.pinot.core.common.BlockValSet;
+import org.apache.pinot.core.common.RowBasedBlockValueFetcher;
+import org.apache.pinot.core.operator.blocks.TransformBlock;
+import org.apache.pinot.core.operator.transform.TransformOperator;
+import org.apache.pinot.core.query.request.context.QueryContext;
+import org.apache.pinot.segment.spi.IndexSegment;
+
+
+/**
+ * An operator for order-by queries DESC that are partially sorted over the sorting keys.
+ *
+ * @see LinearSelectionOrderByOperator
+ */
+public class SelectionPartiallyOrderedByDescOperation extends LinearSelectionOrderByOperator {
+
+  private static final String EXPLAIN_NAME = "SELECT_PARTIAL_ORDER_BY_DESC";
+
+  private int _numDocsScanned = 0;
+  private long _numEntriesScannedPostFilter = 0;
+
+  public SelectionPartiallyOrderedByDescOperation(IndexSegment indexSegment, QueryContext queryContext,
+      List<ExpressionContext> expressions, TransformOperator transformOperator, int sortedExpr) {
+    super(indexSegment, queryContext, expressions, transformOperator, sortedExpr);
+    assert queryContext.getOrderByExpressions() != null;
+    Preconditions.checkArgument(queryContext.getOrderByExpressions().stream()
+            .filter(expr -> expr.getExpression().getType() == ExpressionContext.Type.IDENTIFIER)
+            .findFirst()
+            .orElseThrow(() -> new IllegalArgumentException("The query is not order by identifiers"))
+            .isDesc(),
+        "%s can only be used when the first column in order by is DESC", EXPLAIN_NAME);
+  }
+
+  @Override
+  protected void fetch(ListBuilder listBuilder) {
+
+    List<TransformBlock> blocks = new ArrayList<>();
+
+    TransformBlock transformBlock;
+    int numColumnsProjected = _transformOperator.getNumColumnsProjected();
+    try {
+      while ((transformBlock = _transformOperator.nextBlock()) != null) {
+        int numDocsFetched = transformBlock.getNumDocs();
+        _numDocsScanned += numDocsFetched;
+        blocks.add(transformBlock);

Review Comment:
   (MAJOR) We cannot store all blocks here because the `ProjectionBlock` shares the same `DataBlockCache` underlying, where the previous value is overridden.
   For descending order, the best we can do currently is to iterate in reverse order from each block, and keep up to `LIMIT` rows per block. When getting the next block, if we gathered enough rows, we can throw away the rows from the previous block.



##########
pinot-core/src/main/java/org/apache/pinot/core/operator/query/LinearSelectionOrderByOperator.java:
##########
@@ -0,0 +1,388 @@
+/**
+ * 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.pinot.core.operator.query;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+import javax.annotation.Nullable;
+import org.apache.pinot.common.request.context.ExpressionContext;
+import org.apache.pinot.common.request.context.OrderByExpressionContext;
+import org.apache.pinot.common.utils.DataSchema;
+import org.apache.pinot.core.common.BlockValSet;
+import org.apache.pinot.core.common.Operator;
+import org.apache.pinot.core.common.RowBasedBlockValueFetcher;
+import org.apache.pinot.core.operator.BaseOperator;
+import org.apache.pinot.core.operator.ExecutionStatistics;
+import org.apache.pinot.core.operator.blocks.IntermediateResultsBlock;
+import org.apache.pinot.core.operator.blocks.TransformBlock;
+import org.apache.pinot.core.operator.transform.TransformOperator;
+import org.apache.pinot.core.operator.transform.TransformResultMetadata;
+import org.apache.pinot.core.query.request.context.QueryContext;
+import org.apache.pinot.core.query.selection.SelectionOperatorUtils;
+import org.apache.pinot.segment.spi.IndexSegment;
+
+
+/**
+ * A selection Operator used when the first expressions in the order by are identifier expressions of columns that are
+ * already sorted (either ascendingly or descendingly), even if the tail of order by expressions are not sorted.
+ *
+ * ie: SELECT ... FROM Table WHERE predicates ORDER BY sorted_column DESC LIMIT 10 OFFSET 5
+ * or: SELECT ... FROM Table WHERE predicates ORDER BY sorted_column, not_sorted LIMIT 10 OFFSET 5
+ * but not SELECT ... FROM Table WHERE predicates ORDER BY not_sorted, sorted_column LIMIT 10 OFFSET 5
+ *
+ * Operators that derives from this class are going to have an almost linear cost instead of the usual NlogN when actual
+ * sorting must be done, where N is the number of rows in the segment.
+ * There is a degraded scenario when the cost is actually NlogL (where L is the limit of the query) when all the first L
+ * rows have the exact same value for the prefix of the sorted columns. Even in that case, L should be quite smaller
+ * than N, so this implementation is algorithmically better than the normal solution.
+ */
+public abstract class LinearSelectionOrderByOperator extends BaseOperator<IntermediateResultsBlock> {
+  protected final IndexSegment _indexSegment;
+
+  // Deduped order-by expressions followed by output expressions from SelectionOperatorUtils.extractExpressions()
+  protected final List<ExpressionContext> _expressions;
+  protected final List<ExpressionContext> _alreadySorted;
+  protected final List<ExpressionContext> _toSort;
+
+  protected final TransformOperator _transformOperator;
+  protected final List<OrderByExpressionContext> _orderByExpressions;
+  protected final TransformResultMetadata[] _expressionsMetadata;
+  protected final int _numRowsToKeep;
+  private final ListBuilder _listBuilder;
+  protected boolean _used = false;
+  protected Comparator<Object[]> _comparator;
+
+  /**
+   *
+   * @param expressions order by expressions must be at the head of the list.
+   * @param sortedExpr How many expressions at the head of the expression list are going to be considered sorted by
+   * {@link #fetch(ListBuilder)}
+   */
+  public LinearSelectionOrderByOperator(IndexSegment indexSegment, QueryContext queryContext,
+      List<ExpressionContext> expressions, TransformOperator transformOperator,
+      int sortedExpr) {
+    _indexSegment = indexSegment;
+    _expressions = expressions;
+    _transformOperator = transformOperator;
+
+    _orderByExpressions = queryContext.getOrderByExpressions();
+    assert _orderByExpressions != null;
+    int numOrderByExpressions = _orderByExpressions.size();
+
+    _alreadySorted = expressions.subList(0, sortedExpr);
+    _toSort = expressions.subList(sortedExpr, numOrderByExpressions);
+
+    _expressionsMetadata = new TransformResultMetadata[_expressions.size()];
+    for (int i = 0; i < _expressionsMetadata.length; i++) {
+      ExpressionContext expression = _expressions.get(i);
+      _expressionsMetadata[i] = _transformOperator.getResultMetadata(expression);
+    }
+
+    _numRowsToKeep = queryContext.getOffset() + queryContext.getLimit();
+
+    if (_toSort.isEmpty()) {
+      int expectedSize = Math.min(SelectionOperatorUtils.MAX_ROW_HOLDER_INITIAL_CAPACITY, _numRowsToKeep);
+      _listBuilder = new TotallySortedListBuilder(expectedSize);
+    } else {
+      int expectedSize = Math.min(SelectionOperatorUtils.MAX_ROW_HOLDER_INITIAL_CAPACITY, _numRowsToKeep * 2);
+
+      Comparator<Object[]> sortedComparator =
+          OrderByComparatorFactory.getComparator(_orderByExpressions, _expressionsMetadata, true, 0, sortedExpr);
+      Comparator<Object[]> unsortedComparator =
+          OrderByComparatorFactory.getComparator(_orderByExpressions, _expressionsMetadata, true, sortedExpr,
+              numOrderByExpressions);
+      _listBuilder = new PartiallySortedListBuilder(expectedSize, sortedComparator, unsortedComparator);
+    }
+
+    _comparator = OrderByComparatorFactory.getComparator(_orderByExpressions, _expressionsMetadata, false);
+  }
+
+  @Override
+  public IndexSegment getIndexSegment() {
+    return _indexSegment;
+  }
+
+  @Override
+  public ExecutionStatistics getExecutionStatistics() {
+    long numEntriesScannedInFilter = _transformOperator.getExecutionStatistics().getNumEntriesScannedInFilter();
+    int numTotalDocs = _indexSegment.getSegmentMetadata().getTotalDocs();
+    return new ExecutionStatistics(getNumDocsScanned(), numEntriesScannedInFilter, getNumEntriesScannedPostFilter(),
+        numTotalDocs);
+  }
+
+  protected RowBasedBlockValueFetcher fetchBlock(TransformBlock transformBlock, BlockValSet[] blockValSets) {
+    int numExpressions = _expressions.size();
+
+    for (int i = 0; i < numExpressions; i++) {
+      ExpressionContext expression = _expressions.get(i);
+      blockValSets[i] = transformBlock.getBlockValueSet(expression);
+    }
+    return new RowBasedBlockValueFetcher(blockValSets);
+  }
+
+  protected abstract long getNumEntriesScannedPostFilter();
+
+  protected abstract int getNumDocsScanned();
+
+  /**
+   * Modifies the given {@link ListBuilder} adding rows in an order compatible with the constructor used until the
+   * implementation considers that no more rows need to be added.
+   */
+  protected abstract void fetch(ListBuilder listBuilder);
+
+  @Override
+  public List<Operator> getChildOperators() {
+    return Collections.singletonList(_transformOperator);
+  }
+
+  protected abstract String getExplainName();
+
+  @Override
+  public String toExplainString() {
+    StringBuilder sb = new StringBuilder(getExplainName());
+
+    sb.append("(sortedList: ");
+    concatList(sb, _alreadySorted);
+
+    sb.append(", unsortedList: ");
+    concatList(sb, _toSort);
+
+    sb.append(", rest: ");
+    concatList(sb, _expressions.subList(_alreadySorted.size() + _toSort.size(), _expressions.size()));
+
+    sb.append(')');
+    return sb.toString();
+  }
+
+  private void concatList(StringBuilder sb, List<?> list) {
+    sb.append('(');
+    Iterator<?> it = list.iterator();
+    if (it.hasNext()) {
+      sb.append(it.next());
+      while (it.hasNext()) {
+        sb.append(", ").append(it.next());
+      }
+    }
+    sb.append(')');
+  }
+
+  @Override
+  protected IntermediateResultsBlock getNextBlock() {
+    Preconditions.checkState(!_used, "nextBlock was called more than once");
+    _used = true;
+    fetch(_listBuilder);
+
+    DataSchema dataSchema = createDataSchema();
+
+    List<Object[]> list = _listBuilder.build();
+    if (list.size() > _numRowsToKeep) {
+      list = new ArrayList<>(list.subList(0, _numRowsToKeep));
+    }
+
+    return new IntermediateResultsBlock.ListSelection(dataSchema, list, _comparator);
+  }
+
+  protected DataSchema createDataSchema() {
+    int numExpressions = _expressions.size();
+
+    // Create the data schema
+    String[] columnNames = new String[numExpressions];
+    DataSchema.ColumnDataType[] columnDataTypes = new DataSchema.ColumnDataType[numExpressions];
+    for (int i = 0; i < columnNames.length; i++) {
+      columnNames[i] = _expressions.get(i).toString();
+    }
+    for (int i = 0; i < numExpressions; i++) {
+      TransformResultMetadata expressionMetadata = _expressionsMetadata[i];
+      columnDataTypes[i] =
+          DataSchema.ColumnDataType.fromDataType(expressionMetadata.getDataType(), expressionMetadata.isSingleValue());
+    }
+    return new DataSchema(columnNames, columnDataTypes);
+  }
+
+  /**
+   * A private class used to build a sorted list by adding partially sorted data.
+   *
+   * Specifically, this class has been designed to receive successive calls to {@link #add(Object[])} follow by a single
+   * call to {@link #build()}. Once this method is called, the behavior of this object is undefined and therefore it
+   * should not be used.
+   *
+   * Rows must be inserted in ascending order accordingly to the partial order specified by a comparator.
+   * This comparator will define <i>partitions</i> of rows. All the rows in the same partition same are considered equal
+   * by that comparator.
+   *
+   * Some implementations, like {@link PartiallySortedListBuilder} accepts a second comparator that is used to sort rows
+   * inside each partition.
+   * When calling {@link #add(Object[])} with a row that doesn't belong to the current partition, a new one is started
+   * and the previous one is sorted. Therefore, this object maintains the invariant that at any moment there are at
+   * least {@link #sortedSize()} elements that are completely sorted, which means that no matter which elements are
+   * added after that, these elements are going to be smallest.
+   */
+  protected interface ListBuilder {
+
+    /**
+     * Adds the given row to this object. The new column must be equal or higher than the partition comparator.
+     *
+     * @param row The row to add. The values of the already sorted columns must be equal or higher than the last added
+     *           row, if any.
+     * @return true if and only if the previous partition was closed.
+     */
+    boolean add(Object[] row);
+
+    /**
+     * Builds the sorted list. The returned list will be sorted, even if a previous call t o {@link #sortedSize()}
+     * returned a number lower than the number of elements that have been added.
+     *
+     * Once this method is called, the builder should not be used. There is no guaranteed on whether
+     * {@link #sortedSize()} is updated or not.
+     */
+    List<Object[]> build();
+
+    /**
+     * How many elements are actually sorted. This number is lower or equal to the number of elements that has been
+     * added.
+     */
+    int sortedSize();
+  }
+
+  /**
+   * This is the faster {@link ListBuilder} but also the most restrictive one. It can only be used when data is inserted
+   * in total order. Therefore it cannot be used to implement order-by queries where there is at least one expression
+   * that is not sorted. In such case {@link PartiallySortedListBuilder} should be used.
+   *
+   * This implementation is just a wrapper over an ArrayList and therefore the average costs of its methods is constant.
+   */
+  protected static class TotallySortedListBuilder implements ListBuilder {
+    private final ArrayList<Object[]> _list;
+
+    public TotallySortedListBuilder(int expectedSize) {
+      _list = new ArrayList<>(expectedSize);
+    }
+
+    @Override
+    public boolean add(Object[] row) {
+      _list.add(row);
+      return true;
+    }
+
+    @Override
+    public List<Object[]> build() {
+      return _list;
+    }
+
+    @Override
+    public int sortedSize() {
+      return _list.size();
+    }
+  }
+
+  /**
+   * This is the more versatile {@link ListBuilder} that requires two comparators: The first defines the order on which
+   * {@link #add(Object[])} is called and defines the partitions. The second one is used to sort rows in the same
+   * paritition. This class can be used to implement order-by queries that include one or more not sorted expressions.
+   * In cases where all expressions are sorted, {@link TotallySortedListBuilder} should be used because its performance
+   * is better.
+   *
+   * In this implementation the {@link #add(Object[])} method has a log(P) cost, where P is the number of elements in
+   * each partition. In normal cases we can consider P a constant. In some degenerated cases like having an ordering by
+   * a sorted column whose values are all equal, P may tend to the number of elements in the segment, which would make
+   * the cost of this method log(N).
+   */
+  private static class PartiallySortedListBuilder implements ListBuilder {
+    private final ArrayList<Object[]> _rows;
+    /**
+     * The comparator that defines the partitions and the one that impose in which order add has to be called.
+     */
+    private final Comparator<Object[]> _partitionComparator;
+    /**
+     * The comparator that sorts different rows on each partition.
+     */
+    private final Comparator<Object[]> _unsortedComparator;
+    @Nullable
+    private Object[] _lastPartitionRow;
+    /**
+     * The index where the current (and still not sorted) partition starts.
+     */
+    private int _lastSorted;
+
+    public PartiallySortedListBuilder(int expectedSize, Comparator<Object[]> partitionComparator,
+        Comparator<Object[]> unsortedComparator) {
+      _rows = new ArrayList<>(expectedSize);
+      _partitionComparator = partitionComparator;
+      _unsortedComparator = unsortedComparator;
+    }
+
+    @Override
+    public boolean add(Object[] row) {
+      boolean result;
+      if (_lastPartitionRow == null) {
+        _lastSorted = 0;
+        _lastPartitionRow = row;
+        result = false;
+      } else {
+        int cmp = _partitionComparator.compare(row, _lastPartitionRow);
+        if (cmp < 0) {
+          throw new IllegalArgumentException("Row " + Arrays.toString(row) + " is lower than previously added row"
+              + Arrays.toString(_lastPartitionRow));
+        }
+        if (cmp > 0) {

Review Comment:
   In some corner case, we might gather too many rows with sorted columns the same value, and cause memory issue. We might want to use a priority queue and only keep the `LIMIT` rows



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] gortiz commented on a diff in pull request #8979: optimize `order by sorted ASC, unsorted` case

Posted by GitBox <gi...@apache.org>.
gortiz commented on code in PR #8979:
URL: https://github.com/apache/pinot/pull/8979#discussion_r913463570


##########
pinot-core/src/main/java/org/apache/pinot/core/operator/query/SelectionPartiallyOrderedByOperator.java:
##########
@@ -0,0 +1,303 @@
+/**
+ * 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.pinot.core.operator.query;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+import javax.annotation.Nullable;
+import org.apache.pinot.common.request.context.ExpressionContext;
+import org.apache.pinot.common.request.context.OrderByExpressionContext;
+import org.apache.pinot.common.utils.DataSchema;
+import org.apache.pinot.core.common.BlockValSet;
+import org.apache.pinot.core.common.Operator;
+import org.apache.pinot.core.common.RowBasedBlockValueFetcher;
+import org.apache.pinot.core.operator.BaseOperator;
+import org.apache.pinot.core.operator.ExecutionStatistics;
+import org.apache.pinot.core.operator.blocks.IntermediateResultsBlock;
+import org.apache.pinot.core.operator.blocks.TransformBlock;
+import org.apache.pinot.core.operator.transform.TransformOperator;
+import org.apache.pinot.core.operator.transform.TransformResultMetadata;
+import org.apache.pinot.core.query.request.context.QueryContext;
+import org.apache.pinot.core.query.selection.SelectionOperatorUtils;
+import org.apache.pinot.segment.spi.IndexSegment;
+
+
+/**
+ * An operator for order-by queries that are partially sorted over the sorting keys.
+ */
+public class SelectionPartiallyOrderedByOperator extends BaseOperator<IntermediateResultsBlock> {
+
+  private static final String EXPLAIN_NAME = "SELECT_PARTIAL_ORDERBY";
+
+  private final IndexSegment _indexSegment;
+
+  // Deduped order-by expressions followed by output expressions from SelectionOperatorUtils.extractExpressions()
+  private final List<ExpressionContext> _expressions;
+  private final List<ExpressionContext> _alreadySorted;
+  private final List<ExpressionContext> _toSort;
+
+  private final TransformOperator _transformOperator;
+  private final List<OrderByExpressionContext> _orderByExpressions;
+  private final TransformResultMetadata[] _expressionsMetadata;
+  private final int _numRowsToKeep;
+  private final PartiallySortedListBuilder _sorter;
+
+  private int _numDocsScanned = 0;
+  private long _numEntriesScannedPostFilter = 0;
+  private boolean _used = false;
+  private Comparator<Object[]> _comparator;
+
+  public SelectionPartiallyOrderedByOperator(IndexSegment indexSegment, QueryContext queryContext,
+      List<ExpressionContext> expressions, TransformOperator transformOperator, int sortedExpr) {
+    Preconditions.checkArgument(sortedExpr > 0,
+        "This operator should not be used when sorting expressions doesn't start with sorted expressions");
+    _indexSegment = indexSegment;
+    _expressions = expressions;
+    _transformOperator = transformOperator;
+
+    _orderByExpressions = queryContext.getOrderByExpressions();
+    assert _orderByExpressions != null;
+    int numOrderByExpressions = _orderByExpressions.size();
+
+    _alreadySorted = expressions.subList(0, sortedExpr);
+    _toSort = expressions.subList(sortedExpr, numOrderByExpressions);
+
+    Preconditions.checkArgument(!_toSort.isEmpty(),
+        "This operator should not be used when all sorting expressions are sorted. "
+            + "Use %s instead", SelectionOrderByOperator.class.getName());
+
+    _expressionsMetadata = new TransformResultMetadata[_expressions.size()];
+    for (int i = 0; i < _expressionsMetadata.length; i++) {
+      ExpressionContext expression = _expressions.get(i);
+      _expressionsMetadata[i] = _transformOperator.getResultMetadata(expression);
+    }
+
+    _numRowsToKeep = queryContext.getOffset() + queryContext.getLimit();
+
+    int expectedSize = Math.min(_numRowsToKeep * 2, SelectionOperatorUtils.MAX_ROW_HOLDER_INITIAL_CAPACITY);
+    Comparator<Object[]> sortedComparator =
+        SelectionOrderByOperator.getComparator(_orderByExpressions, _expressionsMetadata, true, 0, sortedExpr);
+    Comparator<Object[]> unsortedComparator =
+        SelectionOrderByOperator.getComparator(_orderByExpressions, _expressionsMetadata, true, sortedExpr,
+            numOrderByExpressions);
+    _sorter = new PartiallySortedListBuilder(expectedSize, sortedComparator, unsortedComparator);
+    _comparator = SelectionOrderByOperator.getComparator(_orderByExpressions, _expressionsMetadata, false);
+  }
+
+  @Override
+  public List<Operator> getChildOperators() {
+    return Collections.singletonList(_transformOperator);
+  }
+
+  @Override
+  protected IntermediateResultsBlock getNextBlock() {
+    if (!_used) {
+      _used = true;
+      fetch();
+
+      DataSchema dataSchema = createDataSchema();
+
+      return new IntermediateResultsBlock.ListSelection(dataSchema, _sorter.build(), _comparator);

Review Comment:
   We create one `SelectionPartiallyOrderedByOperator` per query per segment, right? So yeah, we build one `sorter` for each query per segment.
   
   Remember that `_sorter.build()` does not generate memory, it just returns the list it used internally and it shouldn't be used again.



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] gortiz commented on a diff in pull request #8979: optimize `order by sorted ASC, unsorted` case

Posted by GitBox <gi...@apache.org>.
gortiz commented on code in PR #8979:
URL: https://github.com/apache/pinot/pull/8979#discussion_r913456989


##########
pinot-core/src/main/java/org/apache/pinot/core/operator/query/SelectionPartiallyOrderedByOperator.java:
##########
@@ -0,0 +1,303 @@
+/**
+ * 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.pinot.core.operator.query;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+import javax.annotation.Nullable;
+import org.apache.pinot.common.request.context.ExpressionContext;
+import org.apache.pinot.common.request.context.OrderByExpressionContext;
+import org.apache.pinot.common.utils.DataSchema;
+import org.apache.pinot.core.common.BlockValSet;
+import org.apache.pinot.core.common.Operator;
+import org.apache.pinot.core.common.RowBasedBlockValueFetcher;
+import org.apache.pinot.core.operator.BaseOperator;
+import org.apache.pinot.core.operator.ExecutionStatistics;
+import org.apache.pinot.core.operator.blocks.IntermediateResultsBlock;
+import org.apache.pinot.core.operator.blocks.TransformBlock;
+import org.apache.pinot.core.operator.transform.TransformOperator;
+import org.apache.pinot.core.operator.transform.TransformResultMetadata;
+import org.apache.pinot.core.query.request.context.QueryContext;
+import org.apache.pinot.core.query.selection.SelectionOperatorUtils;
+import org.apache.pinot.segment.spi.IndexSegment;
+
+
+/**
+ * An operator for order-by queries that are partially sorted over the sorting keys.
+ */
+public class SelectionPartiallyOrderedByOperator extends BaseOperator<IntermediateResultsBlock> {
+
+  private static final String EXPLAIN_NAME = "SELECT_PARTIAL_ORDERBY";
+
+  private final IndexSegment _indexSegment;
+
+  // Deduped order-by expressions followed by output expressions from SelectionOperatorUtils.extractExpressions()
+  private final List<ExpressionContext> _expressions;
+  private final List<ExpressionContext> _alreadySorted;
+  private final List<ExpressionContext> _toSort;
+
+  private final TransformOperator _transformOperator;
+  private final List<OrderByExpressionContext> _orderByExpressions;
+  private final TransformResultMetadata[] _expressionsMetadata;
+  private final int _numRowsToKeep;
+  private final PartiallySortedListBuilder _sorter;
+
+  private int _numDocsScanned = 0;
+  private long _numEntriesScannedPostFilter = 0;
+  private boolean _used = false;

Review Comment:
   Just to check that the method is not called twice. I hope it is clearer now.



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] gortiz commented on a diff in pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
gortiz commented on code in PR #8979:
URL: https://github.com/apache/pinot/pull/8979#discussion_r932898178


##########
pinot-core/src/main/java/org/apache/pinot/core/operator/query/LinearSelectionOrderByOperator.java:
##########
@@ -0,0 +1,388 @@
+/**
+ * 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.pinot.core.operator.query;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+import javax.annotation.Nullable;
+import org.apache.pinot.common.request.context.ExpressionContext;
+import org.apache.pinot.common.request.context.OrderByExpressionContext;
+import org.apache.pinot.common.utils.DataSchema;
+import org.apache.pinot.core.common.BlockValSet;
+import org.apache.pinot.core.common.Operator;
+import org.apache.pinot.core.common.RowBasedBlockValueFetcher;
+import org.apache.pinot.core.operator.BaseOperator;
+import org.apache.pinot.core.operator.ExecutionStatistics;
+import org.apache.pinot.core.operator.blocks.IntermediateResultsBlock;
+import org.apache.pinot.core.operator.blocks.TransformBlock;
+import org.apache.pinot.core.operator.transform.TransformOperator;
+import org.apache.pinot.core.operator.transform.TransformResultMetadata;
+import org.apache.pinot.core.query.request.context.QueryContext;
+import org.apache.pinot.core.query.selection.SelectionOperatorUtils;
+import org.apache.pinot.segment.spi.IndexSegment;
+
+
+/**
+ * A selection Operator used when the first expressions in the order by are identifier expressions of columns that are
+ * already sorted (either ascendingly or descendingly), even if the tail of order by expressions are not sorted.
+ *
+ * ie: SELECT ... FROM Table WHERE predicates ORDER BY sorted_column DESC LIMIT 10 OFFSET 5
+ * or: SELECT ... FROM Table WHERE predicates ORDER BY sorted_column, not_sorted LIMIT 10 OFFSET 5
+ * but not SELECT ... FROM Table WHERE predicates ORDER BY not_sorted, sorted_column LIMIT 10 OFFSET 5
+ *
+ * Operators that derives from this class are going to have an almost linear cost instead of the usual NlogN when actual
+ * sorting must be done, where N is the number of rows in the segment.
+ * There is a degraded scenario when the cost is actually NlogL (where L is the limit of the query) when all the first L
+ * rows have the exact same value for the prefix of the sorted columns. Even in that case, L should be quite smaller
+ * than N, so this implementation is algorithmically better than the normal solution.
+ */
+public abstract class LinearSelectionOrderByOperator extends BaseOperator<IntermediateResultsBlock> {
+  protected final IndexSegment _indexSegment;
+
+  // Deduped order-by expressions followed by output expressions from SelectionOperatorUtils.extractExpressions()
+  protected final List<ExpressionContext> _expressions;
+  protected final List<ExpressionContext> _alreadySorted;
+  protected final List<ExpressionContext> _toSort;
+
+  protected final TransformOperator _transformOperator;
+  protected final List<OrderByExpressionContext> _orderByExpressions;
+  protected final TransformResultMetadata[] _expressionsMetadata;
+  protected final int _numRowsToKeep;
+  private final ListBuilder _listBuilder;
+  protected boolean _used = false;
+  protected Comparator<Object[]> _comparator;
+
+  /**
+   *
+   * @param expressions order by expressions must be at the head of the list.
+   * @param sortedExpr How many expressions at the head of the expression list are going to be considered sorted by
+   * {@link #fetch(ListBuilder)}
+   */
+  public LinearSelectionOrderByOperator(IndexSegment indexSegment, QueryContext queryContext,
+      List<ExpressionContext> expressions, TransformOperator transformOperator,
+      int sortedExpr) {
+    _indexSegment = indexSegment;
+    _expressions = expressions;
+    _transformOperator = transformOperator;
+
+    _orderByExpressions = queryContext.getOrderByExpressions();
+    assert _orderByExpressions != null;
+    int numOrderByExpressions = _orderByExpressions.size();
+
+    _alreadySorted = expressions.subList(0, sortedExpr);
+    _toSort = expressions.subList(sortedExpr, numOrderByExpressions);
+
+    _expressionsMetadata = new TransformResultMetadata[_expressions.size()];
+    for (int i = 0; i < _expressionsMetadata.length; i++) {
+      ExpressionContext expression = _expressions.get(i);
+      _expressionsMetadata[i] = _transformOperator.getResultMetadata(expression);
+    }
+
+    _numRowsToKeep = queryContext.getOffset() + queryContext.getLimit();
+
+    if (_toSort.isEmpty()) {
+      int expectedSize = Math.min(SelectionOperatorUtils.MAX_ROW_HOLDER_INITIAL_CAPACITY, _numRowsToKeep);
+      _listBuilder = new TotallySortedListBuilder(expectedSize);
+    } else {
+      int expectedSize = Math.min(SelectionOperatorUtils.MAX_ROW_HOLDER_INITIAL_CAPACITY, _numRowsToKeep * 2);
+
+      Comparator<Object[]> sortedComparator =
+          OrderByComparatorFactory.getComparator(_orderByExpressions, _expressionsMetadata, true, 0, sortedExpr);
+      Comparator<Object[]> unsortedComparator =
+          OrderByComparatorFactory.getComparator(_orderByExpressions, _expressionsMetadata, true, sortedExpr,
+              numOrderByExpressions);
+      _listBuilder = new PartiallySortedListBuilder(expectedSize, sortedComparator, unsortedComparator);
+    }
+
+    _comparator = OrderByComparatorFactory.getComparator(_orderByExpressions, _expressionsMetadata, false);
+  }
+
+  @Override
+  public IndexSegment getIndexSegment() {
+    return _indexSegment;
+  }
+
+  @Override
+  public ExecutionStatistics getExecutionStatistics() {
+    long numEntriesScannedInFilter = _transformOperator.getExecutionStatistics().getNumEntriesScannedInFilter();
+    int numTotalDocs = _indexSegment.getSegmentMetadata().getTotalDocs();
+    return new ExecutionStatistics(getNumDocsScanned(), numEntriesScannedInFilter, getNumEntriesScannedPostFilter(),
+        numTotalDocs);
+  }
+
+  protected RowBasedBlockValueFetcher fetchBlock(TransformBlock transformBlock, BlockValSet[] blockValSets) {
+    int numExpressions = _expressions.size();
+
+    for (int i = 0; i < numExpressions; i++) {
+      ExpressionContext expression = _expressions.get(i);
+      blockValSets[i] = transformBlock.getBlockValueSet(expression);
+    }
+    return new RowBasedBlockValueFetcher(blockValSets);
+  }
+
+  protected abstract long getNumEntriesScannedPostFilter();
+
+  protected abstract int getNumDocsScanned();
+
+  /**
+   * Modifies the given {@link ListBuilder} adding rows in an order compatible with the constructor used until the
+   * implementation considers that no more rows need to be added.
+   */
+  protected abstract void fetch(ListBuilder listBuilder);
+
+  @Override
+  public List<Operator> getChildOperators() {
+    return Collections.singletonList(_transformOperator);
+  }
+
+  protected abstract String getExplainName();
+
+  @Override
+  public String toExplainString() {
+    StringBuilder sb = new StringBuilder(getExplainName());
+
+    sb.append("(sortedList: ");
+    concatList(sb, _alreadySorted);
+
+    sb.append(", unsortedList: ");
+    concatList(sb, _toSort);
+
+    sb.append(", rest: ");
+    concatList(sb, _expressions.subList(_alreadySorted.size() + _toSort.size(), _expressions.size()));
+
+    sb.append(')');
+    return sb.toString();
+  }
+
+  private void concatList(StringBuilder sb, List<?> list) {
+    sb.append('(');
+    Iterator<?> it = list.iterator();
+    if (it.hasNext()) {
+      sb.append(it.next());
+      while (it.hasNext()) {
+        sb.append(", ").append(it.next());
+      }
+    }
+    sb.append(')');
+  }
+
+  @Override
+  protected IntermediateResultsBlock getNextBlock() {
+    Preconditions.checkState(!_used, "nextBlock was called more than once");
+    _used = true;
+    fetch(_listBuilder);
+
+    DataSchema dataSchema = createDataSchema();
+
+    List<Object[]> list = _listBuilder.build();
+    if (list.size() > _numRowsToKeep) {
+      list = new ArrayList<>(list.subList(0, _numRowsToKeep));
+    }
+
+    return new IntermediateResultsBlock.ListSelection(dataSchema, list, _comparator);
+  }
+
+  protected DataSchema createDataSchema() {
+    int numExpressions = _expressions.size();
+
+    // Create the data schema
+    String[] columnNames = new String[numExpressions];
+    DataSchema.ColumnDataType[] columnDataTypes = new DataSchema.ColumnDataType[numExpressions];
+    for (int i = 0; i < columnNames.length; i++) {
+      columnNames[i] = _expressions.get(i).toString();
+    }
+    for (int i = 0; i < numExpressions; i++) {
+      TransformResultMetadata expressionMetadata = _expressionsMetadata[i];
+      columnDataTypes[i] =
+          DataSchema.ColumnDataType.fromDataType(expressionMetadata.getDataType(), expressionMetadata.isSingleValue());
+    }
+    return new DataSchema(columnNames, columnDataTypes);
+  }
+
+  /**
+   * A private class used to build a sorted list by adding partially sorted data.
+   *
+   * Specifically, this class has been designed to receive successive calls to {@link #add(Object[])} follow by a single
+   * call to {@link #build()}. Once this method is called, the behavior of this object is undefined and therefore it
+   * should not be used.
+   *
+   * Rows must be inserted in ascending order accordingly to the partial order specified by a comparator.
+   * This comparator will define <i>partitions</i> of rows. All the rows in the same partition same are considered equal
+   * by that comparator.
+   *
+   * Some implementations, like {@link PartiallySortedListBuilder} accepts a second comparator that is used to sort rows
+   * inside each partition.
+   * When calling {@link #add(Object[])} with a row that doesn't belong to the current partition, a new one is started
+   * and the previous one is sorted. Therefore, this object maintains the invariant that at any moment there are at
+   * least {@link #sortedSize()} elements that are completely sorted, which means that no matter which elements are
+   * added after that, these elements are going to be smallest.
+   */
+  protected interface ListBuilder {
+
+    /**
+     * Adds the given row to this object. The new column must be equal or higher than the partition comparator.
+     *
+     * @param row The row to add. The values of the already sorted columns must be equal or higher than the last added
+     *           row, if any.
+     * @return true if and only if the previous partition was closed.
+     */
+    boolean add(Object[] row);
+
+    /**
+     * Builds the sorted list. The returned list will be sorted, even if a previous call t o {@link #sortedSize()}
+     * returned a number lower than the number of elements that have been added.
+     *
+     * Once this method is called, the builder should not be used. There is no guaranteed on whether
+     * {@link #sortedSize()} is updated or not.
+     */
+    List<Object[]> build();
+
+    /**
+     * How many elements are actually sorted. This number is lower or equal to the number of elements that has been
+     * added.
+     */
+    int sortedSize();
+  }
+
+  /**
+   * This is the faster {@link ListBuilder} but also the most restrictive one. It can only be used when data is inserted
+   * in total order. Therefore it cannot be used to implement order-by queries where there is at least one expression
+   * that is not sorted. In such case {@link PartiallySortedListBuilder} should be used.
+   *
+   * This implementation is just a wrapper over an ArrayList and therefore the average costs of its methods is constant.
+   */
+  protected static class TotallySortedListBuilder implements ListBuilder {
+    private final ArrayList<Object[]> _list;
+
+    public TotallySortedListBuilder(int expectedSize) {
+      _list = new ArrayList<>(expectedSize);
+    }
+
+    @Override
+    public boolean add(Object[] row) {
+      _list.add(row);
+      return true;
+    }
+
+    @Override
+    public List<Object[]> build() {
+      return _list;
+    }
+
+    @Override
+    public int sortedSize() {
+      return _list.size();
+    }
+  }
+
+  /**
+   * This is the more versatile {@link ListBuilder} that requires two comparators: The first defines the order on which
+   * {@link #add(Object[])} is called and defines the partitions. The second one is used to sort rows in the same
+   * paritition. This class can be used to implement order-by queries that include one or more not sorted expressions.
+   * In cases where all expressions are sorted, {@link TotallySortedListBuilder} should be used because its performance
+   * is better.
+   *
+   * In this implementation the {@link #add(Object[])} method has a log(P) cost, where P is the number of elements in
+   * each partition. In normal cases we can consider P a constant. In some degenerated cases like having an ordering by
+   * a sorted column whose values are all equal, P may tend to the number of elements in the segment, which would make
+   * the cost of this method log(N).
+   */
+  private static class PartiallySortedListBuilder implements ListBuilder {
+    private final ArrayList<Object[]> _rows;
+    /**
+     * The comparator that defines the partitions and the one that impose in which order add has to be called.
+     */
+    private final Comparator<Object[]> _partitionComparator;
+    /**
+     * The comparator that sorts different rows on each partition.
+     */
+    private final Comparator<Object[]> _unsortedComparator;
+    @Nullable
+    private Object[] _lastPartitionRow;
+    /**
+     * The index where the current (and still not sorted) partition starts.
+     */
+    private int _lastSorted;
+
+    public PartiallySortedListBuilder(int expectedSize, Comparator<Object[]> partitionComparator,
+        Comparator<Object[]> unsortedComparator) {
+      _rows = new ArrayList<>(expectedSize);
+      _partitionComparator = partitionComparator;
+      _unsortedComparator = unsortedComparator;
+    }
+
+    @Override
+    public boolean add(Object[] row) {
+      boolean result;
+      if (_lastPartitionRow == null) {
+        _lastSorted = 0;
+        _lastPartitionRow = row;
+        result = false;
+      } else {
+        int cmp = _partitionComparator.compare(row, _lastPartitionRow);
+        if (cmp < 0) {
+          throw new IllegalArgumentException("Row " + Arrays.toString(row) + " is lower than previously added row"
+              + Arrays.toString(_lastPartitionRow));
+        }
+        if (cmp > 0) {

Review Comment:
   It would make the code a little bit slower, but what you say makes sense. I'm gonna change it



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] Jackie-Jiang commented on a diff in pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
Jackie-Jiang commented on code in PR #8979:
URL: https://github.com/apache/pinot/pull/8979#discussion_r959834727


##########
pinot-core/src/main/java/org/apache/pinot/core/common/NullableRowBasedBlockValueFetcher.java:
##########
@@ -0,0 +1,53 @@
+/**
+ * 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.pinot.core.common;
+
+import org.roaringbitmap.RoaringBitmap;
+
+
+public class NullableRowBasedBlockValueFetcher extends RowBasedBlockValueFetcher {

Review Comment:
   I see your point. The reason why I checked all the existing usage of `RowBasedBlockValueFetcher` and put this comment is that currently we are using 2 ways to read the rows in selection operators: the original usage always read the non-null values and handle the null values on the caller side; the new usage directly read the null values. I see the value of adding this new fetcher, but the inconsistent usage among selection operators can cause confusion, and potentially inconsistent performance.
   
   I'd suggest having a separate PR just for this change since it is not closely related to the purpose for this PR. All the usage of the `RowBasedBlockValueFetcher` should be consistent: handle null values within the fetcher.
   
   Regarding whether to have a boolean flag or a separate class, I don't have strong preference, but when null handling is enabled, we might end up switching between the 2 implementations based on whether the nullbitmap is empty.



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] gortiz commented on a diff in pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
gortiz commented on code in PR #8979:
URL: https://github.com/apache/pinot/pull/8979#discussion_r982188923


##########
pinot-core/src/main/java/org/apache/pinot/core/operator/query/LinearSelectionOrderByOperator.java:
##########
@@ -0,0 +1,476 @@
+/**
+ * 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.pinot.core.operator.query;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+import java.util.PriorityQueue;
+import java.util.function.IntFunction;
+import java.util.function.Supplier;
+import javax.annotation.Nullable;
+import org.apache.pinot.common.request.context.ExpressionContext;
+import org.apache.pinot.common.request.context.OrderByExpressionContext;
+import org.apache.pinot.common.utils.DataSchema;
+import org.apache.pinot.core.common.BlockValSet;
+import org.apache.pinot.core.common.Operator;
+import org.apache.pinot.core.common.RowBasedBlockValueFetcher;
+import org.apache.pinot.core.operator.BaseOperator;
+import org.apache.pinot.core.operator.ExecutionStatistics;
+import org.apache.pinot.core.operator.blocks.TransformBlock;
+import org.apache.pinot.core.operator.blocks.results.SelectionResultsBlock;
+import org.apache.pinot.core.operator.transform.TransformOperator;
+import org.apache.pinot.core.operator.transform.TransformResultMetadata;
+import org.apache.pinot.core.query.request.context.QueryContext;
+import org.apache.pinot.core.query.selection.SelectionOperatorUtils;
+import org.apache.pinot.segment.spi.IndexSegment;
+import org.roaringbitmap.RoaringBitmap;
+
+
+/**
+ * A selection Operator used when the first expressions in the order by are identifier expressions of columns that are
+ * already sorted (either ascendingly or descendingly), even if the tail of order by expressions are not sorted.
+ *
+ * ie: SELECT ... FROM Table WHERE predicates ORDER BY sorted_column DESC LIMIT 10 OFFSET 5
+ * or: SELECT ... FROM Table WHERE predicates ORDER BY sorted_column, not_sorted LIMIT 10 OFFSET 5
+ * but not SELECT ... FROM Table WHERE predicates ORDER BY not_sorted, sorted_column LIMIT 10 OFFSET 5
+ *
+ * Operators that derives from this class are going to have an almost linear cost instead of the usual NlogN when actual
+ * sorting must be done, where N is the number of rows in the segment.
+ * There is a degraded scenario when the cost is actually NlogL (where L is the limit of the query) when all the first L
+ * rows have the exact same value for the prefix of the sorted columns. Even in that case, L should be quite smaller
+ * than N, so this implementation is algorithmically better than the normal solution.
+ */
+public abstract class LinearSelectionOrderByOperator extends BaseOperator<SelectionResultsBlock> {
+  protected final IndexSegment _indexSegment;
+
+  protected final boolean _nullHandlingEnabled;
+  // Deduped order-by expressions followed by output expressions from SelectionOperatorUtils.extractExpressions()
+  protected final List<ExpressionContext> _expressions;
+  protected final List<ExpressionContext> _alreadySorted;
+  protected final List<ExpressionContext> _toSort;
+
+  protected final TransformOperator _transformOperator;
+  protected final List<OrderByExpressionContext> _orderByExpressions;
+  protected final TransformResultMetadata[] _expressionsMetadata;
+  protected final int _numRowsToKeep;
+  private final Supplier<ListBuilder> _listBuilderSupplier;
+  protected boolean _used = false;
+  protected Comparator<Object[]> _comparator;
+
+  /**
+   *
+   * @param expressions order by expressions must be at the head of the list.
+   * @param sortedExpr How many expressions at the head of the expression list are going to be considered sorted by
+   * {@link #fetch(Supplier<ListBuilder>)}
+   */
+  public LinearSelectionOrderByOperator(IndexSegment indexSegment, QueryContext queryContext,
+      List<ExpressionContext> expressions, TransformOperator transformOperator,
+      int sortedExpr) {
+    _indexSegment = indexSegment;
+    _nullHandlingEnabled = queryContext.isNullHandlingEnabled();
+    _expressions = expressions;
+    _transformOperator = transformOperator;
+
+    _orderByExpressions = queryContext.getOrderByExpressions();
+    assert _orderByExpressions != null;
+    int numOrderByExpressions = _orderByExpressions.size();
+
+    _alreadySorted = expressions.subList(0, sortedExpr);
+    _toSort = expressions.subList(sortedExpr, numOrderByExpressions);
+
+    _expressionsMetadata = new TransformResultMetadata[_expressions.size()];
+    for (int i = 0; i < _expressionsMetadata.length; i++) {
+      ExpressionContext expression = _expressions.get(i);
+      _expressionsMetadata[i] = _transformOperator.getResultMetadata(expression);
+    }
+
+    _numRowsToKeep = queryContext.getOffset() + queryContext.getLimit();
+
+    if (_toSort.isEmpty()) {
+      int expectedSize = Math.min(SelectionOperatorUtils.MAX_ROW_HOLDER_INITIAL_CAPACITY, _numRowsToKeep);
+      _listBuilderSupplier = () -> new TotallySortedListBuilder(expectedSize);
+    } else {
+      int maxSize = Math.min(SelectionOperatorUtils.MAX_ROW_HOLDER_INITIAL_CAPACITY, _numRowsToKeep * 2);
+
+      Comparator<Object[]> sortedComparator = OrderByComparatorFactory.getComparator(_orderByExpressions,
+          _expressionsMetadata, true, _nullHandlingEnabled, 0, sortedExpr);
+      Comparator<Object[]> unsortedComparator = OrderByComparatorFactory.getComparator(_orderByExpressions,
+          _expressionsMetadata, true, _nullHandlingEnabled, sortedExpr, numOrderByExpressions);
+      _listBuilderSupplier = () -> new PartiallySortedListBuilder(maxSize, sortedComparator, unsortedComparator);
+    }
+
+    _comparator =
+        OrderByComparatorFactory.getComparator(_orderByExpressions, _expressionsMetadata, false, _nullHandlingEnabled);
+  }
+
+  @Override
+  public IndexSegment getIndexSegment() {
+    return _indexSegment;
+  }
+
+  @Override
+  public ExecutionStatistics getExecutionStatistics() {
+    long numEntriesScannedInFilter = _transformOperator.getExecutionStatistics().getNumEntriesScannedInFilter();
+    int numTotalDocs = _indexSegment.getSegmentMetadata().getTotalDocs();
+    return new ExecutionStatistics(getNumDocsScanned(), numEntriesScannedInFilter, getNumEntriesScannedPostFilter(),
+        numTotalDocs);
+  }
+
+  protected IntFunction<Object[]> fetchBlock(TransformBlock transformBlock, BlockValSet[] blockValSets) {
+    int numExpressions = _expressions.size();
+
+    for (int i = 0; i < numExpressions; i++) {
+      ExpressionContext expression = _expressions.get(i);
+      blockValSets[i] = transformBlock.getBlockValueSet(expression);
+    }
+    RowBasedBlockValueFetcher blockValueFetcher = new RowBasedBlockValueFetcher(blockValSets);
+
+    if (!_nullHandlingEnabled) {
+      return blockValueFetcher::getRow;
+    }
+    RoaringBitmap[] nullBitmaps = new RoaringBitmap[numExpressions];
+    for (int i = 0; i < numExpressions; i++) {
+      nullBitmaps[i] = blockValSets[i].getNullBitmap();
+    }
+    return (docId) -> {
+      Object[] row = blockValueFetcher.getRow(docId);
+      for (int colId = 0; colId < nullBitmaps.length; colId++) {
+        if (nullBitmaps[colId] != null && nullBitmaps[colId].contains(docId)) {
+          row[colId] = null;
+        }
+      }
+      return row;
+    };
+  }
+
+  protected abstract long getNumEntriesScannedPostFilter();
+
+  protected abstract int getNumDocsScanned();
+
+  /**
+   * Returns a list of rows sorted that:
+   * <ul>
+   *   <li>At least contains all the rows that fulfill the predicate</li>
+   *   <li>Rows are sorted in a way that is compatible with the given list builder supplier</li>
+   * </ul>
+   *
+   * That means that the result may contain more rows than required.
+   *
+   * @param listBuilderSupplier a {@link ListBuilder} supplier that should be used to create the result. Each time is
+   *                            called a new {@link ListBuilder} will be returned. All returned instances use the same
+   *                            comparator logic.
+   */
+  protected abstract List<Object[]> fetch(Supplier<ListBuilder> listBuilderSupplier);
+
+  @Override
+  public List<Operator> getChildOperators() {
+    return Collections.singletonList(_transformOperator);
+  }
+
+  protected abstract String getExplainName();
+
+  @Override
+  public String toExplainString() {
+    StringBuilder sb = new StringBuilder(getExplainName());
+
+    sb.append("(sortedList: ");
+    concatList(sb, _alreadySorted);
+
+    sb.append(", unsortedList: ");
+    concatList(sb, _toSort);
+
+    sb.append(", rest: ");
+    concatList(sb, _expressions.subList(_alreadySorted.size() + _toSort.size(), _expressions.size()));
+
+    sb.append(')');
+    return sb.toString();
+  }
+
+  private void concatList(StringBuilder sb, List<?> list) {
+    sb.append('(');
+    Iterator<?> it = list.iterator();
+    if (it.hasNext()) {
+      sb.append(it.next());
+      while (it.hasNext()) {
+        sb.append(", ").append(it.next());
+      }
+    }
+    sb.append(')');
+  }
+
+  @Override
+  protected SelectionResultsBlock getNextBlock() {
+    Preconditions.checkState(!_used, "nextBlock was called more than once");
+    _used = true;
+    List<Object[]> list = fetch(_listBuilderSupplier);
+
+    DataSchema dataSchema = createDataSchema();
+
+    if (list.size() > _numRowsToKeep) {
+      list = new ArrayList<>(list.subList(0, _numRowsToKeep));
+    }
+
+    SelectionResultsBlock resultsBlock = new SelectionResultsBlock(dataSchema, list, _comparator);
+
+    return resultsBlock;
+  }
+
+  protected DataSchema createDataSchema() {
+    int numExpressions = _expressions.size();
+
+    // Create the data schema
+    String[] columnNames = new String[numExpressions];
+    DataSchema.ColumnDataType[] columnDataTypes = new DataSchema.ColumnDataType[numExpressions];
+    for (int i = 0; i < columnNames.length; i++) {
+      columnNames[i] = _expressions.get(i).toString();
+    }
+    for (int i = 0; i < numExpressions; i++) {
+      TransformResultMetadata expressionMetadata = _expressionsMetadata[i];
+      columnDataTypes[i] =
+          DataSchema.ColumnDataType.fromDataType(expressionMetadata.getDataType(), expressionMetadata.isSingleValue());
+    }
+    return new DataSchema(columnNames, columnDataTypes);
+  }
+
+  /**
+   * A private class used to build a sorted list by adding partially sorted data.
+   *
+   * Specifically, this class has been designed to receive successive calls to {@link #add(Object[])} follow by a single
+   * call to {@link #build()}. Once this method is called, the behavior of this object is undefined and therefore it
+   * should not be used.
+   *
+   * Rows must be inserted in ascending order accordingly to the partial order specified by a comparator.
+   * This comparator will define <i>partitions</i> of rows. All the rows in the same partition same are considered equal
+   * by that comparator.
+   *
+   * Some implementations, like {@link PartiallySortedListBuilder} accepts a second comparator that is used to sort rows
+   * inside each partition.
+   * When calling {@link #add(Object[])} with a row that doesn't belong to the current partition, a new one is started
+   * and the previous one is sorted. Therefore, this object maintains the invariant that at any moment there are at
+   * least {@link #sortedSize()} elements that are completely sorted, which means that no matter which elements are
+   * added after that, these elements are going to be smallest.
+   */
+  protected interface ListBuilder {
+
+    /**
+     * Adds the given row to this object. The new column must be equal or higher than the partition comparator.
+     *
+     * @param row The row to add. The values of the already sorted columns must be equal or higher than the last added
+     *           row, if any.
+     * @return true if and only if the previous partition was closed.
+     */
+    boolean add(Object[] row);
+
+    /**
+     * Builds the sorted list. The returned list will be sorted, even if a previous call t o {@link #sortedSize()}
+     * returned a number lower than the number of elements that have been added.
+     *
+     * Once this method is called, the builder should not be used. There is no guaranteed on whether
+     * {@link #sortedSize()} is updated or not.
+     */
+    List<Object[]> build();
+
+    /**
+     * How many elements are actually sorted. This number is lower or equal to the number of elements that has been
+     * added.
+     */
+    int sortedSize();
+  }
+
+  /**
+   * This is the faster {@link ListBuilder} but also the most restrictive one. It can only be used when data is inserted
+   * in total order. Therefore it cannot be used to implement order-by queries where there is at least one expression
+   * that is not sorted. In such case {@link PartiallySortedListBuilder} should be used.
+   *
+   * This implementation is just a wrapper over an ArrayList and therefore the average costs of its methods is constant.
+   */
+  protected static class TotallySortedListBuilder implements ListBuilder {
+    private final ArrayList<Object[]> _list;
+
+    public TotallySortedListBuilder(int expectedSize) {
+      _list = new ArrayList<>(expectedSize);
+    }
+
+    @Override
+    public boolean add(Object[] row) {
+      _list.add(row);
+      return true;
+    }
+
+    @Override
+    public List<Object[]> build() {
+      return _list;
+    }
+
+    @Override
+    public int sortedSize() {
+      return _list.size();
+    }
+  }
+
+  /**
+   * This is the more versatile {@link ListBuilder} that requires two comparators: The first defines the order on which
+   * {@link #add(Object[])} is called and defines the partitions. The second one is used to sort rows in the same
+   * partition. This class can be used to implement order-by queries that include one or more not sorted expressions.
+   * In cases where all expressions are sorted, {@link TotallySortedListBuilder} should be used because its performance
+   * is better.
+   *
+   * In this implementation the {@link #add(Object[])} method has a log(P) cost, where P is the number of elements in
+   * each partition. In normal cases we can consider P a constant. In some degenerated cases like having an ordering by
+   * a sorted column whose values are all equal, P may tend to the number of elements in the segment, which would make
+   * the cost of this method log(N).
+   *
+   * This class is optimized for scenarios where the partitions are smaller than the limit. In that case, the partition
+   * is only sorted once it is closed (aka when a new element for the other partition is found), so each insertion has
+   * an average cost of log(P) (where P-1 insertions are cost O(1) and the last one is O(PlogP)). In cases where at
+   * least one partition is larger than the limit, this implementation delegates the last partition to a
+   * {@link PriorityQueue}.
+   */
+  private static class PartiallySortedListBuilder implements ListBuilder {
+    private final ArrayList<Object[]> _rows;
+    /**
+     * The comparator that defines the partitions and the one that impose in which order add has to be called.
+     */
+    private final Comparator<Object[]> _partitionComparator;
+    /**
+     * The comparator that sorts different rows on each partition.
+     */
+    private final Comparator<Object[]> _unsortedComparator;
+    @Nullable
+    private Object[] _lastPartitionRow;
+    /**
+     * How many elements are already sorted. This is also the index where the last (and still not sorted) partition
+     * starts or should start.
+     */
+    private int _sortedPrefixSize;
+    private final int _maxSize;
+    private PriorityQueue<Object[]> _queue = null;
+    private int _maxPriorityQueueValues;
+
+    public PartiallySortedListBuilder(int maxSize, Comparator<Object[]> partitionComparator,
+        Comparator<Object[]> unsortedComparator) {
+      Preconditions.checkArgument(maxSize > 0, "Max size must be greater than 0");
+      _maxSize = maxSize;
+      _rows = new ArrayList<>(maxSize);
+      _partitionComparator = partitionComparator;
+      _unsortedComparator = unsortedComparator;
+    }
+
+    @Override
+    public boolean add(Object[] row) {
+      boolean result;
+      if (_lastPartitionRow == null) {
+        _sortedPrefixSize = 0;
+        _lastPartitionRow = row;
+        _rows.add(row);
+        return false;
+      } else {
+        int cmp = _partitionComparator.compare(row, _lastPartitionRow);
+        if (cmp < 0) {
+          throw new IllegalArgumentException("Row " + Arrays.toString(row) + " is lower than previously added row"
+              + Arrays.toString(_lastPartitionRow));
+        }
+
+        if (_queue != null) {
+          if (cmp > 0) {
+            // the new row is in a greater partition, just don't add it and continue
+            return true;
+          }
+          // otherwise they are equal by the already sorted columns. Let's check the other columns and evict the higher
+          // also, we have the higher value at the last position
+          SelectionOperatorUtils.addToPriorityQueue(row, _queue, _maxPriorityQueueValues);
+          return false;
+        } else {
+          if (_rows.size() == _maxSize) { // we already have _maxSize results
+            if (cmp > 0) {
+              // and the new one is higher, so we don't need to add it
+              sortLastPartition();
+              return true;
+            }
+            // and the new one may be smaller, so this is going to be the last partition and we need to prepare the
+            // priority queue
+            buildPriorityQueue();
+            SelectionOperatorUtils.addToPriorityQueue(row, _queue, _maxPriorityQueueValues);
+            return false;
+          }
+          if (cmp > 0) {
+            sortLastPartition();
+            _lastPartitionRow = row;
+            result = true;
+          } else {
+            result = false;
+          }
+          _rows.add(row);
+          return result;
+        }
+      }
+    }
+
+    private void buildPriorityQueue() {
+      _maxPriorityQueueValues = _maxSize - _sortedPrefixSize;
+      _queue = new PriorityQueue<>(_maxPriorityQueueValues, _unsortedComparator.reversed());
+      for (int i = 0; i < _maxPriorityQueueValues; i++) {
+        int lastIdx = _rows.size() - 1;
+        _queue.add(_rows.get(lastIdx));
+        _rows.remove(lastIdx);
+      }
+    }
+
+    void sortLastPartition() {

Review Comment:
   So your idea is that `ListBuilder.build()` invariant should be that elements are ordered by partition, but not by the not already sorted columns. In the current implementation, I think that makes sense. I'm going to change it.
   
   But I think we should think at longer term. My original idea was more ambitious than that. The idea was to sort each block in the map phase (therefore in parallel) so the reduce/combine phase (that is called by a single thread) should have a linear cost. Also, by applying the sorting in the map phase we can use the local knowledge derived from sorted columns and make the comparison faster by ignoring the fields that are already sorted in the partition.
   
   
   
   



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] gortiz commented on a diff in pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
gortiz commented on code in PR #8979:
URL: https://github.com/apache/pinot/pull/8979#discussion_r982646456


##########
pinot-core/src/main/java/org/apache/pinot/core/plan/SelectionPlanNode.java:
##########
@@ -50,67 +56,152 @@ public Operator<SelectionResultsBlock> run() {
     List<ExpressionContext> expressions = SelectionOperatorUtils.extractExpressions(_queryContext, _indexSegment);
     int limit = _queryContext.getLimit();
 
-    if (limit > 0) {
-      List<OrderByExpressionContext> orderByExpressions = _queryContext.getOrderByExpressions();
-      if (orderByExpressions == null) {
-        // Selection only
-        TransformOperator transformOperator = new TransformPlanNode(_indexSegment, _queryContext, expressions,
-            Math.min(limit, DocIdSetPlanNode.MAX_DOC_PER_CALL)).run();
-        return new SelectionOnlyOperator(_indexSegment, _queryContext, expressions, transformOperator);
-      } else {
-        // Selection order-by
-        if (isAllOrderByColumnsSorted(orderByExpressions)) {
-          // All order-by columns are sorted, no need to sort the records
-          TransformOperator transformOperator = new TransformPlanNode(_indexSegment, _queryContext, expressions,
-              Math.min(limit + _queryContext.getOffset(), DocIdSetPlanNode.MAX_DOC_PER_CALL)).run();
-          return new SelectionOrderByOperator(_indexSegment, _queryContext, expressions, transformOperator, true);
-        } else if (orderByExpressions.size() == expressions.size()) {
-          // All output expressions are ordered
-          TransformOperator transformOperator =
-              new TransformPlanNode(_indexSegment, _queryContext, expressions, DocIdSetPlanNode.MAX_DOC_PER_CALL).run();
-          return new SelectionOrderByOperator(_indexSegment, _queryContext, expressions, transformOperator, false);
-        } else {
-          // Not all output expressions are ordered, only fetch the order-by expressions and docId to avoid the
-          // unnecessary data fetch
-          List<ExpressionContext> expressionsToTransform = new ArrayList<>(orderByExpressions.size());
-          for (OrderByExpressionContext orderByExpression : orderByExpressions) {
-            expressionsToTransform.add(orderByExpression.getExpression());
-          }
-          TransformOperator transformOperator =
-              new TransformPlanNode(_indexSegment, _queryContext, expressionsToTransform,
-                  DocIdSetPlanNode.MAX_DOC_PER_CALL).run();
-          return new SelectionOrderByOperator(_indexSegment, _queryContext, expressions, transformOperator, false);
-        }
-      }
-    } else {
+    if (limit == 0) {
       // Empty selection (LIMIT 0)
       TransformOperator transformOperator = new TransformPlanNode(_indexSegment, _queryContext, expressions, 0).run();
       return new EmptySelectionOperator(_indexSegment, expressions, transformOperator);
     }
+    List<OrderByExpressionContext> orderByExpressions = _queryContext.getOrderByExpressions();
+    if (orderByExpressions == null) {
+      // Selection only
+      // ie: SELECT ... FROM Table WHERE ... LIMIT 10
+      int maxDocsPerCall = Math.min(limit, DocIdSetPlanNode.MAX_DOC_PER_CALL);
+      TransformPlanNode planNode = new TransformPlanNode(_indexSegment, _queryContext, expressions, maxDocsPerCall);
+      TransformOperator transformOperator = planNode.run();
+
+      return new SelectionOnlyOperator(_indexSegment, _queryContext, expressions, transformOperator);
+    }
+    int numOrderByExpressions = orderByExpressions.size();
+    // Although it is a break of abstraction, some code, specially merging, assumes that if there is an order by
+    // expression the operator will return a block whose selection result is a priority queue.
+    int sortedColumnsPrefixSize = getSortedColumnsPrefix(orderByExpressions, _queryContext.isNullHandlingEnabled());
+    OrderByAlgorithm orderByAlgorithm = OrderByAlgorithm.fromQueryContext(_queryContext);
+    if (sortedColumnsPrefixSize > 0 && orderByAlgorithm != OrderByAlgorithm.NAIVE) {
+      int maxDocsPerCall = DocIdSetPlanNode.MAX_DOC_PER_CALL;
+      // The first order by expressions are sorted (either asc or desc).
+      // ie: SELECT ... FROM Table WHERE predicates ORDER BY sorted_column DESC LIMIT 10 OFFSET 5
+      // or: SELECT ... FROM Table WHERE predicates ORDER BY sorted_column, not_sorted LIMIT 10 OFFSET 5
+      // but not SELECT ... FROM Table WHERE predicates ORDER BY not_sorted, sorted_column LIMIT 10 OFFSET 5
+      if (orderByExpressions.get(0).isAsc()) {
+        if (sortedColumnsPrefixSize == orderByExpressions.size()) {
+          maxDocsPerCall = Math.min(limit + _queryContext.getOffset(), DocIdSetPlanNode.MAX_DOC_PER_CALL);
+        }
+        TransformPlanNode planNode = new TransformPlanNode(_indexSegment, _queryContext, expressions, maxDocsPerCall);
+        TransformOperator transformOperator = planNode.run();
+        return new SelectionPartiallyOrderedByAscOperator(_indexSegment, _queryContext, expressions,
+            transformOperator, sortedColumnsPrefixSize);
+      } else {
+        TransformPlanNode planNode = new TransformPlanNode(_indexSegment, _queryContext, expressions, maxDocsPerCall);
+        TransformOperator transformOperator = planNode.run();
+        return new SelectionPartiallyOrderedByDescOperation(_indexSegment, _queryContext, expressions,
+            transformOperator, sortedColumnsPrefixSize);
+      }
+    }
+    if (numOrderByExpressions == expressions.size()) {
+      // All output expressions are ordered
+      // ie: SELECT not_sorted1, not_sorted2 FROM Table WHERE ... ORDER BY not_sorted1, not_sorted2 LIMIT 10 OFFSET 5
+      TransformOperator transformOperator =
+          new TransformPlanNode(_indexSegment, _queryContext, expressions, DocIdSetPlanNode.MAX_DOC_PER_CALL).run();
+      return new SelectionOrderByOperator(_indexSegment, _queryContext, expressions, transformOperator);
+    }
+    // Not all output expressions are ordered, only fetch the order-by expressions and docId to avoid the
+    // unnecessary data fetch
+    // ie: SELECT ... FROM Table WHERE ... ORDER BY not_sorted1, not_sorted2 LIMIT 10
+    List<ExpressionContext> expressionsToTransform = new ArrayList<>(numOrderByExpressions);
+    for (OrderByExpressionContext orderByExpression : orderByExpressions) {
+      expressionsToTransform.add(orderByExpression.getExpression());
+    }
+    TransformOperator transformOperator = new TransformPlanNode(_indexSegment, _queryContext, expressionsToTransform,
+        DocIdSetPlanNode.MAX_DOC_PER_CALL).run();
+    return new SelectionOrderByOperator(_indexSegment, _queryContext, expressions, transformOperator);
   }
 
   /**
-   *  This function checks whether all columns in order by clause are pre-sorted.
-   *  This is used to optimize order by limit clauses.
-   *  For eg:
-   *  A query like "select * from table order by col1, col2 limit 10"
-   *  will take all the n matching rows and add it to a priority queue of size 10.
-   *  This is nlogk operation which can be quite expensive for a large n.
-   *  In the above example, if the docs in the segment are already sorted by col1 and col2 then there is no need for
-   *  sorting at all (only limit is needed).
-   * @return true is all columns in order by clause are sorted . False otherwise
+   * This functions returns the number of expressions that are sorted by the implicit order in the index.
+   *
+   * This means that query that uses these expressions in its order by doesn't actually need to sort from 0 to the
+   * given number (excluded) of expressions, as they are returned in the correct order.
+   *
+   * This method supports ASC and DESC order and ensures that all prefix expressions follow the same order. For example,
+   * ORDER BY sorted_col1 ASC, sorted_col2 ASC and ORDER BY sorted_col1 DESC, sorted_col2 DESC will return 2 but
+   * ORDER BY sorted_col1 DESC, sorted_col2 ASC and ORDER BY sorted_col1 ASC, sorted_col2 DESC will return 1 while
+   * ORDER BY not_sorted, sorted_col1 will return 0 because the first column is not sorted.
+   *
+   * It doesn't make sense to add literal expressions in an order by expression, but if they are included, they are
+   * considered sorted and its ASC/DESC is ignored.
+   *
+   * @return the max number that guarantees that from the first expression to the returned number, the index is already
+   * sorted.
    */
-  private boolean isAllOrderByColumnsSorted(List<OrderByExpressionContext> orderByExpressions) {
-    for (OrderByExpressionContext orderByExpression : orderByExpressions) {
-      if (!(orderByExpression.getExpression().getType() == ExpressionContext.Type.IDENTIFIER)
-          || !orderByExpression.isAsc()) {
-        return false;
+  private int getSortedColumnsPrefix(List<OrderByExpressionContext> orderByExpressions, boolean isNullHandlingEnabled) {
+    boolean asc = orderByExpressions.get(0).isAsc();
+    for (int i = 0; i < orderByExpressions.size(); i++) {
+      if (!isSorted(orderByExpressions.get(i), asc, isNullHandlingEnabled)) {
+        return i;
       }
-      String column = orderByExpression.getExpression().getIdentifier();
-      if (!_indexSegment.getDataSource(column).getDataSourceMetadata().isSorted()) {
+    }
+    // If we reach here, all are sorted
+    return orderByExpressions.size();
+  }
+
+  private boolean isSorted(OrderByExpressionContext orderByExpression, boolean asc, boolean isNullHandlingEnabled) {
+    switch (orderByExpression.getExpression().getType()) {
+      case LITERAL: {
+        return true;
+      }
+      case IDENTIFIER: {
+        if (!orderByExpression.isAsc() == asc) {
+          return false;
+        }
+        String column = orderByExpression.getExpression().getIdentifier();
+        DataSource dataSource = _indexSegment.getDataSource(column);
+        // If there are null values, we cannot trust DataSourceMetadata.isSorted
+        if (isNullHandlingEnabled) {
+          NullValueVectorReader nullValueVector = dataSource.getNullValueVector();
+          if (nullValueVector != null && !nullValueVector.getNullBitmap().isEmpty()) {
+            return false;
+          }
+        }
+        return dataSource.getDataSourceMetadata().isSorted();
+      }
+      case FUNCTION: // we could optimize monotonically increasing functions
+      default: {
         return false;
       }
     }
-    return true;
+  }
+
+  public enum OrderByAlgorithm {
+    NAIVE("naive");
+
+    /**
+     * The public name of the algorithm. This name can be used by users to specify the algorithm to use. Therefore any
+     * change here must be backward compatible.
+     *
+     * @see #findByPublicName(String)
+     */
+    private final String _publicName;
+
+    OrderByAlgorithm(String publicName) {
+      _publicName = publicName;
+    }
+
+    @Nullable
+    public static OrderByAlgorithm findByPublicName(@Nullable String publicName) {
+      if (publicName == null || publicName.equals("null") || publicName.isEmpty()) {
+        return null;
+      }
+      for (OrderByAlgorithm value : OrderByAlgorithm.values()) {

Review Comment:
   But that doesn't let us change the name of the literals or add synonymous in the future. I like this pattern more, as it is easier to maintain in the future.
   
   But the idea of ignoring the case is nice. I'm going to add it.



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] gortiz commented on a diff in pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
gortiz commented on code in PR #8979:
URL: https://github.com/apache/pinot/pull/8979#discussion_r979763121


##########
pinot-core/src/main/java/org/apache/pinot/core/operator/combine/MinMaxValueBasedSelectionOrderByCombineOperator.java:
##########
@@ -211,30 +211,51 @@ protected void processSegments() {
           ((AcquireReleaseColumnsSegmentOperator) operator).release();
         }
       }
-      PriorityQueue<Object[]> selectionResult = (PriorityQueue<Object[]>) resultsBlock.getRows();
-      if (selectionResult != null && selectionResult.size() == _numRowsToKeep) {
-        // Segment result has enough rows, update the boundary value
-        assert selectionResult.peek() != null;
-        Comparable segmentBoundaryValue = (Comparable) selectionResult.peek()[0];
-        if (boundaryValue == null) {
-          boundaryValue = segmentBoundaryValue;
-        } else {
-          if (asc) {
-            if (segmentBoundaryValue.compareTo(boundaryValue) < 0) {
-              boundaryValue = segmentBoundaryValue;
-            }
-          } else {
-            if (segmentBoundaryValue.compareTo(boundaryValue) > 0) {
-              boundaryValue = segmentBoundaryValue;
-            }
-          }
-        }
+      Collection<Object[]> rows = resultsBlock.getRows();
+      if (rows != null && rows.size() >= _numRowsToKeep) {
+        boundaryValue = updateBoundaryValue(boundaryValue, extractBoundaryValue(rows), asc);
       }
       threadBoundaryValue = boundaryValue;
       _blockingQueue.offer(resultsBlock);
     }
   }
 
+  private Comparable extractBoundaryValue(Collection<Object[]> rows) {
+    if (rows instanceof PriorityQueue) {
+      PriorityQueue<Object[]> selectionResult = (PriorityQueue<Object[]>) rows;
+      assert selectionResult.peek() != null;
+      // at this point, priority queues are sorted in the inverse order
+      return (Comparable) selectionResult.peek()[0];
+    }
+    List<Object[]> selectionResult;
+    if (rows instanceof List) {
+      selectionResult = (List<Object[]>) rows;
+    } else {
+      LOGGER.warn("Selection result stored in an unexpected data structure of type {}. A copy is needed",

Review Comment:
   We are in the paranoid territory here but... most changes I can imagine (for example, adding a new operation that stores rows in a Set) wouldn't break in this situation. But both solutions (falling here or just logging) are not actually that good. What I'm going to do is to attack the cause of the problem and change `SelectionResultsBlock` to only support Lists and PriorityQueues. Therefore is some time in the future we add a new operation datatype, the type system will help us to note that some `SelectionResultsBlock` consumers may assume that rows cannot be of any Collection subclass



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] gortiz commented on a diff in pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
gortiz commented on code in PR #8979:
URL: https://github.com/apache/pinot/pull/8979#discussion_r980798180


##########
pinot-core/src/main/java/org/apache/pinot/core/operator/query/LinearSelectionOrderByOperator.java:
##########
@@ -0,0 +1,476 @@
+/**
+ * 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.pinot.core.operator.query;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+import java.util.PriorityQueue;
+import java.util.function.IntFunction;
+import java.util.function.Supplier;
+import javax.annotation.Nullable;
+import org.apache.pinot.common.request.context.ExpressionContext;
+import org.apache.pinot.common.request.context.OrderByExpressionContext;
+import org.apache.pinot.common.utils.DataSchema;
+import org.apache.pinot.core.common.BlockValSet;
+import org.apache.pinot.core.common.Operator;
+import org.apache.pinot.core.common.RowBasedBlockValueFetcher;
+import org.apache.pinot.core.operator.BaseOperator;
+import org.apache.pinot.core.operator.ExecutionStatistics;
+import org.apache.pinot.core.operator.blocks.TransformBlock;
+import org.apache.pinot.core.operator.blocks.results.SelectionResultsBlock;
+import org.apache.pinot.core.operator.transform.TransformOperator;
+import org.apache.pinot.core.operator.transform.TransformResultMetadata;
+import org.apache.pinot.core.query.request.context.QueryContext;
+import org.apache.pinot.core.query.selection.SelectionOperatorUtils;
+import org.apache.pinot.segment.spi.IndexSegment;
+import org.roaringbitmap.RoaringBitmap;
+
+
+/**
+ * A selection Operator used when the first expressions in the order by are identifier expressions of columns that are
+ * already sorted (either ascendingly or descendingly), even if the tail of order by expressions are not sorted.
+ *
+ * ie: SELECT ... FROM Table WHERE predicates ORDER BY sorted_column DESC LIMIT 10 OFFSET 5
+ * or: SELECT ... FROM Table WHERE predicates ORDER BY sorted_column, not_sorted LIMIT 10 OFFSET 5
+ * but not SELECT ... FROM Table WHERE predicates ORDER BY not_sorted, sorted_column LIMIT 10 OFFSET 5
+ *
+ * Operators that derives from this class are going to have an almost linear cost instead of the usual NlogN when actual
+ * sorting must be done, where N is the number of rows in the segment.
+ * There is a degraded scenario when the cost is actually NlogL (where L is the limit of the query) when all the first L
+ * rows have the exact same value for the prefix of the sorted columns. Even in that case, L should be quite smaller
+ * than N, so this implementation is algorithmically better than the normal solution.
+ */
+public abstract class LinearSelectionOrderByOperator extends BaseOperator<SelectionResultsBlock> {
+  protected final IndexSegment _indexSegment;
+
+  protected final boolean _nullHandlingEnabled;
+  // Deduped order-by expressions followed by output expressions from SelectionOperatorUtils.extractExpressions()
+  protected final List<ExpressionContext> _expressions;
+  protected final List<ExpressionContext> _alreadySorted;
+  protected final List<ExpressionContext> _toSort;
+
+  protected final TransformOperator _transformOperator;
+  protected final List<OrderByExpressionContext> _orderByExpressions;
+  protected final TransformResultMetadata[] _expressionsMetadata;
+  protected final int _numRowsToKeep;
+  private final Supplier<ListBuilder> _listBuilderSupplier;
+  protected boolean _used = false;
+  protected Comparator<Object[]> _comparator;
+
+  /**
+   *
+   * @param expressions order by expressions must be at the head of the list.
+   * @param sortedExpr How many expressions at the head of the expression list are going to be considered sorted by
+   * {@link #fetch(Supplier<ListBuilder>)}
+   */
+  public LinearSelectionOrderByOperator(IndexSegment indexSegment, QueryContext queryContext,
+      List<ExpressionContext> expressions, TransformOperator transformOperator,
+      int sortedExpr) {
+    _indexSegment = indexSegment;
+    _nullHandlingEnabled = queryContext.isNullHandlingEnabled();
+    _expressions = expressions;
+    _transformOperator = transformOperator;
+
+    _orderByExpressions = queryContext.getOrderByExpressions();
+    assert _orderByExpressions != null;
+    int numOrderByExpressions = _orderByExpressions.size();
+
+    _alreadySorted = expressions.subList(0, sortedExpr);
+    _toSort = expressions.subList(sortedExpr, numOrderByExpressions);
+
+    _expressionsMetadata = new TransformResultMetadata[_expressions.size()];
+    for (int i = 0; i < _expressionsMetadata.length; i++) {
+      ExpressionContext expression = _expressions.get(i);
+      _expressionsMetadata[i] = _transformOperator.getResultMetadata(expression);
+    }
+
+    _numRowsToKeep = queryContext.getOffset() + queryContext.getLimit();
+
+    if (_toSort.isEmpty()) {
+      int expectedSize = Math.min(SelectionOperatorUtils.MAX_ROW_HOLDER_INITIAL_CAPACITY, _numRowsToKeep);
+      _listBuilderSupplier = () -> new TotallySortedListBuilder(expectedSize);
+    } else {
+      int maxSize = Math.min(SelectionOperatorUtils.MAX_ROW_HOLDER_INITIAL_CAPACITY, _numRowsToKeep * 2);
+
+      Comparator<Object[]> sortedComparator = OrderByComparatorFactory.getComparator(_orderByExpressions,
+          _expressionsMetadata, true, _nullHandlingEnabled, 0, sortedExpr);
+      Comparator<Object[]> unsortedComparator = OrderByComparatorFactory.getComparator(_orderByExpressions,
+          _expressionsMetadata, true, _nullHandlingEnabled, sortedExpr, numOrderByExpressions);
+      _listBuilderSupplier = () -> new PartiallySortedListBuilder(maxSize, sortedComparator, unsortedComparator);
+    }
+
+    _comparator =
+        OrderByComparatorFactory.getComparator(_orderByExpressions, _expressionsMetadata, false, _nullHandlingEnabled);
+  }
+
+  @Override
+  public IndexSegment getIndexSegment() {
+    return _indexSegment;
+  }
+
+  @Override
+  public ExecutionStatistics getExecutionStatistics() {
+    long numEntriesScannedInFilter = _transformOperator.getExecutionStatistics().getNumEntriesScannedInFilter();
+    int numTotalDocs = _indexSegment.getSegmentMetadata().getTotalDocs();
+    return new ExecutionStatistics(getNumDocsScanned(), numEntriesScannedInFilter, getNumEntriesScannedPostFilter(),
+        numTotalDocs);
+  }
+
+  protected IntFunction<Object[]> fetchBlock(TransformBlock transformBlock, BlockValSet[] blockValSets) {
+    int numExpressions = _expressions.size();
+
+    for (int i = 0; i < numExpressions; i++) {
+      ExpressionContext expression = _expressions.get(i);
+      blockValSets[i] = transformBlock.getBlockValueSet(expression);
+    }
+    RowBasedBlockValueFetcher blockValueFetcher = new RowBasedBlockValueFetcher(blockValSets);
+
+    if (!_nullHandlingEnabled) {
+      return blockValueFetcher::getRow;
+    }
+    RoaringBitmap[] nullBitmaps = new RoaringBitmap[numExpressions];
+    for (int i = 0; i < numExpressions; i++) {
+      nullBitmaps[i] = blockValSets[i].getNullBitmap();
+    }
+    return (docId) -> {
+      Object[] row = blockValueFetcher.getRow(docId);
+      for (int colId = 0; colId < nullBitmaps.length; colId++) {
+        if (nullBitmaps[colId] != null && nullBitmaps[colId].contains(docId)) {
+          row[colId] = null;
+        }
+      }
+      return row;
+    };
+  }
+
+  protected abstract long getNumEntriesScannedPostFilter();
+
+  protected abstract int getNumDocsScanned();
+
+  /**
+   * Returns a list of rows sorted that:
+   * <ul>
+   *   <li>At least contains all the rows that fulfill the predicate</li>
+   *   <li>Rows are sorted in a way that is compatible with the given list builder supplier</li>
+   * </ul>
+   *
+   * That means that the result may contain more rows than required.
+   *
+   * @param listBuilderSupplier a {@link ListBuilder} supplier that should be used to create the result. Each time is
+   *                            called a new {@link ListBuilder} will be returned. All returned instances use the same
+   *                            comparator logic.
+   */
+  protected abstract List<Object[]> fetch(Supplier<ListBuilder> listBuilderSupplier);
+
+  @Override
+  public List<Operator> getChildOperators() {
+    return Collections.singletonList(_transformOperator);
+  }
+
+  protected abstract String getExplainName();
+
+  @Override
+  public String toExplainString() {
+    StringBuilder sb = new StringBuilder(getExplainName());
+
+    sb.append("(sortedList: ");
+    concatList(sb, _alreadySorted);
+
+    sb.append(", unsortedList: ");
+    concatList(sb, _toSort);
+
+    sb.append(", rest: ");
+    concatList(sb, _expressions.subList(_alreadySorted.size() + _toSort.size(), _expressions.size()));
+
+    sb.append(')');
+    return sb.toString();
+  }
+
+  private void concatList(StringBuilder sb, List<?> list) {
+    sb.append('(');
+    Iterator<?> it = list.iterator();
+    if (it.hasNext()) {
+      sb.append(it.next());
+      while (it.hasNext()) {
+        sb.append(", ").append(it.next());
+      }
+    }
+    sb.append(')');
+  }
+
+  @Override
+  protected SelectionResultsBlock getNextBlock() {
+    Preconditions.checkState(!_used, "nextBlock was called more than once");
+    _used = true;
+    List<Object[]> list = fetch(_listBuilderSupplier);
+
+    DataSchema dataSchema = createDataSchema();
+
+    if (list.size() > _numRowsToKeep) {
+      list = new ArrayList<>(list.subList(0, _numRowsToKeep));
+    }
+
+    SelectionResultsBlock resultsBlock = new SelectionResultsBlock(dataSchema, list, _comparator);
+
+    return resultsBlock;
+  }
+
+  protected DataSchema createDataSchema() {
+    int numExpressions = _expressions.size();
+
+    // Create the data schema
+    String[] columnNames = new String[numExpressions];
+    DataSchema.ColumnDataType[] columnDataTypes = new DataSchema.ColumnDataType[numExpressions];
+    for (int i = 0; i < columnNames.length; i++) {
+      columnNames[i] = _expressions.get(i).toString();
+    }
+    for (int i = 0; i < numExpressions; i++) {
+      TransformResultMetadata expressionMetadata = _expressionsMetadata[i];
+      columnDataTypes[i] =
+          DataSchema.ColumnDataType.fromDataType(expressionMetadata.getDataType(), expressionMetadata.isSingleValue());
+    }
+    return new DataSchema(columnNames, columnDataTypes);
+  }
+
+  /**
+   * A private class used to build a sorted list by adding partially sorted data.
+   *
+   * Specifically, this class has been designed to receive successive calls to {@link #add(Object[])} follow by a single
+   * call to {@link #build()}. Once this method is called, the behavior of this object is undefined and therefore it
+   * should not be used.
+   *
+   * Rows must be inserted in ascending order accordingly to the partial order specified by a comparator.
+   * This comparator will define <i>partitions</i> of rows. All the rows in the same partition same are considered equal
+   * by that comparator.
+   *
+   * Some implementations, like {@link PartiallySortedListBuilder} accepts a second comparator that is used to sort rows
+   * inside each partition.
+   * When calling {@link #add(Object[])} with a row that doesn't belong to the current partition, a new one is started
+   * and the previous one is sorted. Therefore, this object maintains the invariant that at any moment there are at
+   * least {@link #sortedSize()} elements that are completely sorted, which means that no matter which elements are
+   * added after that, these elements are going to be smallest.
+   */
+  protected interface ListBuilder {
+
+    /**
+     * Adds the given row to this object. The new column must be equal or higher than the partition comparator.
+     *
+     * @param row The row to add. The values of the already sorted columns must be equal or higher than the last added
+     *           row, if any.
+     * @return true if and only if the previous partition was closed.
+     */
+    boolean add(Object[] row);
+
+    /**
+     * Builds the sorted list. The returned list will be sorted, even if a previous call t o {@link #sortedSize()}
+     * returned a number lower than the number of elements that have been added.
+     *
+     * Once this method is called, the builder should not be used. There is no guaranteed on whether
+     * {@link #sortedSize()} is updated or not.
+     */
+    List<Object[]> build();
+
+    /**
+     * How many elements are actually sorted. This number is lower or equal to the number of elements that has been
+     * added.
+     */
+    int sortedSize();
+  }
+
+  /**
+   * This is the faster {@link ListBuilder} but also the most restrictive one. It can only be used when data is inserted
+   * in total order. Therefore it cannot be used to implement order-by queries where there is at least one expression
+   * that is not sorted. In such case {@link PartiallySortedListBuilder} should be used.
+   *
+   * This implementation is just a wrapper over an ArrayList and therefore the average costs of its methods is constant.
+   */
+  protected static class TotallySortedListBuilder implements ListBuilder {
+    private final ArrayList<Object[]> _list;
+
+    public TotallySortedListBuilder(int expectedSize) {
+      _list = new ArrayList<>(expectedSize);
+    }
+
+    @Override
+    public boolean add(Object[] row) {
+      _list.add(row);
+      return true;
+    }
+
+    @Override
+    public List<Object[]> build() {
+      return _list;
+    }
+
+    @Override
+    public int sortedSize() {
+      return _list.size();
+    }
+  }
+
+  /**
+   * This is the more versatile {@link ListBuilder} that requires two comparators: The first defines the order on which
+   * {@link #add(Object[])} is called and defines the partitions. The second one is used to sort rows in the same
+   * partition. This class can be used to implement order-by queries that include one or more not sorted expressions.
+   * In cases where all expressions are sorted, {@link TotallySortedListBuilder} should be used because its performance
+   * is better.
+   *
+   * In this implementation the {@link #add(Object[])} method has a log(P) cost, where P is the number of elements in
+   * each partition. In normal cases we can consider P a constant. In some degenerated cases like having an ordering by
+   * a sorted column whose values are all equal, P may tend to the number of elements in the segment, which would make
+   * the cost of this method log(N).
+   *
+   * This class is optimized for scenarios where the partitions are smaller than the limit. In that case, the partition
+   * is only sorted once it is closed (aka when a new element for the other partition is found), so each insertion has
+   * an average cost of log(P) (where P-1 insertions are cost O(1) and the last one is O(PlogP)). In cases where at
+   * least one partition is larger than the limit, this implementation delegates the last partition to a
+   * {@link PriorityQueue}.
+   */
+  private static class PartiallySortedListBuilder implements ListBuilder {
+    private final ArrayList<Object[]> _rows;
+    /**
+     * The comparator that defines the partitions and the one that impose in which order add has to be called.
+     */
+    private final Comparator<Object[]> _partitionComparator;
+    /**
+     * The comparator that sorts different rows on each partition.
+     */
+    private final Comparator<Object[]> _unsortedComparator;
+    @Nullable
+    private Object[] _lastPartitionRow;
+    /**
+     * How many elements are already sorted. This is also the index where the last (and still not sorted) partition
+     * starts or should start.
+     */
+    private int _sortedPrefixSize;
+    private final int _maxSize;
+    private PriorityQueue<Object[]> _queue = null;
+    private int _maxPriorityQueueValues;
+
+    public PartiallySortedListBuilder(int maxSize, Comparator<Object[]> partitionComparator,
+        Comparator<Object[]> unsortedComparator) {
+      Preconditions.checkArgument(maxSize > 0, "Max size must be greater than 0");
+      _maxSize = maxSize;
+      _rows = new ArrayList<>(maxSize);
+      _partitionComparator = partitionComparator;
+      _unsortedComparator = unsortedComparator;
+    }
+
+    @Override
+    public boolean add(Object[] row) {
+      boolean result;
+      if (_lastPartitionRow == null) {
+        _sortedPrefixSize = 0;
+        _lastPartitionRow = row;
+        _rows.add(row);
+        return false;
+      } else {
+        int cmp = _partitionComparator.compare(row, _lastPartitionRow);
+        if (cmp < 0) {
+          throw new IllegalArgumentException("Row " + Arrays.toString(row) + " is lower than previously added row"
+              + Arrays.toString(_lastPartitionRow));
+        }
+
+        if (_queue != null) {
+          if (cmp > 0) {
+            // the new row is in a greater partition, just don't add it and continue
+            return true;
+          }
+          // otherwise they are equal by the already sorted columns. Let's check the other columns and evict the higher
+          // also, we have the higher value at the last position
+          SelectionOperatorUtils.addToPriorityQueue(row, _queue, _maxPriorityQueueValues);
+          return false;
+        } else {
+          if (_rows.size() == _maxSize) { // we already have _maxSize results
+            if (cmp > 0) {
+              // and the new one is higher, so we don't need to add it
+              sortLastPartition();
+              return true;
+            }
+            // and the new one may be smaller, so this is going to be the last partition and we need to prepare the
+            // priority queue
+            buildPriorityQueue();
+            SelectionOperatorUtils.addToPriorityQueue(row, _queue, _maxPriorityQueueValues);
+            return false;
+          }
+          if (cmp > 0) {
+            sortLastPartition();
+            _lastPartitionRow = row;
+            result = true;
+          } else {
+            result = false;
+          }
+          _rows.add(row);
+          return result;
+        }
+      }
+    }
+
+    private void buildPriorityQueue() {
+      _maxPriorityQueueValues = _maxSize - _sortedPrefixSize;
+      _queue = new PriorityQueue<>(_maxPriorityQueueValues, _unsortedComparator.reversed());
+      for (int i = 0; i < _maxPriorityQueueValues; i++) {
+        int lastIdx = _rows.size() - 1;
+        _queue.add(_rows.get(lastIdx));
+        _rows.remove(lastIdx);
+      }
+    }
+
+    void sortLastPartition() {
+      int size = _rows.size();
+      if (_sortedPrefixSize != size) {
+        List<Object[]> lastsPartition = _rows.subList(_sortedPrefixSize, size);
+        lastsPartition.sort(_unsortedComparator);
+        _sortedPrefixSize = size;
+      }
+    }
+
+    /**
+     * Sorts the rows and returns the sorted list.
+     *
+     * This object should not be used once this method is called.
+     *
+     * @return the list of all added rows, sorted by {@link #_partitionComparator} and then by
+     * {@link #_unsortedComparator}
+     */
+    @Override
+    public List<Object[]> build() {
+      if (_queue != null) {
+        _rows.addAll(_queue);
+        // queue is sorted in the reverse order, so we need to reverse this partition

Review Comment:
   I don't get it. There is no PQ here. This method must return an ordered list. If it is later used in a PQ or not it is not a concern of this interface.



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] Jackie-Jiang commented on a diff in pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
Jackie-Jiang commented on code in PR #8979:
URL: https://github.com/apache/pinot/pull/8979#discussion_r981791568


##########
pinot-spi/src/main/java/org/apache/pinot/spi/utils/CommonConstants.java:
##########
@@ -287,6 +287,8 @@ public static class QueryOptionKey {
         public static final String ENABLE_NULL_HANDLING = "enableNullHandling";
         public static final String SERVER_RETURN_FINAL_RESULT = "serverReturnFinalResult";
 
+        public static final String ORDER_BY_ALGORITHM = "order-by-algorithm";

Review Comment:
   Can we keep the same key format (camel case): `orderByAlgorithm`



##########
pinot-core/src/main/java/org/apache/pinot/core/plan/SelectionPlanNode.java:
##########
@@ -50,67 +56,152 @@ public Operator<SelectionResultsBlock> run() {
     List<ExpressionContext> expressions = SelectionOperatorUtils.extractExpressions(_queryContext, _indexSegment);
     int limit = _queryContext.getLimit();
 
-    if (limit > 0) {
-      List<OrderByExpressionContext> orderByExpressions = _queryContext.getOrderByExpressions();
-      if (orderByExpressions == null) {
-        // Selection only
-        TransformOperator transformOperator = new TransformPlanNode(_indexSegment, _queryContext, expressions,
-            Math.min(limit, DocIdSetPlanNode.MAX_DOC_PER_CALL)).run();
-        return new SelectionOnlyOperator(_indexSegment, _queryContext, expressions, transformOperator);
-      } else {
-        // Selection order-by
-        if (isAllOrderByColumnsSorted(orderByExpressions)) {
-          // All order-by columns are sorted, no need to sort the records
-          TransformOperator transformOperator = new TransformPlanNode(_indexSegment, _queryContext, expressions,
-              Math.min(limit + _queryContext.getOffset(), DocIdSetPlanNode.MAX_DOC_PER_CALL)).run();
-          return new SelectionOrderByOperator(_indexSegment, _queryContext, expressions, transformOperator, true);
-        } else if (orderByExpressions.size() == expressions.size()) {
-          // All output expressions are ordered
-          TransformOperator transformOperator =
-              new TransformPlanNode(_indexSegment, _queryContext, expressions, DocIdSetPlanNode.MAX_DOC_PER_CALL).run();
-          return new SelectionOrderByOperator(_indexSegment, _queryContext, expressions, transformOperator, false);
-        } else {
-          // Not all output expressions are ordered, only fetch the order-by expressions and docId to avoid the
-          // unnecessary data fetch
-          List<ExpressionContext> expressionsToTransform = new ArrayList<>(orderByExpressions.size());
-          for (OrderByExpressionContext orderByExpression : orderByExpressions) {
-            expressionsToTransform.add(orderByExpression.getExpression());
-          }
-          TransformOperator transformOperator =
-              new TransformPlanNode(_indexSegment, _queryContext, expressionsToTransform,
-                  DocIdSetPlanNode.MAX_DOC_PER_CALL).run();
-          return new SelectionOrderByOperator(_indexSegment, _queryContext, expressions, transformOperator, false);
-        }
-      }
-    } else {
+    if (limit == 0) {
       // Empty selection (LIMIT 0)
       TransformOperator transformOperator = new TransformPlanNode(_indexSegment, _queryContext, expressions, 0).run();
       return new EmptySelectionOperator(_indexSegment, expressions, transformOperator);
     }
+    List<OrderByExpressionContext> orderByExpressions = _queryContext.getOrderByExpressions();
+    if (orderByExpressions == null) {
+      // Selection only
+      // ie: SELECT ... FROM Table WHERE ... LIMIT 10
+      int maxDocsPerCall = Math.min(limit, DocIdSetPlanNode.MAX_DOC_PER_CALL);
+      TransformPlanNode planNode = new TransformPlanNode(_indexSegment, _queryContext, expressions, maxDocsPerCall);
+      TransformOperator transformOperator = planNode.run();
+
+      return new SelectionOnlyOperator(_indexSegment, _queryContext, expressions, transformOperator);
+    }
+    int numOrderByExpressions = orderByExpressions.size();
+    // Although it is a break of abstraction, some code, specially merging, assumes that if there is an order by
+    // expression the operator will return a block whose selection result is a priority queue.
+    int sortedColumnsPrefixSize = getSortedColumnsPrefix(orderByExpressions, _queryContext.isNullHandlingEnabled());
+    OrderByAlgorithm orderByAlgorithm = OrderByAlgorithm.fromQueryContext(_queryContext);
+    if (sortedColumnsPrefixSize > 0 && orderByAlgorithm != OrderByAlgorithm.NAIVE) {
+      int maxDocsPerCall = DocIdSetPlanNode.MAX_DOC_PER_CALL;
+      // The first order by expressions are sorted (either asc or desc).
+      // ie: SELECT ... FROM Table WHERE predicates ORDER BY sorted_column DESC LIMIT 10 OFFSET 5
+      // or: SELECT ... FROM Table WHERE predicates ORDER BY sorted_column, not_sorted LIMIT 10 OFFSET 5
+      // but not SELECT ... FROM Table WHERE predicates ORDER BY not_sorted, sorted_column LIMIT 10 OFFSET 5
+      if (orderByExpressions.get(0).isAsc()) {
+        if (sortedColumnsPrefixSize == orderByExpressions.size()) {
+          maxDocsPerCall = Math.min(limit + _queryContext.getOffset(), DocIdSetPlanNode.MAX_DOC_PER_CALL);
+        }
+        TransformPlanNode planNode = new TransformPlanNode(_indexSegment, _queryContext, expressions, maxDocsPerCall);
+        TransformOperator transformOperator = planNode.run();
+        return new SelectionPartiallyOrderedByAscOperator(_indexSegment, _queryContext, expressions,
+            transformOperator, sortedColumnsPrefixSize);
+      } else {
+        TransformPlanNode planNode = new TransformPlanNode(_indexSegment, _queryContext, expressions, maxDocsPerCall);
+        TransformOperator transformOperator = planNode.run();
+        return new SelectionPartiallyOrderedByDescOperation(_indexSegment, _queryContext, expressions,
+            transformOperator, sortedColumnsPrefixSize);
+      }
+    }
+    if (numOrderByExpressions == expressions.size()) {
+      // All output expressions are ordered
+      // ie: SELECT not_sorted1, not_sorted2 FROM Table WHERE ... ORDER BY not_sorted1, not_sorted2 LIMIT 10 OFFSET 5
+      TransformOperator transformOperator =
+          new TransformPlanNode(_indexSegment, _queryContext, expressions, DocIdSetPlanNode.MAX_DOC_PER_CALL).run();
+      return new SelectionOrderByOperator(_indexSegment, _queryContext, expressions, transformOperator);
+    }
+    // Not all output expressions are ordered, only fetch the order-by expressions and docId to avoid the
+    // unnecessary data fetch
+    // ie: SELECT ... FROM Table WHERE ... ORDER BY not_sorted1, not_sorted2 LIMIT 10
+    List<ExpressionContext> expressionsToTransform = new ArrayList<>(numOrderByExpressions);
+    for (OrderByExpressionContext orderByExpression : orderByExpressions) {
+      expressionsToTransform.add(orderByExpression.getExpression());
+    }
+    TransformOperator transformOperator = new TransformPlanNode(_indexSegment, _queryContext, expressionsToTransform,
+        DocIdSetPlanNode.MAX_DOC_PER_CALL).run();
+    return new SelectionOrderByOperator(_indexSegment, _queryContext, expressions, transformOperator);
   }
 
   /**
-   *  This function checks whether all columns in order by clause are pre-sorted.
-   *  This is used to optimize order by limit clauses.
-   *  For eg:
-   *  A query like "select * from table order by col1, col2 limit 10"
-   *  will take all the n matching rows and add it to a priority queue of size 10.
-   *  This is nlogk operation which can be quite expensive for a large n.
-   *  In the above example, if the docs in the segment are already sorted by col1 and col2 then there is no need for
-   *  sorting at all (only limit is needed).
-   * @return true is all columns in order by clause are sorted . False otherwise
+   * This functions returns the number of expressions that are sorted by the implicit order in the index.
+   *
+   * This means that query that uses these expressions in its order by doesn't actually need to sort from 0 to the
+   * given number (excluded) of expressions, as they are returned in the correct order.
+   *
+   * This method supports ASC and DESC order and ensures that all prefix expressions follow the same order. For example,
+   * ORDER BY sorted_col1 ASC, sorted_col2 ASC and ORDER BY sorted_col1 DESC, sorted_col2 DESC will return 2 but
+   * ORDER BY sorted_col1 DESC, sorted_col2 ASC and ORDER BY sorted_col1 ASC, sorted_col2 DESC will return 1 while
+   * ORDER BY not_sorted, sorted_col1 will return 0 because the first column is not sorted.
+   *
+   * It doesn't make sense to add literal expressions in an order by expression, but if they are included, they are
+   * considered sorted and its ASC/DESC is ignored.
+   *
+   * @return the max number that guarantees that from the first expression to the returned number, the index is already
+   * sorted.
    */
-  private boolean isAllOrderByColumnsSorted(List<OrderByExpressionContext> orderByExpressions) {
-    for (OrderByExpressionContext orderByExpression : orderByExpressions) {
-      if (!(orderByExpression.getExpression().getType() == ExpressionContext.Type.IDENTIFIER)
-          || !orderByExpression.isAsc()) {
-        return false;
+  private int getSortedColumnsPrefix(List<OrderByExpressionContext> orderByExpressions, boolean isNullHandlingEnabled) {
+    boolean asc = orderByExpressions.get(0).isAsc();
+    for (int i = 0; i < orderByExpressions.size(); i++) {
+      if (!isSorted(orderByExpressions.get(i), asc, isNullHandlingEnabled)) {
+        return i;
       }
-      String column = orderByExpression.getExpression().getIdentifier();
-      if (!_indexSegment.getDataSource(column).getDataSourceMetadata().isSorted()) {
+    }
+    // If we reach here, all are sorted
+    return orderByExpressions.size();
+  }
+
+  private boolean isSorted(OrderByExpressionContext orderByExpression, boolean asc, boolean isNullHandlingEnabled) {
+    switch (orderByExpression.getExpression().getType()) {
+      case LITERAL: {
+        return true;
+      }
+      case IDENTIFIER: {
+        if (!orderByExpression.isAsc() == asc) {
+          return false;
+        }
+        String column = orderByExpression.getExpression().getIdentifier();
+        DataSource dataSource = _indexSegment.getDataSource(column);
+        // If there are null values, we cannot trust DataSourceMetadata.isSorted
+        if (isNullHandlingEnabled) {
+          NullValueVectorReader nullValueVector = dataSource.getNullValueVector();
+          if (nullValueVector != null && !nullValueVector.getNullBitmap().isEmpty()) {
+            return false;
+          }
+        }
+        return dataSource.getDataSourceMetadata().isSorted();
+      }
+      case FUNCTION: // we could optimize monotonically increasing functions
+      default: {
         return false;
       }
     }
-    return true;
+  }
+
+  public enum OrderByAlgorithm {
+    NAIVE("naive");
+
+    /**
+     * The public name of the algorithm. This name can be used by users to specify the algorithm to use. Therefore any
+     * change here must be backward compatible.
+     *
+     * @see #findByPublicName(String)
+     */
+    private final String _publicName;
+
+    OrderByAlgorithm(String publicName) {
+      _publicName = publicName;
+    }
+
+    @Nullable
+    public static OrderByAlgorithm findByPublicName(@Nullable String publicName) {
+      if (publicName == null || publicName.equals("null") || publicName.isEmpty()) {
+        return null;
+      }
+      for (OrderByAlgorithm value : OrderByAlgorithm.values()) {

Review Comment:
   We usually do `OrderByAlgorithm.valueOf(name.toUpperCase())` to avoid the linear scan



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] gortiz commented on a diff in pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
gortiz commented on code in PR #8979:
URL: https://github.com/apache/pinot/pull/8979#discussion_r982725932


##########
pinot-core/src/main/java/org/apache/pinot/core/operator/blocks/results/SelectionResultsBlock.java:
##########
@@ -45,6 +56,26 @@ public Collection<Object[]> getRows() {
     return _rows;
   }
 
+  public SelectionResultsBlock cloneWithInnerPriorityQueue() {
+    if (_rows instanceof PriorityQueue) {
+      return new SelectionResultsBlock(_dataSchema, new PriorityQueue<>(_rows));

Review Comment:
   > The SelectionResultsBlock is still immutable. We just don't create a duplicate one when it is already backed by a priority queue.
   
   It is not. `MinMaxValueBasedSelectionOrderByCombineOperator` and `SelectionOrderByCombineOperator` will modify the returned instace (by directly modifying the value returned by `getRows()`.
   
   I think it is better to keep them immutable, but given that the mutable pattern seems to be used in other parts of Pinot, I'm going to add your suggested changes to do not generate another discussion that may delay this PR.



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] gortiz commented on a diff in pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
gortiz commented on code in PR #8979:
URL: https://github.com/apache/pinot/pull/8979#discussion_r980827705


##########
pinot-core/src/main/java/org/apache/pinot/core/operator/query/LinearSelectionOrderByOperator.java:
##########
@@ -0,0 +1,476 @@
+/**
+ * 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.pinot.core.operator.query;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+import java.util.PriorityQueue;
+import java.util.function.IntFunction;
+import java.util.function.Supplier;
+import javax.annotation.Nullable;
+import org.apache.pinot.common.request.context.ExpressionContext;
+import org.apache.pinot.common.request.context.OrderByExpressionContext;
+import org.apache.pinot.common.utils.DataSchema;
+import org.apache.pinot.core.common.BlockValSet;
+import org.apache.pinot.core.common.Operator;
+import org.apache.pinot.core.common.RowBasedBlockValueFetcher;
+import org.apache.pinot.core.operator.BaseOperator;
+import org.apache.pinot.core.operator.ExecutionStatistics;
+import org.apache.pinot.core.operator.blocks.TransformBlock;
+import org.apache.pinot.core.operator.blocks.results.SelectionResultsBlock;
+import org.apache.pinot.core.operator.transform.TransformOperator;
+import org.apache.pinot.core.operator.transform.TransformResultMetadata;
+import org.apache.pinot.core.query.request.context.QueryContext;
+import org.apache.pinot.core.query.selection.SelectionOperatorUtils;
+import org.apache.pinot.segment.spi.IndexSegment;
+import org.roaringbitmap.RoaringBitmap;
+
+
+/**
+ * A selection Operator used when the first expressions in the order by are identifier expressions of columns that are
+ * already sorted (either ascendingly or descendingly), even if the tail of order by expressions are not sorted.
+ *
+ * ie: SELECT ... FROM Table WHERE predicates ORDER BY sorted_column DESC LIMIT 10 OFFSET 5
+ * or: SELECT ... FROM Table WHERE predicates ORDER BY sorted_column, not_sorted LIMIT 10 OFFSET 5
+ * but not SELECT ... FROM Table WHERE predicates ORDER BY not_sorted, sorted_column LIMIT 10 OFFSET 5
+ *
+ * Operators that derives from this class are going to have an almost linear cost instead of the usual NlogN when actual
+ * sorting must be done, where N is the number of rows in the segment.
+ * There is a degraded scenario when the cost is actually NlogL (where L is the limit of the query) when all the first L
+ * rows have the exact same value for the prefix of the sorted columns. Even in that case, L should be quite smaller
+ * than N, so this implementation is algorithmically better than the normal solution.
+ */
+public abstract class LinearSelectionOrderByOperator extends BaseOperator<SelectionResultsBlock> {
+  protected final IndexSegment _indexSegment;
+
+  protected final boolean _nullHandlingEnabled;
+  // Deduped order-by expressions followed by output expressions from SelectionOperatorUtils.extractExpressions()
+  protected final List<ExpressionContext> _expressions;
+  protected final List<ExpressionContext> _alreadySorted;
+  protected final List<ExpressionContext> _toSort;
+
+  protected final TransformOperator _transformOperator;
+  protected final List<OrderByExpressionContext> _orderByExpressions;
+  protected final TransformResultMetadata[] _expressionsMetadata;
+  protected final int _numRowsToKeep;
+  private final Supplier<ListBuilder> _listBuilderSupplier;
+  protected boolean _used = false;
+  protected Comparator<Object[]> _comparator;
+
+  /**
+   *
+   * @param expressions order by expressions must be at the head of the list.
+   * @param sortedExpr How many expressions at the head of the expression list are going to be considered sorted by
+   * {@link #fetch(Supplier<ListBuilder>)}
+   */
+  public LinearSelectionOrderByOperator(IndexSegment indexSegment, QueryContext queryContext,
+      List<ExpressionContext> expressions, TransformOperator transformOperator,
+      int sortedExpr) {
+    _indexSegment = indexSegment;
+    _nullHandlingEnabled = queryContext.isNullHandlingEnabled();
+    _expressions = expressions;
+    _transformOperator = transformOperator;
+
+    _orderByExpressions = queryContext.getOrderByExpressions();
+    assert _orderByExpressions != null;
+    int numOrderByExpressions = _orderByExpressions.size();
+
+    _alreadySorted = expressions.subList(0, sortedExpr);
+    _toSort = expressions.subList(sortedExpr, numOrderByExpressions);
+
+    _expressionsMetadata = new TransformResultMetadata[_expressions.size()];
+    for (int i = 0; i < _expressionsMetadata.length; i++) {
+      ExpressionContext expression = _expressions.get(i);
+      _expressionsMetadata[i] = _transformOperator.getResultMetadata(expression);
+    }
+
+    _numRowsToKeep = queryContext.getOffset() + queryContext.getLimit();
+
+    if (_toSort.isEmpty()) {
+      int expectedSize = Math.min(SelectionOperatorUtils.MAX_ROW_HOLDER_INITIAL_CAPACITY, _numRowsToKeep);
+      _listBuilderSupplier = () -> new TotallySortedListBuilder(expectedSize);
+    } else {
+      int maxSize = Math.min(SelectionOperatorUtils.MAX_ROW_HOLDER_INITIAL_CAPACITY, _numRowsToKeep * 2);
+
+      Comparator<Object[]> sortedComparator = OrderByComparatorFactory.getComparator(_orderByExpressions,
+          _expressionsMetadata, true, _nullHandlingEnabled, 0, sortedExpr);
+      Comparator<Object[]> unsortedComparator = OrderByComparatorFactory.getComparator(_orderByExpressions,
+          _expressionsMetadata, true, _nullHandlingEnabled, sortedExpr, numOrderByExpressions);
+      _listBuilderSupplier = () -> new PartiallySortedListBuilder(maxSize, sortedComparator, unsortedComparator);
+    }
+
+    _comparator =
+        OrderByComparatorFactory.getComparator(_orderByExpressions, _expressionsMetadata, false, _nullHandlingEnabled);
+  }
+
+  @Override
+  public IndexSegment getIndexSegment() {
+    return _indexSegment;
+  }
+
+  @Override
+  public ExecutionStatistics getExecutionStatistics() {
+    long numEntriesScannedInFilter = _transformOperator.getExecutionStatistics().getNumEntriesScannedInFilter();
+    int numTotalDocs = _indexSegment.getSegmentMetadata().getTotalDocs();
+    return new ExecutionStatistics(getNumDocsScanned(), numEntriesScannedInFilter, getNumEntriesScannedPostFilter(),
+        numTotalDocs);
+  }
+
+  protected IntFunction<Object[]> fetchBlock(TransformBlock transformBlock, BlockValSet[] blockValSets) {
+    int numExpressions = _expressions.size();
+
+    for (int i = 0; i < numExpressions; i++) {
+      ExpressionContext expression = _expressions.get(i);
+      blockValSets[i] = transformBlock.getBlockValueSet(expression);
+    }
+    RowBasedBlockValueFetcher blockValueFetcher = new RowBasedBlockValueFetcher(blockValSets);
+
+    if (!_nullHandlingEnabled) {
+      return blockValueFetcher::getRow;
+    }
+    RoaringBitmap[] nullBitmaps = new RoaringBitmap[numExpressions];
+    for (int i = 0; i < numExpressions; i++) {
+      nullBitmaps[i] = blockValSets[i].getNullBitmap();
+    }
+    return (docId) -> {
+      Object[] row = blockValueFetcher.getRow(docId);
+      for (int colId = 0; colId < nullBitmaps.length; colId++) {
+        if (nullBitmaps[colId] != null && nullBitmaps[colId].contains(docId)) {
+          row[colId] = null;
+        }
+      }
+      return row;
+    };
+  }
+
+  protected abstract long getNumEntriesScannedPostFilter();
+
+  protected abstract int getNumDocsScanned();
+
+  /**
+   * Returns a list of rows sorted that:
+   * <ul>
+   *   <li>At least contains all the rows that fulfill the predicate</li>
+   *   <li>Rows are sorted in a way that is compatible with the given list builder supplier</li>
+   * </ul>
+   *
+   * That means that the result may contain more rows than required.
+   *
+   * @param listBuilderSupplier a {@link ListBuilder} supplier that should be used to create the result. Each time is
+   *                            called a new {@link ListBuilder} will be returned. All returned instances use the same
+   *                            comparator logic.
+   */
+  protected abstract List<Object[]> fetch(Supplier<ListBuilder> listBuilderSupplier);
+
+  @Override
+  public List<Operator> getChildOperators() {
+    return Collections.singletonList(_transformOperator);
+  }
+
+  protected abstract String getExplainName();
+
+  @Override
+  public String toExplainString() {
+    StringBuilder sb = new StringBuilder(getExplainName());
+
+    sb.append("(sortedList: ");
+    concatList(sb, _alreadySorted);
+
+    sb.append(", unsortedList: ");
+    concatList(sb, _toSort);
+
+    sb.append(", rest: ");
+    concatList(sb, _expressions.subList(_alreadySorted.size() + _toSort.size(), _expressions.size()));
+
+    sb.append(')');
+    return sb.toString();
+  }
+
+  private void concatList(StringBuilder sb, List<?> list) {
+    sb.append('(');
+    Iterator<?> it = list.iterator();
+    if (it.hasNext()) {
+      sb.append(it.next());
+      while (it.hasNext()) {
+        sb.append(", ").append(it.next());
+      }
+    }
+    sb.append(')');
+  }
+
+  @Override
+  protected SelectionResultsBlock getNextBlock() {
+    Preconditions.checkState(!_used, "nextBlock was called more than once");
+    _used = true;
+    List<Object[]> list = fetch(_listBuilderSupplier);
+
+    DataSchema dataSchema = createDataSchema();
+
+    if (list.size() > _numRowsToKeep) {
+      list = new ArrayList<>(list.subList(0, _numRowsToKeep));
+    }
+
+    SelectionResultsBlock resultsBlock = new SelectionResultsBlock(dataSchema, list, _comparator);
+
+    return resultsBlock;
+  }
+
+  protected DataSchema createDataSchema() {
+    int numExpressions = _expressions.size();
+
+    // Create the data schema
+    String[] columnNames = new String[numExpressions];
+    DataSchema.ColumnDataType[] columnDataTypes = new DataSchema.ColumnDataType[numExpressions];
+    for (int i = 0; i < columnNames.length; i++) {
+      columnNames[i] = _expressions.get(i).toString();
+    }
+    for (int i = 0; i < numExpressions; i++) {
+      TransformResultMetadata expressionMetadata = _expressionsMetadata[i];
+      columnDataTypes[i] =
+          DataSchema.ColumnDataType.fromDataType(expressionMetadata.getDataType(), expressionMetadata.isSingleValue());
+    }
+    return new DataSchema(columnNames, columnDataTypes);
+  }
+
+  /**
+   * A private class used to build a sorted list by adding partially sorted data.
+   *
+   * Specifically, this class has been designed to receive successive calls to {@link #add(Object[])} follow by a single
+   * call to {@link #build()}. Once this method is called, the behavior of this object is undefined and therefore it
+   * should not be used.
+   *
+   * Rows must be inserted in ascending order accordingly to the partial order specified by a comparator.
+   * This comparator will define <i>partitions</i> of rows. All the rows in the same partition same are considered equal
+   * by that comparator.
+   *
+   * Some implementations, like {@link PartiallySortedListBuilder} accepts a second comparator that is used to sort rows
+   * inside each partition.
+   * When calling {@link #add(Object[])} with a row that doesn't belong to the current partition, a new one is started
+   * and the previous one is sorted. Therefore, this object maintains the invariant that at any moment there are at
+   * least {@link #sortedSize()} elements that are completely sorted, which means that no matter which elements are
+   * added after that, these elements are going to be smallest.
+   */
+  protected interface ListBuilder {
+
+    /**
+     * Adds the given row to this object. The new column must be equal or higher than the partition comparator.
+     *
+     * @param row The row to add. The values of the already sorted columns must be equal or higher than the last added
+     *           row, if any.
+     * @return true if and only if the previous partition was closed.
+     */
+    boolean add(Object[] row);
+
+    /**
+     * Builds the sorted list. The returned list will be sorted, even if a previous call t o {@link #sortedSize()}
+     * returned a number lower than the number of elements that have been added.
+     *
+     * Once this method is called, the builder should not be used. There is no guaranteed on whether
+     * {@link #sortedSize()} is updated or not.
+     */
+    List<Object[]> build();
+
+    /**
+     * How many elements are actually sorted. This number is lower or equal to the number of elements that has been
+     * added.
+     */
+    int sortedSize();
+  }
+
+  /**
+   * This is the faster {@link ListBuilder} but also the most restrictive one. It can only be used when data is inserted
+   * in total order. Therefore it cannot be used to implement order-by queries where there is at least one expression
+   * that is not sorted. In such case {@link PartiallySortedListBuilder} should be used.
+   *
+   * This implementation is just a wrapper over an ArrayList and therefore the average costs of its methods is constant.
+   */
+  protected static class TotallySortedListBuilder implements ListBuilder {
+    private final ArrayList<Object[]> _list;
+
+    public TotallySortedListBuilder(int expectedSize) {
+      _list = new ArrayList<>(expectedSize);
+    }
+
+    @Override
+    public boolean add(Object[] row) {
+      _list.add(row);
+      return true;
+    }
+
+    @Override
+    public List<Object[]> build() {
+      return _list;
+    }
+
+    @Override
+    public int sortedSize() {
+      return _list.size();
+    }
+  }
+
+  /**
+   * This is the more versatile {@link ListBuilder} that requires two comparators: The first defines the order on which
+   * {@link #add(Object[])} is called and defines the partitions. The second one is used to sort rows in the same
+   * partition. This class can be used to implement order-by queries that include one or more not sorted expressions.
+   * In cases where all expressions are sorted, {@link TotallySortedListBuilder} should be used because its performance
+   * is better.
+   *
+   * In this implementation the {@link #add(Object[])} method has a log(P) cost, where P is the number of elements in
+   * each partition. In normal cases we can consider P a constant. In some degenerated cases like having an ordering by
+   * a sorted column whose values are all equal, P may tend to the number of elements in the segment, which would make
+   * the cost of this method log(N).
+   *
+   * This class is optimized for scenarios where the partitions are smaller than the limit. In that case, the partition
+   * is only sorted once it is closed (aka when a new element for the other partition is found), so each insertion has
+   * an average cost of log(P) (where P-1 insertions are cost O(1) and the last one is O(PlogP)). In cases where at
+   * least one partition is larger than the limit, this implementation delegates the last partition to a
+   * {@link PriorityQueue}.
+   */
+  private static class PartiallySortedListBuilder implements ListBuilder {
+    private final ArrayList<Object[]> _rows;
+    /**
+     * The comparator that defines the partitions and the one that impose in which order add has to be called.
+     */
+    private final Comparator<Object[]> _partitionComparator;
+    /**
+     * The comparator that sorts different rows on each partition.
+     */
+    private final Comparator<Object[]> _unsortedComparator;
+    @Nullable
+    private Object[] _lastPartitionRow;
+    /**
+     * How many elements are already sorted. This is also the index where the last (and still not sorted) partition
+     * starts or should start.
+     */
+    private int _sortedPrefixSize;
+    private final int _maxSize;
+    private PriorityQueue<Object[]> _queue = null;
+    private int _maxPriorityQueueValues;
+
+    public PartiallySortedListBuilder(int maxSize, Comparator<Object[]> partitionComparator,
+        Comparator<Object[]> unsortedComparator) {
+      Preconditions.checkArgument(maxSize > 0, "Max size must be greater than 0");
+      _maxSize = maxSize;
+      _rows = new ArrayList<>(maxSize);
+      _partitionComparator = partitionComparator;
+      _unsortedComparator = unsortedComparator;
+    }
+
+    @Override
+    public boolean add(Object[] row) {
+      boolean result;
+      if (_lastPartitionRow == null) {
+        _sortedPrefixSize = 0;
+        _lastPartitionRow = row;
+        _rows.add(row);
+        return false;
+      } else {
+        int cmp = _partitionComparator.compare(row, _lastPartitionRow);
+        if (cmp < 0) {
+          throw new IllegalArgumentException("Row " + Arrays.toString(row) + " is lower than previously added row"
+              + Arrays.toString(_lastPartitionRow));
+        }
+
+        if (_queue != null) {
+          if (cmp > 0) {
+            // the new row is in a greater partition, just don't add it and continue
+            return true;
+          }
+          // otherwise they are equal by the already sorted columns. Let's check the other columns and evict the higher
+          // also, we have the higher value at the last position
+          SelectionOperatorUtils.addToPriorityQueue(row, _queue, _maxPriorityQueueValues);
+          return false;
+        } else {
+          if (_rows.size() == _maxSize) { // we already have _maxSize results
+            if (cmp > 0) {
+              // and the new one is higher, so we don't need to add it
+              sortLastPartition();
+              return true;
+            }
+            // and the new one may be smaller, so this is going to be the last partition and we need to prepare the
+            // priority queue
+            buildPriorityQueue();
+            SelectionOperatorUtils.addToPriorityQueue(row, _queue, _maxPriorityQueueValues);
+            return false;
+          }
+          if (cmp > 0) {
+            sortLastPartition();
+            _lastPartitionRow = row;
+            result = true;
+          } else {
+            result = false;
+          }
+          _rows.add(row);
+          return result;
+        }
+      }
+    }
+
+    private void buildPriorityQueue() {
+      _maxPriorityQueueValues = _maxSize - _sortedPrefixSize;
+      _queue = new PriorityQueue<>(_maxPriorityQueueValues, _unsortedComparator.reversed());
+      for (int i = 0; i < _maxPriorityQueueValues; i++) {
+        int lastIdx = _rows.size() - 1;
+        _queue.add(_rows.get(lastIdx));
+        _rows.remove(lastIdx);
+      }
+    }
+
+    void sortLastPartition() {
+      int size = _rows.size();
+      if (_sortedPrefixSize != size) {
+        List<Object[]> lastsPartition = _rows.subList(_sortedPrefixSize, size);
+        lastsPartition.sort(_unsortedComparator);
+        _sortedPrefixSize = size;
+      }
+    }
+
+    /**
+     * Sorts the rows and returns the sorted list.
+     *
+     * This object should not be used once this method is called.
+     *
+     * @return the list of all added rows, sorted by {@link #_partitionComparator} and then by
+     * {@link #_unsortedComparator}
+     */
+    @Override
+    public List<Object[]> build() {
+      if (_queue != null) {
+        _rows.addAll(_queue);
+        // queue is sorted in the reverse order, so we need to reverse this partition

Review Comment:
   But I get your point. Given that PQ iterator doesn't honor the order, I shouldn't use reverse but sort. Changed.



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] gortiz commented on a diff in pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
gortiz commented on code in PR #8979:
URL: https://github.com/apache/pinot/pull/8979#discussion_r982768725


##########
pinot-core/src/main/java/org/apache/pinot/core/plan/SelectionPlanNode.java:
##########
@@ -50,67 +55,119 @@ public Operator<SelectionResultsBlock> run() {
     List<ExpressionContext> expressions = SelectionOperatorUtils.extractExpressions(_queryContext, _indexSegment);
     int limit = _queryContext.getLimit();
 
-    if (limit > 0) {
-      List<OrderByExpressionContext> orderByExpressions = _queryContext.getOrderByExpressions();
-      if (orderByExpressions == null) {
-        // Selection only
-        TransformOperator transformOperator = new TransformPlanNode(_indexSegment, _queryContext, expressions,
-            Math.min(limit, DocIdSetPlanNode.MAX_DOC_PER_CALL)).run();
-        return new SelectionOnlyOperator(_indexSegment, _queryContext, expressions, transformOperator);
-      } else {
-        // Selection order-by
-        if (isAllOrderByColumnsSorted(orderByExpressions)) {
-          // All order-by columns are sorted, no need to sort the records
-          TransformOperator transformOperator = new TransformPlanNode(_indexSegment, _queryContext, expressions,
-              Math.min(limit + _queryContext.getOffset(), DocIdSetPlanNode.MAX_DOC_PER_CALL)).run();
-          return new SelectionOrderByOperator(_indexSegment, _queryContext, expressions, transformOperator, true);
-        } else if (orderByExpressions.size() == expressions.size()) {
-          // All output expressions are ordered
-          TransformOperator transformOperator =
-              new TransformPlanNode(_indexSegment, _queryContext, expressions, DocIdSetPlanNode.MAX_DOC_PER_CALL).run();
-          return new SelectionOrderByOperator(_indexSegment, _queryContext, expressions, transformOperator, false);
-        } else {
-          // Not all output expressions are ordered, only fetch the order-by expressions and docId to avoid the
-          // unnecessary data fetch
-          List<ExpressionContext> expressionsToTransform = new ArrayList<>(orderByExpressions.size());
-          for (OrderByExpressionContext orderByExpression : orderByExpressions) {
-            expressionsToTransform.add(orderByExpression.getExpression());
-          }
-          TransformOperator transformOperator =
-              new TransformPlanNode(_indexSegment, _queryContext, expressionsToTransform,
-                  DocIdSetPlanNode.MAX_DOC_PER_CALL).run();
-          return new SelectionOrderByOperator(_indexSegment, _queryContext, expressions, transformOperator, false);
-        }
-      }
-    } else {
+    if (limit == 0) {
       // Empty selection (LIMIT 0)
       TransformOperator transformOperator = new TransformPlanNode(_indexSegment, _queryContext, expressions, 0).run();
       return new EmptySelectionOperator(_indexSegment, expressions, transformOperator);
     }
+    List<OrderByExpressionContext> orderByExpressions = _queryContext.getOrderByExpressions();
+    if (orderByExpressions == null) {
+      // Selection only
+      // ie: SELECT ... FROM Table WHERE ... LIMIT 10
+      int maxDocsPerCall = Math.min(limit, DocIdSetPlanNode.MAX_DOC_PER_CALL);
+      TransformPlanNode planNode = new TransformPlanNode(_indexSegment, _queryContext, expressions, maxDocsPerCall);
+      TransformOperator transformOperator = planNode.run();
+
+      return new SelectionOnlyOperator(_indexSegment, _queryContext, expressions, transformOperator);
+    }
+    int numOrderByExpressions = orderByExpressions.size();
+    // Although it is a break of abstraction, some code, specially merging, assumes that if there is an order by
+    // expression the operator will return a block whose selection result is a priority queue.
+    int sortedColumnsPrefixSize = getSortedColumnsPrefix(orderByExpressions, _queryContext.isNullHandlingEnabled());
+    if (sortedColumnsPrefixSize > 0 && !isSkipOrderByOptimization()) {
+      // The first order by expressions are sorted (either asc or desc).
+      // ie: SELECT ... FROM Table WHERE predicates ORDER BY sorted_column DESC LIMIT 10 OFFSET 5
+      // or: SELECT ... FROM Table WHERE predicates ORDER BY sorted_column, not_sorted LIMIT 10 OFFSET 5
+      // but not SELECT ... FROM Table WHERE predicates ORDER BY not_sorted, sorted_column LIMIT 10 OFFSET 5
+      if (orderByExpressions.get(0).isAsc()) {
+        int maxDocsPerCall = Math.min(limit + _queryContext.getOffset(), DocIdSetPlanNode.MAX_DOC_PER_CALL);
+        TransformPlanNode planNode = new TransformPlanNode(_indexSegment, _queryContext, expressions, maxDocsPerCall);
+        TransformOperator transformOperator = planNode.run();
+        return new SelectionPartiallyOrderedByAscOperator(_indexSegment, _queryContext, expressions,
+            transformOperator, sortedColumnsPrefixSize);
+      } else {
+        int maxDocsPerCall = DocIdSetPlanNode.MAX_DOC_PER_CALL;

Review Comment:
   Yep. The two main reasons why I worked on this is to avoid PQ comparisons (as suggested by @richardstartin) and to improve (as much as possible without reverse cursors) the order by desc.



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] gortiz commented on a diff in pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
gortiz commented on code in PR #8979:
URL: https://github.com/apache/pinot/pull/8979#discussion_r978531168


##########
pinot-core/src/main/java/org/apache/pinot/core/operator/blocks/results/SelectionResultsBlock.java:
##########
@@ -45,6 +56,18 @@ public Collection<Object[]> getRows() {
     return _rows;
   }
 
+  public PriorityQueue<Object[]> getRowsAsPriorityQueue() {

Review Comment:
   I find easier to read and to explore the code if we have something like this instead of forcing castings around the code.



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] Jackie-Jiang commented on a diff in pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
Jackie-Jiang commented on code in PR #8979:
URL: https://github.com/apache/pinot/pull/8979#discussion_r961851815


##########
pinot-core/src/main/java/org/apache/pinot/core/plan/SelectionPlanNode.java:
##########
@@ -50,67 +52,113 @@ public Operator<IntermediateResultsBlock> run() {
     List<ExpressionContext> expressions = SelectionOperatorUtils.extractExpressions(_queryContext, _indexSegment);
     int limit = _queryContext.getLimit();
 
-    if (limit > 0) {
-      List<OrderByExpressionContext> orderByExpressions = _queryContext.getOrderByExpressions();
-      if (orderByExpressions == null) {
-        // Selection only
-        TransformOperator transformOperator = new TransformPlanNode(_indexSegment, _queryContext, expressions,
-            Math.min(limit, DocIdSetPlanNode.MAX_DOC_PER_CALL)).run();
-        return new SelectionOnlyOperator(_indexSegment, _queryContext, expressions, transformOperator);
-      } else {
-        // Selection order-by
-        if (isAllOrderByColumnsSorted(orderByExpressions)) {
-          // All order-by columns are sorted, no need to sort the records
-          TransformOperator transformOperator = new TransformPlanNode(_indexSegment, _queryContext, expressions,
-              Math.min(limit + _queryContext.getOffset(), DocIdSetPlanNode.MAX_DOC_PER_CALL)).run();
-          return new SelectionOrderByOperator(_indexSegment, _queryContext, expressions, transformOperator, true);
-        } else if (orderByExpressions.size() == expressions.size()) {
-          // All output expressions are ordered
-          TransformOperator transformOperator =
-              new TransformPlanNode(_indexSegment, _queryContext, expressions, DocIdSetPlanNode.MAX_DOC_PER_CALL).run();
-          return new SelectionOrderByOperator(_indexSegment, _queryContext, expressions, transformOperator, false);
-        } else {
-          // Not all output expressions are ordered, only fetch the order-by expressions and docId to avoid the
-          // unnecessary data fetch
-          List<ExpressionContext> expressionsToTransform = new ArrayList<>(orderByExpressions.size());
-          for (OrderByExpressionContext orderByExpression : orderByExpressions) {
-            expressionsToTransform.add(orderByExpression.getExpression());
-          }
-          TransformOperator transformOperator =
-              new TransformPlanNode(_indexSegment, _queryContext, expressionsToTransform,
-                  DocIdSetPlanNode.MAX_DOC_PER_CALL).run();
-          return new SelectionOrderByOperator(_indexSegment, _queryContext, expressions, transformOperator, false);
-        }
-      }
-    } else {
+    if (limit == 0) {
       // Empty selection (LIMIT 0)
       TransformOperator transformOperator = new TransformPlanNode(_indexSegment, _queryContext, expressions, 0).run();
       return new EmptySelectionOperator(_indexSegment, expressions, transformOperator);
     }
+    List<OrderByExpressionContext> orderByExpressions = _queryContext.getOrderByExpressions();
+
+    if (orderByExpressions == null) {
+      // Selection only
+      // ie: SELECT ... FROM Table WHERE ... LIMIT 10
+      int actualLimit = Math.min(limit, DocIdSetPlanNode.MAX_DOC_PER_CALL);
+      TransformPlanNode planNode = new TransformPlanNode(_indexSegment, _queryContext, expressions, actualLimit);
+      TransformOperator transformOperator = planNode.run();
+
+      return new SelectionOnlyOperator(_indexSegment, _queryContext, expressions, transformOperator);
+    }
+    int numOrderByExpressions = orderByExpressions.size();
+    // Although it is a break of abstraction, some code, specially merging, assumes that if there is an order by
+    // expression the operator will return a block whose selection result is a priority queue.
+    int sortedColumnsPrefixSize = getSortedColumnsPrefix(orderByExpressions);

Review Comment:
   It might be sorted or not based on the default value of the column. E.g. if default value for a int column is `0`, then `-1, null, 1` is considered sorted; but if the default value is `-100` then it is not sorted.
   
   The null handling support feature is added recently, and we treat null as default value when generating the index (we don't know if null handling is enabled at ingestion time either). So what we can do here is deciding whether to use this optimization at query time, and not use it when null handling is enabled and the column contains null values



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


[GitHub] [pinot] Jackie-Jiang commented on a diff in pull request #8979: optimize `order by sorted ASC, unsorted` and `order by DESC` cases

Posted by GitBox <gi...@apache.org>.
Jackie-Jiang commented on code in PR #8979:
URL: https://github.com/apache/pinot/pull/8979#discussion_r979120516


##########
pinot-core/src/main/java/org/apache/pinot/core/util/QueryOptionsUtils.java:
##########
@@ -102,4 +102,8 @@ public static boolean isNullHandlingEnabled(Map<String, String> queryOptions) {
   public static boolean isServerReturnFinalResult(Map<String, String> queryOptions) {
     return Boolean.parseBoolean(queryOptions.get(QueryOptionKey.SERVER_RETURN_FINAL_RESULT));
   }
+
+  public static boolean isSkipOrderByOptimization(Map<String, String> queryOptions) {
+    return Boolean.parseBoolean(queryOptions.getOrDefault("skip-order-by", "false"));

Review Comment:
   Let's move the key in to the `QueryOptionKey` constant. No need to get the default `false` because `parseBoolean` can handle `null`. We should think of a more exact key as `skip order by` can be ambiguous, e.g. `skipOrderBySortedColumnOptimization`



##########
pinot-core/src/main/java/org/apache/pinot/core/operator/blocks/results/SelectionResultsBlock.java:
##########
@@ -45,6 +56,26 @@ public Collection<Object[]> getRows() {
     return _rows;
   }
 
+  public SelectionResultsBlock cloneWithInnerPriorityQueue() {
+    if (_rows instanceof PriorityQueue) {
+      return new SelectionResultsBlock(_dataSchema, new PriorityQueue<>(_rows));

Review Comment:
   This will involve extra overhead when the block is already backed by a PQ. We want to directly `return this` here, and change the method name to e.g. `convertToPriorityQueueBased()` to reflect that.



##########
pinot-core/src/main/java/org/apache/pinot/core/plan/SelectionPlanNode.java:
##########
@@ -50,67 +55,119 @@ public Operator<SelectionResultsBlock> run() {
     List<ExpressionContext> expressions = SelectionOperatorUtils.extractExpressions(_queryContext, _indexSegment);
     int limit = _queryContext.getLimit();
 
-    if (limit > 0) {
-      List<OrderByExpressionContext> orderByExpressions = _queryContext.getOrderByExpressions();
-      if (orderByExpressions == null) {
-        // Selection only
-        TransformOperator transformOperator = new TransformPlanNode(_indexSegment, _queryContext, expressions,
-            Math.min(limit, DocIdSetPlanNode.MAX_DOC_PER_CALL)).run();
-        return new SelectionOnlyOperator(_indexSegment, _queryContext, expressions, transformOperator);
-      } else {
-        // Selection order-by
-        if (isAllOrderByColumnsSorted(orderByExpressions)) {
-          // All order-by columns are sorted, no need to sort the records
-          TransformOperator transformOperator = new TransformPlanNode(_indexSegment, _queryContext, expressions,
-              Math.min(limit + _queryContext.getOffset(), DocIdSetPlanNode.MAX_DOC_PER_CALL)).run();
-          return new SelectionOrderByOperator(_indexSegment, _queryContext, expressions, transformOperator, true);
-        } else if (orderByExpressions.size() == expressions.size()) {
-          // All output expressions are ordered
-          TransformOperator transformOperator =
-              new TransformPlanNode(_indexSegment, _queryContext, expressions, DocIdSetPlanNode.MAX_DOC_PER_CALL).run();
-          return new SelectionOrderByOperator(_indexSegment, _queryContext, expressions, transformOperator, false);
-        } else {
-          // Not all output expressions are ordered, only fetch the order-by expressions and docId to avoid the
-          // unnecessary data fetch
-          List<ExpressionContext> expressionsToTransform = new ArrayList<>(orderByExpressions.size());
-          for (OrderByExpressionContext orderByExpression : orderByExpressions) {
-            expressionsToTransform.add(orderByExpression.getExpression());
-          }
-          TransformOperator transformOperator =
-              new TransformPlanNode(_indexSegment, _queryContext, expressionsToTransform,
-                  DocIdSetPlanNode.MAX_DOC_PER_CALL).run();
-          return new SelectionOrderByOperator(_indexSegment, _queryContext, expressions, transformOperator, false);
-        }
-      }
-    } else {
+    if (limit == 0) {
       // Empty selection (LIMIT 0)
       TransformOperator transformOperator = new TransformPlanNode(_indexSegment, _queryContext, expressions, 0).run();
       return new EmptySelectionOperator(_indexSegment, expressions, transformOperator);
     }
+    List<OrderByExpressionContext> orderByExpressions = _queryContext.getOrderByExpressions();
+    if (orderByExpressions == null) {
+      // Selection only
+      // ie: SELECT ... FROM Table WHERE ... LIMIT 10
+      int maxDocsPerCall = Math.min(limit, DocIdSetPlanNode.MAX_DOC_PER_CALL);
+      TransformPlanNode planNode = new TransformPlanNode(_indexSegment, _queryContext, expressions, maxDocsPerCall);
+      TransformOperator transformOperator = planNode.run();
+
+      return new SelectionOnlyOperator(_indexSegment, _queryContext, expressions, transformOperator);
+    }
+    int numOrderByExpressions = orderByExpressions.size();
+    // Although it is a break of abstraction, some code, specially merging, assumes that if there is an order by
+    // expression the operator will return a block whose selection result is a priority queue.
+    int sortedColumnsPrefixSize = getSortedColumnsPrefix(orderByExpressions, _queryContext.isNullHandlingEnabled());
+    if (sortedColumnsPrefixSize > 0 && !isSkipOrderByOptimization()) {
+      // The first order by expressions are sorted (either asc or desc).
+      // ie: SELECT ... FROM Table WHERE predicates ORDER BY sorted_column DESC LIMIT 10 OFFSET 5
+      // or: SELECT ... FROM Table WHERE predicates ORDER BY sorted_column, not_sorted LIMIT 10 OFFSET 5
+      // but not SELECT ... FROM Table WHERE predicates ORDER BY not_sorted, sorted_column LIMIT 10 OFFSET 5
+      if (orderByExpressions.get(0).isAsc()) {
+        int maxDocsPerCall = Math.min(limit + _queryContext.getOffset(), DocIdSetPlanNode.MAX_DOC_PER_CALL);

Review Comment:
   This `maxDocsPerCall` only applies to all sorted case. If it is partially sorted, reading this number of docs won't be able to solve the query.



##########
pinot-core/src/main/java/org/apache/pinot/core/operator/combine/BaseCombineOperator.java:
##########
@@ -162,7 +162,7 @@ protected void processSegments() {
         if (operator instanceof AcquireReleaseColumnsSegmentOperator) {
           ((AcquireReleaseColumnsSegmentOperator) operator).acquire();
         }
-        resultsBlock = (T) operator.nextBlock();
+        resultsBlock = convertToMergeableBlock((BaseResultsBlock) operator.nextBlock());

Review Comment:
   We don't want to convert here. We should change the type of `resultsBlock` to `BaseResultsBlock`.



##########
pinot-core/src/main/java/org/apache/pinot/core/operator/query/LinearSelectionOrderByOperator.java:
##########
@@ -0,0 +1,476 @@
+/**
+ * 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.pinot.core.operator.query;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+import java.util.PriorityQueue;
+import java.util.function.IntFunction;
+import java.util.function.Supplier;
+import javax.annotation.Nullable;
+import org.apache.pinot.common.request.context.ExpressionContext;
+import org.apache.pinot.common.request.context.OrderByExpressionContext;
+import org.apache.pinot.common.utils.DataSchema;
+import org.apache.pinot.core.common.BlockValSet;
+import org.apache.pinot.core.common.Operator;
+import org.apache.pinot.core.common.RowBasedBlockValueFetcher;
+import org.apache.pinot.core.operator.BaseOperator;
+import org.apache.pinot.core.operator.ExecutionStatistics;
+import org.apache.pinot.core.operator.blocks.TransformBlock;
+import org.apache.pinot.core.operator.blocks.results.SelectionResultsBlock;
+import org.apache.pinot.core.operator.transform.TransformOperator;
+import org.apache.pinot.core.operator.transform.TransformResultMetadata;
+import org.apache.pinot.core.query.request.context.QueryContext;
+import org.apache.pinot.core.query.selection.SelectionOperatorUtils;
+import org.apache.pinot.segment.spi.IndexSegment;
+import org.roaringbitmap.RoaringBitmap;
+
+
+/**
+ * A selection Operator used when the first expressions in the order by are identifier expressions of columns that are
+ * already sorted (either ascendingly or descendingly), even if the tail of order by expressions are not sorted.
+ *
+ * ie: SELECT ... FROM Table WHERE predicates ORDER BY sorted_column DESC LIMIT 10 OFFSET 5
+ * or: SELECT ... FROM Table WHERE predicates ORDER BY sorted_column, not_sorted LIMIT 10 OFFSET 5
+ * but not SELECT ... FROM Table WHERE predicates ORDER BY not_sorted, sorted_column LIMIT 10 OFFSET 5
+ *
+ * Operators that derives from this class are going to have an almost linear cost instead of the usual NlogN when actual
+ * sorting must be done, where N is the number of rows in the segment.
+ * There is a degraded scenario when the cost is actually NlogL (where L is the limit of the query) when all the first L
+ * rows have the exact same value for the prefix of the sorted columns. Even in that case, L should be quite smaller
+ * than N, so this implementation is algorithmically better than the normal solution.
+ */
+public abstract class LinearSelectionOrderByOperator extends BaseOperator<SelectionResultsBlock> {
+  protected final IndexSegment _indexSegment;
+
+  protected final boolean _nullHandlingEnabled;
+  // Deduped order-by expressions followed by output expressions from SelectionOperatorUtils.extractExpressions()
+  protected final List<ExpressionContext> _expressions;
+  protected final List<ExpressionContext> _alreadySorted;
+  protected final List<ExpressionContext> _toSort;
+
+  protected final TransformOperator _transformOperator;
+  protected final List<OrderByExpressionContext> _orderByExpressions;
+  protected final TransformResultMetadata[] _expressionsMetadata;
+  protected final int _numRowsToKeep;
+  private final Supplier<ListBuilder> _listBuilderSupplier;
+  protected boolean _used = false;
+  protected Comparator<Object[]> _comparator;
+
+  /**
+   *
+   * @param expressions order by expressions must be at the head of the list.
+   * @param sortedExpr How many expressions at the head of the expression list are going to be considered sorted by
+   * {@link #fetch(Supplier<ListBuilder>)}
+   */
+  public LinearSelectionOrderByOperator(IndexSegment indexSegment, QueryContext queryContext,
+      List<ExpressionContext> expressions, TransformOperator transformOperator,
+      int sortedExpr) {
+    _indexSegment = indexSegment;
+    _nullHandlingEnabled = queryContext.isNullHandlingEnabled();
+    _expressions = expressions;
+    _transformOperator = transformOperator;
+
+    _orderByExpressions = queryContext.getOrderByExpressions();
+    assert _orderByExpressions != null;
+    int numOrderByExpressions = _orderByExpressions.size();
+
+    _alreadySorted = expressions.subList(0, sortedExpr);
+    _toSort = expressions.subList(sortedExpr, numOrderByExpressions);
+
+    _expressionsMetadata = new TransformResultMetadata[_expressions.size()];
+    for (int i = 0; i < _expressionsMetadata.length; i++) {
+      ExpressionContext expression = _expressions.get(i);
+      _expressionsMetadata[i] = _transformOperator.getResultMetadata(expression);
+    }
+
+    _numRowsToKeep = queryContext.getOffset() + queryContext.getLimit();
+
+    if (_toSort.isEmpty()) {
+      int expectedSize = Math.min(SelectionOperatorUtils.MAX_ROW_HOLDER_INITIAL_CAPACITY, _numRowsToKeep);
+      _listBuilderSupplier = () -> new TotallySortedListBuilder(expectedSize);
+    } else {
+      int maxSize = Math.min(SelectionOperatorUtils.MAX_ROW_HOLDER_INITIAL_CAPACITY, _numRowsToKeep * 2);
+
+      Comparator<Object[]> sortedComparator = OrderByComparatorFactory.getComparator(_orderByExpressions,
+          _expressionsMetadata, true, _nullHandlingEnabled, 0, sortedExpr);
+      Comparator<Object[]> unsortedComparator = OrderByComparatorFactory.getComparator(_orderByExpressions,
+          _expressionsMetadata, true, _nullHandlingEnabled, sortedExpr, numOrderByExpressions);
+      _listBuilderSupplier = () -> new PartiallySortedListBuilder(maxSize, sortedComparator, unsortedComparator);
+    }
+
+    _comparator =
+        OrderByComparatorFactory.getComparator(_orderByExpressions, _expressionsMetadata, false, _nullHandlingEnabled);
+  }
+
+  @Override
+  public IndexSegment getIndexSegment() {
+    return _indexSegment;
+  }
+
+  @Override
+  public ExecutionStatistics getExecutionStatistics() {
+    long numEntriesScannedInFilter = _transformOperator.getExecutionStatistics().getNumEntriesScannedInFilter();
+    int numTotalDocs = _indexSegment.getSegmentMetadata().getTotalDocs();
+    return new ExecutionStatistics(getNumDocsScanned(), numEntriesScannedInFilter, getNumEntriesScannedPostFilter(),
+        numTotalDocs);
+  }
+
+  protected IntFunction<Object[]> fetchBlock(TransformBlock transformBlock, BlockValSet[] blockValSets) {
+    int numExpressions = _expressions.size();
+
+    for (int i = 0; i < numExpressions; i++) {
+      ExpressionContext expression = _expressions.get(i);
+      blockValSets[i] = transformBlock.getBlockValueSet(expression);
+    }
+    RowBasedBlockValueFetcher blockValueFetcher = new RowBasedBlockValueFetcher(blockValSets);
+
+    if (!_nullHandlingEnabled) {
+      return blockValueFetcher::getRow;
+    }
+    RoaringBitmap[] nullBitmaps = new RoaringBitmap[numExpressions];
+    for (int i = 0; i < numExpressions; i++) {
+      nullBitmaps[i] = blockValSets[i].getNullBitmap();
+    }
+    return (docId) -> {
+      Object[] row = blockValueFetcher.getRow(docId);
+      for (int colId = 0; colId < nullBitmaps.length; colId++) {
+        if (nullBitmaps[colId] != null && nullBitmaps[colId].contains(docId)) {
+          row[colId] = null;
+        }
+      }
+      return row;
+    };
+  }
+
+  protected abstract long getNumEntriesScannedPostFilter();
+
+  protected abstract int getNumDocsScanned();
+
+  /**
+   * Returns a list of rows sorted that:
+   * <ul>
+   *   <li>At least contains all the rows that fulfill the predicate</li>
+   *   <li>Rows are sorted in a way that is compatible with the given list builder supplier</li>
+   * </ul>
+   *
+   * That means that the result may contain more rows than required.
+   *
+   * @param listBuilderSupplier a {@link ListBuilder} supplier that should be used to create the result. Each time is
+   *                            called a new {@link ListBuilder} will be returned. All returned instances use the same
+   *                            comparator logic.
+   */
+  protected abstract List<Object[]> fetch(Supplier<ListBuilder> listBuilderSupplier);
+
+  @Override
+  public List<Operator> getChildOperators() {
+    return Collections.singletonList(_transformOperator);
+  }
+
+  protected abstract String getExplainName();
+
+  @Override
+  public String toExplainString() {
+    StringBuilder sb = new StringBuilder(getExplainName());
+
+    sb.append("(sortedList: ");
+    concatList(sb, _alreadySorted);
+
+    sb.append(", unsortedList: ");
+    concatList(sb, _toSort);
+
+    sb.append(", rest: ");
+    concatList(sb, _expressions.subList(_alreadySorted.size() + _toSort.size(), _expressions.size()));
+
+    sb.append(')');
+    return sb.toString();
+  }
+
+  private void concatList(StringBuilder sb, List<?> list) {
+    sb.append('(');
+    Iterator<?> it = list.iterator();
+    if (it.hasNext()) {
+      sb.append(it.next());
+      while (it.hasNext()) {
+        sb.append(", ").append(it.next());
+      }
+    }
+    sb.append(')');
+  }
+
+  @Override
+  protected SelectionResultsBlock getNextBlock() {
+    Preconditions.checkState(!_used, "nextBlock was called more than once");
+    _used = true;
+    List<Object[]> list = fetch(_listBuilderSupplier);
+
+    DataSchema dataSchema = createDataSchema();
+
+    if (list.size() > _numRowsToKeep) {
+      list = new ArrayList<>(list.subList(0, _numRowsToKeep));
+    }
+
+    SelectionResultsBlock resultsBlock = new SelectionResultsBlock(dataSchema, list, _comparator);
+
+    return resultsBlock;
+  }
+
+  protected DataSchema createDataSchema() {
+    int numExpressions = _expressions.size();
+
+    // Create the data schema
+    String[] columnNames = new String[numExpressions];
+    DataSchema.ColumnDataType[] columnDataTypes = new DataSchema.ColumnDataType[numExpressions];
+    for (int i = 0; i < columnNames.length; i++) {
+      columnNames[i] = _expressions.get(i).toString();
+    }
+    for (int i = 0; i < numExpressions; i++) {
+      TransformResultMetadata expressionMetadata = _expressionsMetadata[i];
+      columnDataTypes[i] =
+          DataSchema.ColumnDataType.fromDataType(expressionMetadata.getDataType(), expressionMetadata.isSingleValue());
+    }
+    return new DataSchema(columnNames, columnDataTypes);
+  }
+
+  /**
+   * A private class used to build a sorted list by adding partially sorted data.
+   *
+   * Specifically, this class has been designed to receive successive calls to {@link #add(Object[])} follow by a single
+   * call to {@link #build()}. Once this method is called, the behavior of this object is undefined and therefore it
+   * should not be used.
+   *
+   * Rows must be inserted in ascending order accordingly to the partial order specified by a comparator.
+   * This comparator will define <i>partitions</i> of rows. All the rows in the same partition same are considered equal
+   * by that comparator.
+   *
+   * Some implementations, like {@link PartiallySortedListBuilder} accepts a second comparator that is used to sort rows
+   * inside each partition.
+   * When calling {@link #add(Object[])} with a row that doesn't belong to the current partition, a new one is started
+   * and the previous one is sorted. Therefore, this object maintains the invariant that at any moment there are at
+   * least {@link #sortedSize()} elements that are completely sorted, which means that no matter which elements are
+   * added after that, these elements are going to be smallest.
+   */
+  protected interface ListBuilder {
+
+    /**
+     * Adds the given row to this object. The new column must be equal or higher than the partition comparator.
+     *
+     * @param row The row to add. The values of the already sorted columns must be equal or higher than the last added
+     *           row, if any.
+     * @return true if and only if the previous partition was closed.
+     */
+    boolean add(Object[] row);
+
+    /**
+     * Builds the sorted list. The returned list will be sorted, even if a previous call t o {@link #sortedSize()}
+     * returned a number lower than the number of elements that have been added.
+     *
+     * Once this method is called, the builder should not be used. There is no guaranteed on whether
+     * {@link #sortedSize()} is updated or not.
+     */
+    List<Object[]> build();
+
+    /**
+     * How many elements are actually sorted. This number is lower or equal to the number of elements that has been
+     * added.
+     */
+    int sortedSize();
+  }
+
+  /**
+   * This is the faster {@link ListBuilder} but also the most restrictive one. It can only be used when data is inserted
+   * in total order. Therefore it cannot be used to implement order-by queries where there is at least one expression
+   * that is not sorted. In such case {@link PartiallySortedListBuilder} should be used.
+   *
+   * This implementation is just a wrapper over an ArrayList and therefore the average costs of its methods is constant.
+   */
+  protected static class TotallySortedListBuilder implements ListBuilder {
+    private final ArrayList<Object[]> _list;
+
+    public TotallySortedListBuilder(int expectedSize) {
+      _list = new ArrayList<>(expectedSize);
+    }
+
+    @Override
+    public boolean add(Object[] row) {
+      _list.add(row);
+      return true;
+    }
+
+    @Override
+    public List<Object[]> build() {
+      return _list;
+    }
+
+    @Override
+    public int sortedSize() {
+      return _list.size();
+    }
+  }
+
+  /**
+   * This is the more versatile {@link ListBuilder} that requires two comparators: The first defines the order on which
+   * {@link #add(Object[])} is called and defines the partitions. The second one is used to sort rows in the same
+   * partition. This class can be used to implement order-by queries that include one or more not sorted expressions.
+   * In cases where all expressions are sorted, {@link TotallySortedListBuilder} should be used because its performance
+   * is better.
+   *
+   * In this implementation the {@link #add(Object[])} method has a log(P) cost, where P is the number of elements in
+   * each partition. In normal cases we can consider P a constant. In some degenerated cases like having an ordering by
+   * a sorted column whose values are all equal, P may tend to the number of elements in the segment, which would make
+   * the cost of this method log(N).
+   *
+   * This class is optimized for scenarios where the partitions are smaller than the limit. In that case, the partition
+   * is only sorted once it is closed (aka when a new element for the other partition is found), so each insertion has
+   * an average cost of log(P) (where P-1 insertions are cost O(1) and the last one is O(PlogP)). In cases where at
+   * least one partition is larger than the limit, this implementation delegates the last partition to a
+   * {@link PriorityQueue}.
+   */
+  private static class PartiallySortedListBuilder implements ListBuilder {
+    private final ArrayList<Object[]> _rows;
+    /**
+     * The comparator that defines the partitions and the one that impose in which order add has to be called.
+     */
+    private final Comparator<Object[]> _partitionComparator;
+    /**
+     * The comparator that sorts different rows on each partition.
+     */
+    private final Comparator<Object[]> _unsortedComparator;
+    @Nullable
+    private Object[] _lastPartitionRow;
+    /**
+     * How many elements are already sorted. This is also the index where the last (and still not sorted) partition
+     * starts or should start.
+     */
+    private int _sortedPrefixSize;
+    private final int _maxSize;
+    private PriorityQueue<Object[]> _queue = null;
+    private int _maxPriorityQueueValues;
+
+    public PartiallySortedListBuilder(int maxSize, Comparator<Object[]> partitionComparator,
+        Comparator<Object[]> unsortedComparator) {
+      Preconditions.checkArgument(maxSize > 0, "Max size must be greater than 0");
+      _maxSize = maxSize;
+      _rows = new ArrayList<>(maxSize);
+      _partitionComparator = partitionComparator;
+      _unsortedComparator = unsortedComparator;
+    }
+
+    @Override
+    public boolean add(Object[] row) {
+      boolean result;
+      if (_lastPartitionRow == null) {
+        _sortedPrefixSize = 0;
+        _lastPartitionRow = row;
+        _rows.add(row);
+        return false;
+      } else {
+        int cmp = _partitionComparator.compare(row, _lastPartitionRow);
+        if (cmp < 0) {
+          throw new IllegalArgumentException("Row " + Arrays.toString(row) + " is lower than previously added row"
+              + Arrays.toString(_lastPartitionRow));
+        }
+
+        if (_queue != null) {
+          if (cmp > 0) {
+            // the new row is in a greater partition, just don't add it and continue
+            return true;
+          }
+          // otherwise they are equal by the already sorted columns. Let's check the other columns and evict the higher
+          // also, we have the higher value at the last position
+          SelectionOperatorUtils.addToPriorityQueue(row, _queue, _maxPriorityQueueValues);
+          return false;
+        } else {
+          if (_rows.size() == _maxSize) { // we already have _maxSize results
+            if (cmp > 0) {
+              // and the new one is higher, so we don't need to add it
+              sortLastPartition();
+              return true;
+            }
+            // and the new one may be smaller, so this is going to be the last partition and we need to prepare the
+            // priority queue
+            buildPriorityQueue();
+            SelectionOperatorUtils.addToPriorityQueue(row, _queue, _maxPriorityQueueValues);
+            return false;
+          }
+          if (cmp > 0) {
+            sortLastPartition();
+            _lastPartitionRow = row;
+            result = true;
+          } else {
+            result = false;
+          }
+          _rows.add(row);
+          return result;
+        }
+      }
+    }
+
+    private void buildPriorityQueue() {
+      _maxPriorityQueueValues = _maxSize - _sortedPrefixSize;
+      _queue = new PriorityQueue<>(_maxPriorityQueueValues, _unsortedComparator.reversed());
+      for (int i = 0; i < _maxPriorityQueueValues; i++) {
+        int lastIdx = _rows.size() - 1;
+        _queue.add(_rows.get(lastIdx));
+        _rows.remove(lastIdx);
+      }
+    }
+
+    void sortLastPartition() {

Review Comment:
   We don't need to sort within the partition because we will convert it into a PQ in the combining phase. For the min-max based combine, since the partitions are sorted, it should work properly.



##########
pinot-core/src/main/java/org/apache/pinot/core/operator/query/LinearSelectionOrderByOperator.java:
##########
@@ -0,0 +1,476 @@
+/**
+ * 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.pinot.core.operator.query;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+import java.util.PriorityQueue;
+import java.util.function.IntFunction;
+import java.util.function.Supplier;
+import javax.annotation.Nullable;
+import org.apache.pinot.common.request.context.ExpressionContext;
+import org.apache.pinot.common.request.context.OrderByExpressionContext;
+import org.apache.pinot.common.utils.DataSchema;
+import org.apache.pinot.core.common.BlockValSet;
+import org.apache.pinot.core.common.Operator;
+import org.apache.pinot.core.common.RowBasedBlockValueFetcher;
+import org.apache.pinot.core.operator.BaseOperator;
+import org.apache.pinot.core.operator.ExecutionStatistics;
+import org.apache.pinot.core.operator.blocks.TransformBlock;
+import org.apache.pinot.core.operator.blocks.results.SelectionResultsBlock;
+import org.apache.pinot.core.operator.transform.TransformOperator;
+import org.apache.pinot.core.operator.transform.TransformResultMetadata;
+import org.apache.pinot.core.query.request.context.QueryContext;
+import org.apache.pinot.core.query.selection.SelectionOperatorUtils;
+import org.apache.pinot.segment.spi.IndexSegment;
+import org.roaringbitmap.RoaringBitmap;
+
+
+/**
+ * A selection Operator used when the first expressions in the order by are identifier expressions of columns that are
+ * already sorted (either ascendingly or descendingly), even if the tail of order by expressions are not sorted.
+ *
+ * ie: SELECT ... FROM Table WHERE predicates ORDER BY sorted_column DESC LIMIT 10 OFFSET 5
+ * or: SELECT ... FROM Table WHERE predicates ORDER BY sorted_column, not_sorted LIMIT 10 OFFSET 5
+ * but not SELECT ... FROM Table WHERE predicates ORDER BY not_sorted, sorted_column LIMIT 10 OFFSET 5
+ *
+ * Operators that derives from this class are going to have an almost linear cost instead of the usual NlogN when actual
+ * sorting must be done, where N is the number of rows in the segment.
+ * There is a degraded scenario when the cost is actually NlogL (where L is the limit of the query) when all the first L
+ * rows have the exact same value for the prefix of the sorted columns. Even in that case, L should be quite smaller
+ * than N, so this implementation is algorithmically better than the normal solution.
+ */
+public abstract class LinearSelectionOrderByOperator extends BaseOperator<SelectionResultsBlock> {
+  protected final IndexSegment _indexSegment;
+
+  protected final boolean _nullHandlingEnabled;
+  // Deduped order-by expressions followed by output expressions from SelectionOperatorUtils.extractExpressions()
+  protected final List<ExpressionContext> _expressions;
+  protected final List<ExpressionContext> _alreadySorted;
+  protected final List<ExpressionContext> _toSort;
+
+  protected final TransformOperator _transformOperator;
+  protected final List<OrderByExpressionContext> _orderByExpressions;
+  protected final TransformResultMetadata[] _expressionsMetadata;
+  protected final int _numRowsToKeep;
+  private final Supplier<ListBuilder> _listBuilderSupplier;
+  protected boolean _used = false;
+  protected Comparator<Object[]> _comparator;
+
+  /**
+   *
+   * @param expressions order by expressions must be at the head of the list.
+   * @param sortedExpr How many expressions at the head of the expression list are going to be considered sorted by
+   * {@link #fetch(Supplier<ListBuilder>)}
+   */
+  public LinearSelectionOrderByOperator(IndexSegment indexSegment, QueryContext queryContext,
+      List<ExpressionContext> expressions, TransformOperator transformOperator,
+      int sortedExpr) {
+    _indexSegment = indexSegment;
+    _nullHandlingEnabled = queryContext.isNullHandlingEnabled();
+    _expressions = expressions;
+    _transformOperator = transformOperator;
+
+    _orderByExpressions = queryContext.getOrderByExpressions();
+    assert _orderByExpressions != null;
+    int numOrderByExpressions = _orderByExpressions.size();
+
+    _alreadySorted = expressions.subList(0, sortedExpr);
+    _toSort = expressions.subList(sortedExpr, numOrderByExpressions);
+
+    _expressionsMetadata = new TransformResultMetadata[_expressions.size()];
+    for (int i = 0; i < _expressionsMetadata.length; i++) {
+      ExpressionContext expression = _expressions.get(i);
+      _expressionsMetadata[i] = _transformOperator.getResultMetadata(expression);
+    }
+
+    _numRowsToKeep = queryContext.getOffset() + queryContext.getLimit();
+
+    if (_toSort.isEmpty()) {
+      int expectedSize = Math.min(SelectionOperatorUtils.MAX_ROW_HOLDER_INITIAL_CAPACITY, _numRowsToKeep);
+      _listBuilderSupplier = () -> new TotallySortedListBuilder(expectedSize);
+    } else {
+      int maxSize = Math.min(SelectionOperatorUtils.MAX_ROW_HOLDER_INITIAL_CAPACITY, _numRowsToKeep * 2);
+
+      Comparator<Object[]> sortedComparator = OrderByComparatorFactory.getComparator(_orderByExpressions,
+          _expressionsMetadata, true, _nullHandlingEnabled, 0, sortedExpr);
+      Comparator<Object[]> unsortedComparator = OrderByComparatorFactory.getComparator(_orderByExpressions,
+          _expressionsMetadata, true, _nullHandlingEnabled, sortedExpr, numOrderByExpressions);
+      _listBuilderSupplier = () -> new PartiallySortedListBuilder(maxSize, sortedComparator, unsortedComparator);
+    }
+
+    _comparator =
+        OrderByComparatorFactory.getComparator(_orderByExpressions, _expressionsMetadata, false, _nullHandlingEnabled);
+  }
+
+  @Override
+  public IndexSegment getIndexSegment() {
+    return _indexSegment;
+  }
+
+  @Override
+  public ExecutionStatistics getExecutionStatistics() {
+    long numEntriesScannedInFilter = _transformOperator.getExecutionStatistics().getNumEntriesScannedInFilter();
+    int numTotalDocs = _indexSegment.getSegmentMetadata().getTotalDocs();
+    return new ExecutionStatistics(getNumDocsScanned(), numEntriesScannedInFilter, getNumEntriesScannedPostFilter(),
+        numTotalDocs);
+  }
+
+  protected IntFunction<Object[]> fetchBlock(TransformBlock transformBlock, BlockValSet[] blockValSets) {
+    int numExpressions = _expressions.size();
+
+    for (int i = 0; i < numExpressions; i++) {
+      ExpressionContext expression = _expressions.get(i);
+      blockValSets[i] = transformBlock.getBlockValueSet(expression);
+    }
+    RowBasedBlockValueFetcher blockValueFetcher = new RowBasedBlockValueFetcher(blockValSets);
+
+    if (!_nullHandlingEnabled) {
+      return blockValueFetcher::getRow;
+    }
+    RoaringBitmap[] nullBitmaps = new RoaringBitmap[numExpressions];
+    for (int i = 0; i < numExpressions; i++) {
+      nullBitmaps[i] = blockValSets[i].getNullBitmap();
+    }
+    return (docId) -> {
+      Object[] row = blockValueFetcher.getRow(docId);
+      for (int colId = 0; colId < nullBitmaps.length; colId++) {
+        if (nullBitmaps[colId] != null && nullBitmaps[colId].contains(docId)) {
+          row[colId] = null;
+        }
+      }
+      return row;
+    };
+  }
+
+  protected abstract long getNumEntriesScannedPostFilter();
+
+  protected abstract int getNumDocsScanned();
+
+  /**
+   * Returns a list of rows sorted that:
+   * <ul>
+   *   <li>At least contains all the rows that fulfill the predicate</li>
+   *   <li>Rows are sorted in a way that is compatible with the given list builder supplier</li>
+   * </ul>
+   *
+   * That means that the result may contain more rows than required.
+   *
+   * @param listBuilderSupplier a {@link ListBuilder} supplier that should be used to create the result. Each time is
+   *                            called a new {@link ListBuilder} will be returned. All returned instances use the same
+   *                            comparator logic.
+   */
+  protected abstract List<Object[]> fetch(Supplier<ListBuilder> listBuilderSupplier);
+
+  @Override
+  public List<Operator> getChildOperators() {
+    return Collections.singletonList(_transformOperator);
+  }
+
+  protected abstract String getExplainName();
+
+  @Override
+  public String toExplainString() {
+    StringBuilder sb = new StringBuilder(getExplainName());
+
+    sb.append("(sortedList: ");
+    concatList(sb, _alreadySorted);
+
+    sb.append(", unsortedList: ");
+    concatList(sb, _toSort);
+
+    sb.append(", rest: ");
+    concatList(sb, _expressions.subList(_alreadySorted.size() + _toSort.size(), _expressions.size()));
+
+    sb.append(')');
+    return sb.toString();
+  }
+
+  private void concatList(StringBuilder sb, List<?> list) {
+    sb.append('(');
+    Iterator<?> it = list.iterator();
+    if (it.hasNext()) {
+      sb.append(it.next());
+      while (it.hasNext()) {
+        sb.append(", ").append(it.next());
+      }
+    }
+    sb.append(')');
+  }
+
+  @Override
+  protected SelectionResultsBlock getNextBlock() {
+    Preconditions.checkState(!_used, "nextBlock was called more than once");
+    _used = true;
+    List<Object[]> list = fetch(_listBuilderSupplier);
+
+    DataSchema dataSchema = createDataSchema();
+
+    if (list.size() > _numRowsToKeep) {
+      list = new ArrayList<>(list.subList(0, _numRowsToKeep));
+    }
+
+    SelectionResultsBlock resultsBlock = new SelectionResultsBlock(dataSchema, list, _comparator);
+
+    return resultsBlock;
+  }
+
+  protected DataSchema createDataSchema() {
+    int numExpressions = _expressions.size();
+
+    // Create the data schema
+    String[] columnNames = new String[numExpressions];
+    DataSchema.ColumnDataType[] columnDataTypes = new DataSchema.ColumnDataType[numExpressions];
+    for (int i = 0; i < columnNames.length; i++) {
+      columnNames[i] = _expressions.get(i).toString();
+    }
+    for (int i = 0; i < numExpressions; i++) {
+      TransformResultMetadata expressionMetadata = _expressionsMetadata[i];
+      columnDataTypes[i] =
+          DataSchema.ColumnDataType.fromDataType(expressionMetadata.getDataType(), expressionMetadata.isSingleValue());
+    }
+    return new DataSchema(columnNames, columnDataTypes);
+  }
+
+  /**
+   * A private class used to build a sorted list by adding partially sorted data.
+   *
+   * Specifically, this class has been designed to receive successive calls to {@link #add(Object[])} follow by a single
+   * call to {@link #build()}. Once this method is called, the behavior of this object is undefined and therefore it
+   * should not be used.
+   *
+   * Rows must be inserted in ascending order accordingly to the partial order specified by a comparator.
+   * This comparator will define <i>partitions</i> of rows. All the rows in the same partition same are considered equal
+   * by that comparator.
+   *
+   * Some implementations, like {@link PartiallySortedListBuilder} accepts a second comparator that is used to sort rows
+   * inside each partition.
+   * When calling {@link #add(Object[])} with a row that doesn't belong to the current partition, a new one is started
+   * and the previous one is sorted. Therefore, this object maintains the invariant that at any moment there are at
+   * least {@link #sortedSize()} elements that are completely sorted, which means that no matter which elements are
+   * added after that, these elements are going to be smallest.
+   */
+  protected interface ListBuilder {
+
+    /**
+     * Adds the given row to this object. The new column must be equal or higher than the partition comparator.
+     *
+     * @param row The row to add. The values of the already sorted columns must be equal or higher than the last added
+     *           row, if any.
+     * @return true if and only if the previous partition was closed.
+     */
+    boolean add(Object[] row);
+
+    /**
+     * Builds the sorted list. The returned list will be sorted, even if a previous call t o {@link #sortedSize()}
+     * returned a number lower than the number of elements that have been added.
+     *
+     * Once this method is called, the builder should not be used. There is no guaranteed on whether
+     * {@link #sortedSize()} is updated or not.
+     */
+    List<Object[]> build();
+
+    /**
+     * How many elements are actually sorted. This number is lower or equal to the number of elements that has been
+     * added.
+     */
+    int sortedSize();
+  }
+
+  /**
+   * This is the faster {@link ListBuilder} but also the most restrictive one. It can only be used when data is inserted
+   * in total order. Therefore it cannot be used to implement order-by queries where there is at least one expression
+   * that is not sorted. In such case {@link PartiallySortedListBuilder} should be used.
+   *
+   * This implementation is just a wrapper over an ArrayList and therefore the average costs of its methods is constant.
+   */
+  protected static class TotallySortedListBuilder implements ListBuilder {
+    private final ArrayList<Object[]> _list;
+
+    public TotallySortedListBuilder(int expectedSize) {
+      _list = new ArrayList<>(expectedSize);
+    }
+
+    @Override
+    public boolean add(Object[] row) {
+      _list.add(row);
+      return true;
+    }
+
+    @Override
+    public List<Object[]> build() {
+      return _list;
+    }
+
+    @Override
+    public int sortedSize() {
+      return _list.size();
+    }
+  }
+
+  /**
+   * This is the more versatile {@link ListBuilder} that requires two comparators: The first defines the order on which
+   * {@link #add(Object[])} is called and defines the partitions. The second one is used to sort rows in the same
+   * partition. This class can be used to implement order-by queries that include one or more not sorted expressions.
+   * In cases where all expressions are sorted, {@link TotallySortedListBuilder} should be used because its performance
+   * is better.
+   *
+   * In this implementation the {@link #add(Object[])} method has a log(P) cost, where P is the number of elements in
+   * each partition. In normal cases we can consider P a constant. In some degenerated cases like having an ordering by
+   * a sorted column whose values are all equal, P may tend to the number of elements in the segment, which would make
+   * the cost of this method log(N).
+   *
+   * This class is optimized for scenarios where the partitions are smaller than the limit. In that case, the partition
+   * is only sorted once it is closed (aka when a new element for the other partition is found), so each insertion has
+   * an average cost of log(P) (where P-1 insertions are cost O(1) and the last one is O(PlogP)). In cases where at
+   * least one partition is larger than the limit, this implementation delegates the last partition to a
+   * {@link PriorityQueue}.
+   */
+  private static class PartiallySortedListBuilder implements ListBuilder {
+    private final ArrayList<Object[]> _rows;
+    /**
+     * The comparator that defines the partitions and the one that impose in which order add has to be called.
+     */
+    private final Comparator<Object[]> _partitionComparator;
+    /**
+     * The comparator that sorts different rows on each partition.
+     */
+    private final Comparator<Object[]> _unsortedComparator;
+    @Nullable
+    private Object[] _lastPartitionRow;
+    /**
+     * How many elements are already sorted. This is also the index where the last (and still not sorted) partition
+     * starts or should start.
+     */
+    private int _sortedPrefixSize;
+    private final int _maxSize;
+    private PriorityQueue<Object[]> _queue = null;
+    private int _maxPriorityQueueValues;
+
+    public PartiallySortedListBuilder(int maxSize, Comparator<Object[]> partitionComparator,
+        Comparator<Object[]> unsortedComparator) {
+      Preconditions.checkArgument(maxSize > 0, "Max size must be greater than 0");
+      _maxSize = maxSize;
+      _rows = new ArrayList<>(maxSize);
+      _partitionComparator = partitionComparator;
+      _unsortedComparator = unsortedComparator;
+    }
+
+    @Override
+    public boolean add(Object[] row) {
+      boolean result;
+      if (_lastPartitionRow == null) {
+        _sortedPrefixSize = 0;
+        _lastPartitionRow = row;
+        _rows.add(row);
+        return false;
+      } else {
+        int cmp = _partitionComparator.compare(row, _lastPartitionRow);
+        if (cmp < 0) {
+          throw new IllegalArgumentException("Row " + Arrays.toString(row) + " is lower than previously added row"
+              + Arrays.toString(_lastPartitionRow));
+        }
+
+        if (_queue != null) {
+          if (cmp > 0) {
+            // the new row is in a greater partition, just don't add it and continue
+            return true;
+          }
+          // otherwise they are equal by the already sorted columns. Let's check the other columns and evict the higher
+          // also, we have the higher value at the last position
+          SelectionOperatorUtils.addToPriorityQueue(row, _queue, _maxPriorityQueueValues);
+          return false;
+        } else {
+          if (_rows.size() == _maxSize) { // we already have _maxSize results
+            if (cmp > 0) {
+              // and the new one is higher, so we don't need to add it
+              sortLastPartition();
+              return true;
+            }
+            // and the new one may be smaller, so this is going to be the last partition and we need to prepare the
+            // priority queue
+            buildPriorityQueue();
+            SelectionOperatorUtils.addToPriorityQueue(row, _queue, _maxPriorityQueueValues);
+            return false;
+          }
+          if (cmp > 0) {
+            sortLastPartition();
+            _lastPartitionRow = row;
+            result = true;
+          } else {
+            result = false;
+          }
+          _rows.add(row);
+          return result;
+        }
+      }
+    }
+
+    private void buildPriorityQueue() {
+      _maxPriorityQueueValues = _maxSize - _sortedPrefixSize;
+      _queue = new PriorityQueue<>(_maxPriorityQueueValues, _unsortedComparator.reversed());
+      for (int i = 0; i < _maxPriorityQueueValues; i++) {
+        int lastIdx = _rows.size() - 1;
+        _queue.add(_rows.get(lastIdx));
+        _rows.remove(lastIdx);
+      }
+    }
+
+    void sortLastPartition() {
+      int size = _rows.size();
+      if (_sortedPrefixSize != size) {
+        List<Object[]> lastsPartition = _rows.subList(_sortedPrefixSize, size);
+        lastsPartition.sort(_unsortedComparator);
+        _sortedPrefixSize = size;
+      }
+    }
+
+    /**
+     * Sorts the rows and returns the sorted list.
+     *
+     * This object should not be used once this method is called.
+     *
+     * @return the list of all added rows, sorted by {@link #_partitionComparator} and then by
+     * {@link #_unsortedComparator}
+     */
+    @Override
+    public List<Object[]> build() {
+      if (_queue != null) {
+        _rows.addAll(_queue);
+        // queue is sorted in the reverse order, so we need to reverse this partition

Review Comment:
   Reverse won't work because the iterator for PQ won't return results in order. But as commented above, we shouldn't need to sort the rows within the partition



##########
pinot-core/src/main/java/org/apache/pinot/core/operator/combine/MinMaxValueBasedSelectionOrderByCombineOperator.java:
##########
@@ -211,30 +211,51 @@ protected void processSegments() {
           ((AcquireReleaseColumnsSegmentOperator) operator).release();
         }
       }
-      PriorityQueue<Object[]> selectionResult = (PriorityQueue<Object[]>) resultsBlock.getRows();
-      if (selectionResult != null && selectionResult.size() == _numRowsToKeep) {
-        // Segment result has enough rows, update the boundary value
-        assert selectionResult.peek() != null;
-        Comparable segmentBoundaryValue = (Comparable) selectionResult.peek()[0];
-        if (boundaryValue == null) {
-          boundaryValue = segmentBoundaryValue;
-        } else {
-          if (asc) {
-            if (segmentBoundaryValue.compareTo(boundaryValue) < 0) {
-              boundaryValue = segmentBoundaryValue;
-            }
-          } else {
-            if (segmentBoundaryValue.compareTo(boundaryValue) > 0) {
-              boundaryValue = segmentBoundaryValue;
-            }
-          }
-        }
+      Collection<Object[]> rows = resultsBlock.getRows();
+      if (rows != null && rows.size() >= _numRowsToKeep) {
+        boundaryValue = updateBoundaryValue(boundaryValue, extractBoundaryValue(rows), asc);
       }
       threadBoundaryValue = boundaryValue;
       _blockingQueue.offer(resultsBlock);
     }
   }
 
+  private Comparable extractBoundaryValue(Collection<Object[]> rows) {
+    if (rows instanceof PriorityQueue) {
+      PriorityQueue<Object[]> selectionResult = (PriorityQueue<Object[]>) rows;
+      assert selectionResult.peek() != null;
+      // at this point, priority queues are sorted in the inverse order
+      return (Comparable) selectionResult.peek()[0];
+    }
+    List<Object[]> selectionResult;
+    if (rows instanceof List) {
+      selectionResult = (List<Object[]>) rows;
+    } else {
+      LOGGER.warn("Selection result stored in an unexpected data structure of type {}. A copy is needed",
+          rows.getClass());
+      selectionResult = new ArrayList<>(rows);
+    }
+    int index = selectionResult.size() - 1;
+    return (Comparable) selectionResult.get(index)[0];
+  }
+
+  private Comparable updateBoundaryValue(Comparable oldBoundary, Comparable newBoundary, boolean asc) {

Review Comment:
   (minor) this can be static



##########
pinot-core/src/main/java/org/apache/pinot/core/operator/query/SelectionOrderByOperator.java:
##########
@@ -83,18 +79,18 @@ public class SelectionOrderByOperator extends BaseOperator<SelectionResultsBlock
   private final TransformResultMetadata[] _orderByExpressionMetadata;
   private final int _numRowsToKeep;
   private final PriorityQueue<Object[]> _rows;
-  private final boolean _allOrderByColsPreSorted;
 
   private int _numDocsScanned = 0;
   private long _numEntriesScannedPostFilter = 0;
 
+  private final boolean _queryHasMVSelectionOrderBy;

Review Comment:
   Remove this. I think this is a rebase error



##########
pinot-core/src/main/java/org/apache/pinot/core/operator/query/LinearSelectionOrderByOperator.java:
##########
@@ -0,0 +1,476 @@
+/**
+ * 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.pinot.core.operator.query;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+import java.util.PriorityQueue;
+import java.util.function.IntFunction;
+import java.util.function.Supplier;
+import javax.annotation.Nullable;
+import org.apache.pinot.common.request.context.ExpressionContext;
+import org.apache.pinot.common.request.context.OrderByExpressionContext;
+import org.apache.pinot.common.utils.DataSchema;
+import org.apache.pinot.core.common.BlockValSet;
+import org.apache.pinot.core.common.Operator;
+import org.apache.pinot.core.common.RowBasedBlockValueFetcher;
+import org.apache.pinot.core.operator.BaseOperator;
+import org.apache.pinot.core.operator.ExecutionStatistics;
+import org.apache.pinot.core.operator.blocks.TransformBlock;
+import org.apache.pinot.core.operator.blocks.results.SelectionResultsBlock;
+import org.apache.pinot.core.operator.transform.TransformOperator;
+import org.apache.pinot.core.operator.transform.TransformResultMetadata;
+import org.apache.pinot.core.query.request.context.QueryContext;
+import org.apache.pinot.core.query.selection.SelectionOperatorUtils;
+import org.apache.pinot.segment.spi.IndexSegment;
+import org.roaringbitmap.RoaringBitmap;
+
+
+/**
+ * A selection Operator used when the first expressions in the order by are identifier expressions of columns that are
+ * already sorted (either ascendingly or descendingly), even if the tail of order by expressions are not sorted.
+ *
+ * ie: SELECT ... FROM Table WHERE predicates ORDER BY sorted_column DESC LIMIT 10 OFFSET 5
+ * or: SELECT ... FROM Table WHERE predicates ORDER BY sorted_column, not_sorted LIMIT 10 OFFSET 5
+ * but not SELECT ... FROM Table WHERE predicates ORDER BY not_sorted, sorted_column LIMIT 10 OFFSET 5
+ *
+ * Operators that derives from this class are going to have an almost linear cost instead of the usual NlogN when actual
+ * sorting must be done, where N is the number of rows in the segment.
+ * There is a degraded scenario when the cost is actually NlogL (where L is the limit of the query) when all the first L
+ * rows have the exact same value for the prefix of the sorted columns. Even in that case, L should be quite smaller
+ * than N, so this implementation is algorithmically better than the normal solution.
+ */
+public abstract class LinearSelectionOrderByOperator extends BaseOperator<SelectionResultsBlock> {
+  protected final IndexSegment _indexSegment;
+
+  protected final boolean _nullHandlingEnabled;
+  // Deduped order-by expressions followed by output expressions from SelectionOperatorUtils.extractExpressions()
+  protected final List<ExpressionContext> _expressions;
+  protected final List<ExpressionContext> _alreadySorted;
+  protected final List<ExpressionContext> _toSort;
+
+  protected final TransformOperator _transformOperator;
+  protected final List<OrderByExpressionContext> _orderByExpressions;
+  protected final TransformResultMetadata[] _expressionsMetadata;
+  protected final int _numRowsToKeep;
+  private final Supplier<ListBuilder> _listBuilderSupplier;
+  protected boolean _used = false;
+  protected Comparator<Object[]> _comparator;
+
+  /**
+   *
+   * @param expressions order by expressions must be at the head of the list.
+   * @param sortedExpr How many expressions at the head of the expression list are going to be considered sorted by
+   * {@link #fetch(Supplier<ListBuilder>)}
+   */
+  public LinearSelectionOrderByOperator(IndexSegment indexSegment, QueryContext queryContext,
+      List<ExpressionContext> expressions, TransformOperator transformOperator,
+      int sortedExpr) {
+    _indexSegment = indexSegment;
+    _nullHandlingEnabled = queryContext.isNullHandlingEnabled();
+    _expressions = expressions;
+    _transformOperator = transformOperator;
+
+    _orderByExpressions = queryContext.getOrderByExpressions();
+    assert _orderByExpressions != null;
+    int numOrderByExpressions = _orderByExpressions.size();
+
+    _alreadySorted = expressions.subList(0, sortedExpr);
+    _toSort = expressions.subList(sortedExpr, numOrderByExpressions);
+
+    _expressionsMetadata = new TransformResultMetadata[_expressions.size()];
+    for (int i = 0; i < _expressionsMetadata.length; i++) {
+      ExpressionContext expression = _expressions.get(i);
+      _expressionsMetadata[i] = _transformOperator.getResultMetadata(expression);
+    }
+
+    _numRowsToKeep = queryContext.getOffset() + queryContext.getLimit();
+
+    if (_toSort.isEmpty()) {
+      int expectedSize = Math.min(SelectionOperatorUtils.MAX_ROW_HOLDER_INITIAL_CAPACITY, _numRowsToKeep);
+      _listBuilderSupplier = () -> new TotallySortedListBuilder(expectedSize);
+    } else {
+      int maxSize = Math.min(SelectionOperatorUtils.MAX_ROW_HOLDER_INITIAL_CAPACITY, _numRowsToKeep * 2);
+
+      Comparator<Object[]> sortedComparator = OrderByComparatorFactory.getComparator(_orderByExpressions,
+          _expressionsMetadata, true, _nullHandlingEnabled, 0, sortedExpr);
+      Comparator<Object[]> unsortedComparator = OrderByComparatorFactory.getComparator(_orderByExpressions,
+          _expressionsMetadata, true, _nullHandlingEnabled, sortedExpr, numOrderByExpressions);
+      _listBuilderSupplier = () -> new PartiallySortedListBuilder(maxSize, sortedComparator, unsortedComparator);
+    }
+
+    _comparator =
+        OrderByComparatorFactory.getComparator(_orderByExpressions, _expressionsMetadata, false, _nullHandlingEnabled);
+  }
+
+  @Override
+  public IndexSegment getIndexSegment() {
+    return _indexSegment;
+  }
+
+  @Override
+  public ExecutionStatistics getExecutionStatistics() {
+    long numEntriesScannedInFilter = _transformOperator.getExecutionStatistics().getNumEntriesScannedInFilter();
+    int numTotalDocs = _indexSegment.getSegmentMetadata().getTotalDocs();
+    return new ExecutionStatistics(getNumDocsScanned(), numEntriesScannedInFilter, getNumEntriesScannedPostFilter(),
+        numTotalDocs);
+  }
+
+  protected IntFunction<Object[]> fetchBlock(TransformBlock transformBlock, BlockValSet[] blockValSets) {
+    int numExpressions = _expressions.size();
+
+    for (int i = 0; i < numExpressions; i++) {
+      ExpressionContext expression = _expressions.get(i);
+      blockValSets[i] = transformBlock.getBlockValueSet(expression);
+    }
+    RowBasedBlockValueFetcher blockValueFetcher = new RowBasedBlockValueFetcher(blockValSets);
+
+    if (!_nullHandlingEnabled) {
+      return blockValueFetcher::getRow;
+    }
+    RoaringBitmap[] nullBitmaps = new RoaringBitmap[numExpressions];
+    for (int i = 0; i < numExpressions; i++) {
+      nullBitmaps[i] = blockValSets[i].getNullBitmap();
+    }
+    return (docId) -> {
+      Object[] row = blockValueFetcher.getRow(docId);
+      for (int colId = 0; colId < nullBitmaps.length; colId++) {
+        if (nullBitmaps[colId] != null && nullBitmaps[colId].contains(docId)) {
+          row[colId] = null;
+        }
+      }
+      return row;
+    };
+  }
+
+  protected abstract long getNumEntriesScannedPostFilter();
+
+  protected abstract int getNumDocsScanned();
+
+  /**
+   * Returns a list of rows sorted that:
+   * <ul>
+   *   <li>At least contains all the rows that fulfill the predicate</li>
+   *   <li>Rows are sorted in a way that is compatible with the given list builder supplier</li>
+   * </ul>
+   *
+   * That means that the result may contain more rows than required.
+   *
+   * @param listBuilderSupplier a {@link ListBuilder} supplier that should be used to create the result. Each time is
+   *                            called a new {@link ListBuilder} will be returned. All returned instances use the same
+   *                            comparator logic.
+   */
+  protected abstract List<Object[]> fetch(Supplier<ListBuilder> listBuilderSupplier);
+
+  @Override
+  public List<Operator> getChildOperators() {
+    return Collections.singletonList(_transformOperator);
+  }
+
+  protected abstract String getExplainName();
+
+  @Override
+  public String toExplainString() {
+    StringBuilder sb = new StringBuilder(getExplainName());
+
+    sb.append("(sortedList: ");
+    concatList(sb, _alreadySorted);
+
+    sb.append(", unsortedList: ");
+    concatList(sb, _toSort);
+
+    sb.append(", rest: ");
+    concatList(sb, _expressions.subList(_alreadySorted.size() + _toSort.size(), _expressions.size()));
+
+    sb.append(')');
+    return sb.toString();
+  }
+
+  private void concatList(StringBuilder sb, List<?> list) {
+    sb.append('(');
+    Iterator<?> it = list.iterator();
+    if (it.hasNext()) {
+      sb.append(it.next());
+      while (it.hasNext()) {
+        sb.append(", ").append(it.next());
+      }
+    }
+    sb.append(')');
+  }
+
+  @Override
+  protected SelectionResultsBlock getNextBlock() {
+    Preconditions.checkState(!_used, "nextBlock was called more than once");
+    _used = true;
+    List<Object[]> list = fetch(_listBuilderSupplier);
+
+    DataSchema dataSchema = createDataSchema();
+
+    if (list.size() > _numRowsToKeep) {
+      list = new ArrayList<>(list.subList(0, _numRowsToKeep));
+    }
+
+    SelectionResultsBlock resultsBlock = new SelectionResultsBlock(dataSchema, list, _comparator);
+
+    return resultsBlock;
+  }
+
+  protected DataSchema createDataSchema() {
+    int numExpressions = _expressions.size();
+
+    // Create the data schema
+    String[] columnNames = new String[numExpressions];
+    DataSchema.ColumnDataType[] columnDataTypes = new DataSchema.ColumnDataType[numExpressions];
+    for (int i = 0; i < columnNames.length; i++) {
+      columnNames[i] = _expressions.get(i).toString();
+    }
+    for (int i = 0; i < numExpressions; i++) {
+      TransformResultMetadata expressionMetadata = _expressionsMetadata[i];
+      columnDataTypes[i] =
+          DataSchema.ColumnDataType.fromDataType(expressionMetadata.getDataType(), expressionMetadata.isSingleValue());
+    }
+    return new DataSchema(columnNames, columnDataTypes);
+  }
+
+  /**
+   * A private class used to build a sorted list by adding partially sorted data.
+   *
+   * Specifically, this class has been designed to receive successive calls to {@link #add(Object[])} follow by a single
+   * call to {@link #build()}. Once this method is called, the behavior of this object is undefined and therefore it
+   * should not be used.
+   *
+   * Rows must be inserted in ascending order accordingly to the partial order specified by a comparator.
+   * This comparator will define <i>partitions</i> of rows. All the rows in the same partition same are considered equal
+   * by that comparator.
+   *
+   * Some implementations, like {@link PartiallySortedListBuilder} accepts a second comparator that is used to sort rows
+   * inside each partition.
+   * When calling {@link #add(Object[])} with a row that doesn't belong to the current partition, a new one is started
+   * and the previous one is sorted. Therefore, this object maintains the invariant that at any moment there are at
+   * least {@link #sortedSize()} elements that are completely sorted, which means that no matter which elements are
+   * added after that, these elements are going to be smallest.
+   */
+  protected interface ListBuilder {
+
+    /**
+     * Adds the given row to this object. The new column must be equal or higher than the partition comparator.
+     *
+     * @param row The row to add. The values of the already sorted columns must be equal or higher than the last added
+     *           row, if any.
+     * @return true if and only if the previous partition was closed.
+     */
+    boolean add(Object[] row);
+
+    /**
+     * Builds the sorted list. The returned list will be sorted, even if a previous call t o {@link #sortedSize()}
+     * returned a number lower than the number of elements that have been added.
+     *
+     * Once this method is called, the builder should not be used. There is no guaranteed on whether
+     * {@link #sortedSize()} is updated or not.
+     */
+    List<Object[]> build();
+
+    /**
+     * How many elements are actually sorted. This number is lower or equal to the number of elements that has been
+     * added.
+     */
+    int sortedSize();
+  }
+
+  /**
+   * This is the faster {@link ListBuilder} but also the most restrictive one. It can only be used when data is inserted
+   * in total order. Therefore it cannot be used to implement order-by queries where there is at least one expression
+   * that is not sorted. In such case {@link PartiallySortedListBuilder} should be used.
+   *
+   * This implementation is just a wrapper over an ArrayList and therefore the average costs of its methods is constant.
+   */
+  protected static class TotallySortedListBuilder implements ListBuilder {
+    private final ArrayList<Object[]> _list;
+
+    public TotallySortedListBuilder(int expectedSize) {
+      _list = new ArrayList<>(expectedSize);
+    }
+
+    @Override
+    public boolean add(Object[] row) {
+      _list.add(row);
+      return true;
+    }
+
+    @Override
+    public List<Object[]> build() {
+      return _list;
+    }
+
+    @Override
+    public int sortedSize() {
+      return _list.size();
+    }
+  }
+
+  /**
+   * This is the more versatile {@link ListBuilder} that requires two comparators: The first defines the order on which
+   * {@link #add(Object[])} is called and defines the partitions. The second one is used to sort rows in the same
+   * partition. This class can be used to implement order-by queries that include one or more not sorted expressions.
+   * In cases where all expressions are sorted, {@link TotallySortedListBuilder} should be used because its performance
+   * is better.
+   *
+   * In this implementation the {@link #add(Object[])} method has a log(P) cost, where P is the number of elements in
+   * each partition. In normal cases we can consider P a constant. In some degenerated cases like having an ordering by
+   * a sorted column whose values are all equal, P may tend to the number of elements in the segment, which would make
+   * the cost of this method log(N).
+   *
+   * This class is optimized for scenarios where the partitions are smaller than the limit. In that case, the partition
+   * is only sorted once it is closed (aka when a new element for the other partition is found), so each insertion has
+   * an average cost of log(P) (where P-1 insertions are cost O(1) and the last one is O(PlogP)). In cases where at
+   * least one partition is larger than the limit, this implementation delegates the last partition to a
+   * {@link PriorityQueue}.
+   */
+  private static class PartiallySortedListBuilder implements ListBuilder {
+    private final ArrayList<Object[]> _rows;
+    /**
+     * The comparator that defines the partitions and the one that impose in which order add has to be called.
+     */
+    private final Comparator<Object[]> _partitionComparator;
+    /**
+     * The comparator that sorts different rows on each partition.
+     */
+    private final Comparator<Object[]> _unsortedComparator;
+    @Nullable
+    private Object[] _lastPartitionRow;
+    /**
+     * How many elements are already sorted. This is also the index where the last (and still not sorted) partition
+     * starts or should start.
+     */
+    private int _sortedPrefixSize;
+    private final int _maxSize;
+    private PriorityQueue<Object[]> _queue = null;
+    private int _maxPriorityQueueValues;
+
+    public PartiallySortedListBuilder(int maxSize, Comparator<Object[]> partitionComparator,
+        Comparator<Object[]> unsortedComparator) {
+      Preconditions.checkArgument(maxSize > 0, "Max size must be greater than 0");
+      _maxSize = maxSize;
+      _rows = new ArrayList<>(maxSize);
+      _partitionComparator = partitionComparator;
+      _unsortedComparator = unsortedComparator;
+    }
+
+    @Override
+    public boolean add(Object[] row) {
+      boolean result;
+      if (_lastPartitionRow == null) {
+        _sortedPrefixSize = 0;
+        _lastPartitionRow = row;
+        _rows.add(row);
+        return false;
+      } else {
+        int cmp = _partitionComparator.compare(row, _lastPartitionRow);
+        if (cmp < 0) {
+          throw new IllegalArgumentException("Row " + Arrays.toString(row) + " is lower than previously added row"
+              + Arrays.toString(_lastPartitionRow));
+        }
+
+        if (_queue != null) {
+          if (cmp > 0) {
+            // the new row is in a greater partition, just don't add it and continue
+            return true;
+          }
+          // otherwise they are equal by the already sorted columns. Let's check the other columns and evict the higher
+          // also, we have the higher value at the last position
+          SelectionOperatorUtils.addToPriorityQueue(row, _queue, _maxPriorityQueueValues);
+          return false;
+        } else {
+          if (_rows.size() == _maxSize) { // we already have _maxSize results
+            if (cmp > 0) {
+              // and the new one is higher, so we don't need to add it
+              sortLastPartition();
+              return true;
+            }
+            // and the new one may be smaller, so this is going to be the last partition and we need to prepare the
+            // priority queue
+            buildPriorityQueue();
+            SelectionOperatorUtils.addToPriorityQueue(row, _queue, _maxPriorityQueueValues);
+            return false;
+          }
+          if (cmp > 0) {
+            sortLastPartition();
+            _lastPartitionRow = row;
+            result = true;
+          } else {
+            result = false;
+          }
+          _rows.add(row);
+          return result;
+        }
+      }
+    }
+
+    private void buildPriorityQueue() {
+      _maxPriorityQueueValues = _maxSize - _sortedPrefixSize;
+      _queue = new PriorityQueue<>(_maxPriorityQueueValues, _unsortedComparator.reversed());
+      for (int i = 0; i < _maxPriorityQueueValues; i++) {
+        int lastIdx = _rows.size() - 1;
+        _queue.add(_rows.get(lastIdx));
+        _rows.remove(lastIdx);

Review Comment:
   No need to remove rows here. We can use `set()` when adding rows from queue to the list to reduce overhead



##########
pinot-core/src/main/java/org/apache/pinot/core/operator/combine/MinMaxValueBasedSelectionOrderByCombineOperator.java:
##########
@@ -211,30 +211,51 @@ protected void processSegments() {
           ((AcquireReleaseColumnsSegmentOperator) operator).release();
         }
       }
-      PriorityQueue<Object[]> selectionResult = (PriorityQueue<Object[]>) resultsBlock.getRows();
-      if (selectionResult != null && selectionResult.size() == _numRowsToKeep) {
-        // Segment result has enough rows, update the boundary value
-        assert selectionResult.peek() != null;
-        Comparable segmentBoundaryValue = (Comparable) selectionResult.peek()[0];
-        if (boundaryValue == null) {
-          boundaryValue = segmentBoundaryValue;
-        } else {
-          if (asc) {
-            if (segmentBoundaryValue.compareTo(boundaryValue) < 0) {
-              boundaryValue = segmentBoundaryValue;
-            }
-          } else {
-            if (segmentBoundaryValue.compareTo(boundaryValue) > 0) {
-              boundaryValue = segmentBoundaryValue;
-            }
-          }
-        }
+      Collection<Object[]> rows = resultsBlock.getRows();
+      if (rows != null && rows.size() >= _numRowsToKeep) {
+        boundaryValue = updateBoundaryValue(boundaryValue, extractBoundaryValue(rows), asc);
       }
       threadBoundaryValue = boundaryValue;
       _blockingQueue.offer(resultsBlock);
     }
   }
 
+  private Comparable extractBoundaryValue(Collection<Object[]> rows) {
+    if (rows instanceof PriorityQueue) {
+      PriorityQueue<Object[]> selectionResult = (PriorityQueue<Object[]>) rows;
+      assert selectionResult.peek() != null;
+      // at this point, priority queues are sorted in the inverse order
+      return (Comparable) selectionResult.peek()[0];
+    }
+    List<Object[]> selectionResult;
+    if (rows instanceof List) {
+      selectionResult = (List<Object[]>) rows;
+    } else {
+      LOGGER.warn("Selection result stored in an unexpected data structure of type {}. A copy is needed",

Review Comment:
   We don't want to log warning here since this is unexpected behavior and can cause wrong result. Do an `assert` or `Preconditions.checkState()` instead



##########
pinot-core/src/main/java/org/apache/pinot/core/plan/SelectionPlanNode.java:
##########
@@ -50,67 +55,119 @@ public Operator<SelectionResultsBlock> run() {
     List<ExpressionContext> expressions = SelectionOperatorUtils.extractExpressions(_queryContext, _indexSegment);
     int limit = _queryContext.getLimit();
 
-    if (limit > 0) {
-      List<OrderByExpressionContext> orderByExpressions = _queryContext.getOrderByExpressions();
-      if (orderByExpressions == null) {
-        // Selection only
-        TransformOperator transformOperator = new TransformPlanNode(_indexSegment, _queryContext, expressions,
-            Math.min(limit, DocIdSetPlanNode.MAX_DOC_PER_CALL)).run();
-        return new SelectionOnlyOperator(_indexSegment, _queryContext, expressions, transformOperator);
-      } else {
-        // Selection order-by
-        if (isAllOrderByColumnsSorted(orderByExpressions)) {
-          // All order-by columns are sorted, no need to sort the records
-          TransformOperator transformOperator = new TransformPlanNode(_indexSegment, _queryContext, expressions,
-              Math.min(limit + _queryContext.getOffset(), DocIdSetPlanNode.MAX_DOC_PER_CALL)).run();
-          return new SelectionOrderByOperator(_indexSegment, _queryContext, expressions, transformOperator, true);
-        } else if (orderByExpressions.size() == expressions.size()) {
-          // All output expressions are ordered
-          TransformOperator transformOperator =
-              new TransformPlanNode(_indexSegment, _queryContext, expressions, DocIdSetPlanNode.MAX_DOC_PER_CALL).run();
-          return new SelectionOrderByOperator(_indexSegment, _queryContext, expressions, transformOperator, false);
-        } else {
-          // Not all output expressions are ordered, only fetch the order-by expressions and docId to avoid the
-          // unnecessary data fetch
-          List<ExpressionContext> expressionsToTransform = new ArrayList<>(orderByExpressions.size());
-          for (OrderByExpressionContext orderByExpression : orderByExpressions) {
-            expressionsToTransform.add(orderByExpression.getExpression());
-          }
-          TransformOperator transformOperator =
-              new TransformPlanNode(_indexSegment, _queryContext, expressionsToTransform,
-                  DocIdSetPlanNode.MAX_DOC_PER_CALL).run();
-          return new SelectionOrderByOperator(_indexSegment, _queryContext, expressions, transformOperator, false);
-        }
-      }
-    } else {
+    if (limit == 0) {
       // Empty selection (LIMIT 0)
       TransformOperator transformOperator = new TransformPlanNode(_indexSegment, _queryContext, expressions, 0).run();
       return new EmptySelectionOperator(_indexSegment, expressions, transformOperator);
     }
+    List<OrderByExpressionContext> orderByExpressions = _queryContext.getOrderByExpressions();
+    if (orderByExpressions == null) {
+      // Selection only
+      // ie: SELECT ... FROM Table WHERE ... LIMIT 10
+      int maxDocsPerCall = Math.min(limit, DocIdSetPlanNode.MAX_DOC_PER_CALL);
+      TransformPlanNode planNode = new TransformPlanNode(_indexSegment, _queryContext, expressions, maxDocsPerCall);
+      TransformOperator transformOperator = planNode.run();
+
+      return new SelectionOnlyOperator(_indexSegment, _queryContext, expressions, transformOperator);
+    }
+    int numOrderByExpressions = orderByExpressions.size();
+    // Although it is a break of abstraction, some code, specially merging, assumes that if there is an order by
+    // expression the operator will return a block whose selection result is a priority queue.
+    int sortedColumnsPrefixSize = getSortedColumnsPrefix(orderByExpressions, _queryContext.isNullHandlingEnabled());
+    if (sortedColumnsPrefixSize > 0 && !isSkipOrderByOptimization()) {
+      // The first order by expressions are sorted (either asc or desc).
+      // ie: SELECT ... FROM Table WHERE predicates ORDER BY sorted_column DESC LIMIT 10 OFFSET 5
+      // or: SELECT ... FROM Table WHERE predicates ORDER BY sorted_column, not_sorted LIMIT 10 OFFSET 5
+      // but not SELECT ... FROM Table WHERE predicates ORDER BY not_sorted, sorted_column LIMIT 10 OFFSET 5
+      if (orderByExpressions.get(0).isAsc()) {
+        int maxDocsPerCall = Math.min(limit + _queryContext.getOffset(), DocIdSetPlanNode.MAX_DOC_PER_CALL);
+        TransformPlanNode planNode = new TransformPlanNode(_indexSegment, _queryContext, expressions, maxDocsPerCall);
+        TransformOperator transformOperator = planNode.run();
+        return new SelectionPartiallyOrderedByAscOperator(_indexSegment, _queryContext, expressions,
+            transformOperator, sortedColumnsPrefixSize);
+      } else {
+        int maxDocsPerCall = DocIdSetPlanNode.MAX_DOC_PER_CALL;

Review Comment:
   We want to avoid using this optimization when `limit + offset` is too large. We can start with a threshold of `MAX_DOC_PER_CALL / 2`



##########
pinot-core/src/main/java/org/apache/pinot/core/operator/query/OrderByComparatorFactory.java:
##########
@@ -0,0 +1,170 @@
+/**
+ * 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.pinot.core.operator.query;
+
+import com.google.common.base.Preconditions;
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.List;
+import org.apache.pinot.common.request.context.OrderByExpressionContext;
+import org.apache.pinot.core.operator.transform.TransformResultMetadata;
+import org.apache.pinot.spi.data.FieldSpec;
+import org.apache.pinot.spi.exception.BadQueryRequestException;
+import org.apache.pinot.spi.utils.ByteArray;
+
+
+/**
+ * A utility class used to create comparators that should be used by operators that implements order by semantics.
+ */
+public class OrderByComparatorFactory {
+
+  private OrderByComparatorFactory() {
+  }
+
+  public static Comparator<Object[]> getComparator(List<OrderByExpressionContext> orderByExpressions,
+      TransformResultMetadata[] orderByExpressionMetadata, boolean asc, boolean nullHandlingEnabled) {

Review Comment:
   `asc` here is very confusing. Suggest renaming it to `reversed` and flip the logic, or just remove it and use `Comparator.reverse()` (not sure if it can add overhead)



##########
pinot-core/src/main/java/org/apache/pinot/core/operator/query/OrderByComparatorFactory.java:
##########
@@ -0,0 +1,170 @@
+/**
+ * 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.pinot.core.operator.query;

Review Comment:
   Move this class to the `org.apache.pinot.core.query.utils`



-- 
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: commits-unsubscribe@pinot.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org