You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@arrow.apache.org by GitBox <gi...@apache.org> on 2020/11/09 03:43:52 UTC

[GitHub] [arrow] kou opened a new pull request #8612: ARROW-8199: [C++] Add support for multi-column sort indices on Table

kou opened a new pull request #8612:
URL: https://github.com/apache/arrow/pull/8612


   Summary:
   
     * Deprecate SortToIndices()
   
     * Add SortIndices() because we use "sort_indices" as kernel name in
       #7240
   
     * Add support for sort indices in descending order on Array
   
     * Rename existing "sort_indices" kernel to "array_sort_indices" and
       introduce "sort_indices" meta function to support RecordBatch and
       Table
   
   Benchmark:
   
   Summary:
   
     * No performance regression in existing sort on array
   
     * Same performance as sort on array when the number of sort keys is 1
   
     * 1.5x-100x slower than sort on array when the number of sort keys is 2
   
   Before:
   
       ----------------------------------------------------------------------------------
       Benchmark                                                     Time             CPU
       ----------------------------------------------------------------------------------
       SortToIndicesInt64Count/32768/10000/min_time:1.000        15685 ns        15682 ns
       SortToIndicesInt64Count/32768/100/min_time:1.000          15961 ns        15957 ns
       SortToIndicesInt64Count/32768/10/min_time:1.000           16473 ns        16469 ns
       SortToIndicesInt64Count/32768/2/min_time:1.000            27993 ns        27987 ns
       SortToIndicesInt64Count/32768/1/min_time:1.000             5609 ns         5608 ns
       SortToIndicesInt64Count/32768/0/min_time:1.000            13143 ns        13141 ns
       SortToIndicesInt64Count/1048576/1/min_time:1.000         134695 ns       134670 ns
       SortToIndicesInt64Count/8388608/1/min_time:1.000        1243992 ns      1243260 ns
       SortToIndicesInt64Compare/32768/10000/min_time:1.000     193632 ns       193595 ns
       SortToIndicesInt64Compare/32768/100/min_time:1.000       194876 ns       194837 ns
       SortToIndicesInt64Compare/32768/10/min_time:1.000        182362 ns       182324 ns
       SortToIndicesInt64Compare/32768/2/min_time:1.000         111607 ns       111584 ns
       SortToIndicesInt64Compare/32768/1/min_time:1.000           5642 ns         5641 ns
       SortToIndicesInt64Compare/32768/0/min_time:1.000         190302 ns       190268 ns
       SortToIndicesInt64Compare/1048576/1/min_time:1.000       134743 ns       134718 ns
       SortToIndicesInt64Compare/8388608/1/min_time:1.000      1261404 ns      1249362 ns
   
   After:
   
       -------------------------------------------------------------------------------------
       Benchmark                                                        Time             CPU
       -------------------------------------------------------------------------------------
       ArraySortIndicesInt64Count/32768/10000/min_time:1.000        14769 ns        14766 ns
       ArraySortIndicesInt64Count/32768/100/min_time:1.000          15207 ns        15204 ns
       ArraySortIndicesInt64Count/32768/10/min_time:1.000           15892 ns        15889 ns
       ArraySortIndicesInt64Count/32768/2/min_time:1.000            30107 ns        30100 ns
       ArraySortIndicesInt64Count/32768/1/min_time:1.000             5509 ns         5508 ns
       ArraySortIndicesInt64Count/32768/0/min_time:1.000            12699 ns        12696 ns
       ArraySortIndicesInt64Count/1048576/1/min_time:1.000         132585 ns       132557 ns
       ArraySortIndicesInt64Count/8388608/1/min_time:1.000        1236596 ns      1235842 ns
       ArraySortIndicesInt64Compare/32768/10000/min_time:1.000     193259 ns       193217 ns
       ArraySortIndicesInt64Compare/32768/100/min_time:1.000       190010 ns       189973 ns
       ArraySortIndicesInt64Compare/32768/10/min_time:1.000        179923 ns       179879 ns
       ArraySortIndicesInt64Compare/32768/2/min_time:1.000         111100 ns       111074 ns
       ArraySortIndicesInt64Compare/32768/1/min_time:1.000           5660 ns         5659 ns
       ArraySortIndicesInt64Compare/32768/0/min_time:1.000         186521 ns       186476 ns
       ArraySortIndicesInt64Compare/1048576/1/min_time:1.000       132863 ns       132832 ns
       ArraySortIndicesInt64Compare/8388608/1/min_time:1.000      1266383 ns      1265765 ns
       TableSortIndicesInt64Count/32768/10000/min_time:1.000        21812 ns        21807 ns
       TableSortIndicesInt64Count/32768/100/min_time:1.000          22494 ns        22490 ns
       TableSortIndicesInt64Count/32768/10/min_time:1.000           17300 ns        17296 ns
       TableSortIndicesInt64Count/32768/2/min_time:1.000            29927 ns        29921 ns
       TableSortIndicesInt64Count/32768/1/min_time:1.000             5877 ns         5875 ns
       TableSortIndicesInt64Count/32768/0/min_time:1.000            20394 ns        20390 ns
       TableSortIndicesInt64Count/1048576/1/min_time:1.000         132904 ns       132871 ns
       TableSortIndicesInt64Count/8388608/1/min_time:1.000        1342693 ns      1341943 ns
       TableSortIndicesInt64Compare/32768/10000/min_time:1.000     203163 ns       203106 ns
       TableSortIndicesInt64Compare/32768/100/min_time:1.000       199531 ns       199477 ns
       TableSortIndicesInt64Compare/32768/10/min_time:1.000        185968 ns       185916 ns
       TableSortIndicesInt64Compare/32768/2/min_time:1.000         113571 ns       113540 ns
       TableSortIndicesInt64Compare/32768/1/min_time:1.000           6251 ns         6249 ns
       TableSortIndicesInt64Compare/32768/0/min_time:1.000         183650 ns       183609 ns
       TableSortIndicesInt64Compare/1048576/1/min_time:1.000       131701 ns       131674 ns
       TableSortIndicesInt64Compare/8388608/1/min_time:1.000      1264413 ns      1263622 ns
       TableSortIndicesInt64Int64/32768/10000/min_time:1.000       313368 ns       313310 ns
       TableSortIndicesInt64Int64/32768/100/min_time:1.000         313425 ns       313361 ns
       TableSortIndicesInt64Int64/32768/10/min_time:1.000          337051 ns       336987 ns
       TableSortIndicesInt64Int64/32768/2/min_time:1.000           402063 ns       401973 ns
       TableSortIndicesInt64Int64/32768/1/min_time:1.000           254660 ns       254612 ns
       TableSortIndicesInt64Int64/32768/0/min_time:1.000           305887 ns       305815 ns
       TableSortIndicesInt64Int64/1048576/1/min_time:1.000       11157920 ns     11155020 ns
       TableSortIndicesInt64Int64/8388608/1/min_time:1.000      106529839 ns    106501576 ns
   
   Follow-up tasks:
   
     * Improve performance when the number of sort keys is 2 or greater
   
       * Idea1: Use counting sort for small range data like on array
   
       * Idea2: Use threading and merge sort
   
     * Add support multi-column partition Nth indices on Table


----------------------------------------------------------------
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.

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



[GitHub] [arrow] kou commented on a change in pull request #8612: ARROW-8199: [C++] Add support for multi-column sort indices on Table

Posted by GitBox <gi...@apache.org>.
kou commented on a change in pull request #8612:
URL: https://github.com/apache/arrow/pull/8612#discussion_r519569932



##########
File path: cpp/src/arrow/compute/kernels/vector_sort.cc
##########
@@ -125,35 +128,43 @@ class CompareSorter {
           std::stable_partition(indices_begin, indices_end,
                                 [&values](uint64_t ind) { return !values.IsNull(ind); });
     }
-    std::stable_sort(indices_begin, nulls_begin,
-                     [&values](uint64_t left, uint64_t right) {
-                       return values.GetView(left) < values.GetView(right);
-                     });
+    if (options.order == SortOrder::ASCENDING) {
+      std::stable_sort(indices_begin, nulls_begin,
+                       [&values](uint64_t left, uint64_t right) {
+                         return values.GetView(left) < values.GetView(right);
+                       });
+    } else {
+      std::stable_sort(indices_begin, nulls_begin,
+                       [&values](uint64_t left, uint64_t right) {
+                         return values.GetView(left) > values.GetView(right);

Review comment:
       Good catch!




----------------------------------------------------------------
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.

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



[GitHub] [arrow] kou commented on a change in pull request #8612: ARROW-8199: [C++] Add support for multi-column sort indices on Table

Posted by GitBox <gi...@apache.org>.
kou commented on a change in pull request #8612:
URL: https://github.com/apache/arrow/pull/8612#discussion_r526612843



##########
File path: cpp/src/arrow/compute/kernels/vector_sort.cc
##########
@@ -346,14 +374,396 @@ void AddSortingKernels(VectorKernel base, VectorFunction* func) {
   }
 }
 
+class TableSorter : public TypeVisitor {
+ private:
+  struct ResolvedSortKey {
+    ResolvedSortKey(const ChunkedArray& chunked_array, const SortOrder order)
+        : order(order) {
+      type = chunked_array.type().get();
+      null_count = chunked_array.null_count();
+      num_chunks = chunked_array.num_chunks();
+      for (const auto& chunk : chunked_array.chunks()) {
+        chunks.push_back(chunk.get());
+      }
+    }
+
+    template <typename ArrayType>
+    ArrayType* ResolveChunk(int64_t index, int64_t& chunk_index) const {
+      if (num_chunks == 1) {
+        chunk_index = index;
+        return static_cast<ArrayType*>(chunks[0]);
+      } else {
+        int64_t offset = 0;
+        for (size_t i = 0; i < num_chunks; ++i) {
+          if (index < offset + chunks[i]->length()) {
+            chunk_index = index - offset;
+            return static_cast<ArrayType*>(chunks[i]);
+          }
+          offset += chunks[i]->length();
+        }
+        return nullptr;
+      }
+    }
+
+    SortOrder order;
+    DataType* type;
+    int64_t null_count;
+    size_t num_chunks;

Review comment:
       Fixed. It should be `int` because `ChunkedArray::num_chunks()` returns `int`.




----------------------------------------------------------------
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.

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



[GitHub] [arrow] mrkn commented on a change in pull request #8612: ARROW-8199: [C++] Add support for multi-column sort indices on Table

Posted by GitBox <gi...@apache.org>.
mrkn commented on a change in pull request #8612:
URL: https://github.com/apache/arrow/pull/8612#discussion_r519569356



##########
File path: cpp/src/arrow/compute/kernels/vector_sort.cc
##########
@@ -125,35 +128,43 @@ class CompareSorter {
           std::stable_partition(indices_begin, indices_end,
                                 [&values](uint64_t ind) { return !values.IsNull(ind); });
     }
-    std::stable_sort(indices_begin, nulls_begin,
-                     [&values](uint64_t left, uint64_t right) {
-                       return values.GetView(left) < values.GetView(right);
-                     });
+    if (options.order == SortOrder::ASCENDING) {
+      std::stable_sort(indices_begin, nulls_begin,
+                       [&values](uint64_t left, uint64_t right) {
+                         return values.GetView(left) < values.GetView(right);
+                       });
+    } else {
+      std::stable_sort(indices_begin, nulls_begin,
+                       [&values](uint64_t left, uint64_t right) {
+                         return values.GetView(left) > values.GetView(right);

Review comment:
       This requires that all of `==`, `<`, and `>` are implemented in the value type.
   Instead, writing `right < left` here only requires `==` and `<`.
   IMHO, requiring only `==` and `<` is better to support extension types in the future.




----------------------------------------------------------------
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.

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



[GitHub] [arrow] kou commented on a change in pull request #8612: ARROW-8199: [C++] Add support for multi-column sort indices on Table

Posted by GitBox <gi...@apache.org>.
kou commented on a change in pull request #8612:
URL: https://github.com/apache/arrow/pull/8612#discussion_r526618765



##########
File path: cpp/src/arrow/compute/kernels/vector_sort.cc
##########
@@ -346,14 +374,396 @@ void AddSortingKernels(VectorKernel base, VectorFunction* func) {
   }
 }
 
+class TableSorter : public TypeVisitor {
+ private:
+  struct ResolvedSortKey {
+    ResolvedSortKey(const ChunkedArray& chunked_array, const SortOrder order)
+        : order(order) {
+      type = chunked_array.type().get();
+      null_count = chunked_array.null_count();
+      num_chunks = chunked_array.num_chunks();
+      for (const auto& chunk : chunked_array.chunks()) {
+        chunks.push_back(chunk.get());
+      }
+    }
+
+    template <typename ArrayType>
+    ArrayType* ResolveChunk(int64_t index, int64_t& chunk_index) const {
+      if (num_chunks == 1) {
+        chunk_index = index;
+        return static_cast<ArrayType*>(chunks[0]);
+      } else {
+        int64_t offset = 0;
+        for (size_t i = 0; i < num_chunks; ++i) {
+          if (index < offset + chunks[i]->length()) {
+            chunk_index = index - offset;
+            return static_cast<ArrayType*>(chunks[i]);
+          }
+          offset += chunks[i]->length();
+        }
+        return nullptr;
+      }
+    }
+
+    SortOrder order;
+    DataType* type;
+    int64_t null_count;
+    size_t num_chunks;
+    std::vector<Array*> chunks;
+  };
+
+  class Comparer : public TypeVisitor {
+   public:
+    Comparer(const Table& table, const std::vector<SortKey>& sort_keys)
+        : TypeVisitor(), status_(Status::OK()) {
+      for (const auto& sort_key : sort_keys) {
+        const auto& chunked_array = table.GetColumnByName(sort_key.name);
+        if (!chunked_array) {
+          status_ = Status::Invalid("Nonexistent sort key column: ", sort_key.name);
+          return;
+        }
+        sort_keys_.emplace_back(*chunked_array, sort_key.order);
+      }
+    }
+
+    Status status() { return status_; }
+
+    const std::vector<ResolvedSortKey>& sort_keys() { return sort_keys_; }
+
+    bool Compare(uint64_t left, uint64_t right, size_t start_sort_key_index) {
+      current_left_ = left;
+      current_right_ = right;
+      current_compared_ = 0;
+      auto num_sort_keys = sort_keys_.size();
+      for (size_t i = start_sort_key_index; i < num_sort_keys; ++i) {
+        current_sort_key_index_ = i;
+        status_ = sort_keys_[i].type->Accept(this);
+        if (current_compared_ != 0) {
+          break;
+        }
+      }
+      return current_compared_ < 0;
+    }
+
+#define VISIT(TYPE)                                \
+  Status Visit(const TYPE##Type& type) override {  \
+    current_compared_ = CompareType<TYPE##Type>(); \
+    return Status::OK();                           \
+  }
+
+    VISIT(Int8)
+    VISIT(Int16)
+    VISIT(Int32)
+    VISIT(Int64)
+    VISIT(UInt8)
+    VISIT(UInt16)
+    VISIT(UInt32)
+    VISIT(UInt64)
+    VISIT(Float)
+    VISIT(Double)
+    VISIT(String)
+    VISIT(Binary)
+    VISIT(LargeString)
+    VISIT(LargeBinary)
+
+#undef VISIT
+
+   private:
+    template <typename Type>
+    int32_t CompareType() {
+      using ArrayType = typename TypeTraits<Type>::ArrayType;
+      const auto& sort_key = sort_keys_[current_sort_key_index_];
+      auto order = sort_key.order;
+      int64_t index_left = 0;
+      auto array_left = sort_key.ResolveChunk<ArrayType>(current_left_, index_left);
+      int64_t index_right = 0;
+      auto array_right = sort_key.ResolveChunk<ArrayType>(current_right_, index_right);
+      if (sort_key.null_count > 0) {
+        auto is_null_left = array_left->IsNull(index_left);
+        auto is_null_right = array_right->IsNull(index_right);
+        if (is_null_left && is_null_right) {
+          return 0;
+        } else if (is_null_left) {
+          return 1;
+        } else if (is_null_right) {
+          return -1;
+        }
+      }
+      auto left = array_left->GetView(index_left);
+      auto right = array_right->GetView(index_right);
+      int32_t compared;
+      if (left == right) {
+        compared = 0;
+      } else if (left > right) {
+        compared = 1;
+      } else {
+        compared = -1;
+      }
+      if (order == SortOrder::DESCENDING) {
+        compared = -compared;
+      }
+      return compared;
+    }
+
+    Status status_;
+    std::vector<ResolvedSortKey> sort_keys_;
+    int64_t current_left_;
+    int64_t current_right_;
+    size_t current_sort_key_index_;
+    int32_t current_compared_;
+  };
+
+ public:
+  TableSorter(uint64_t* indices_begin, uint64_t* indices_end, const Table& table,
+              const SortOptions& options)
+      : indices_begin_(indices_begin),
+        indices_end_(indices_end),
+        comparer_(table, options.sort_keys) {}
+
+  Status Sort() {
+    ARROW_RETURN_NOT_OK(comparer_.status());
+    return comparer_.sort_keys()[0].type->Accept(this);
+  }
+
+#define VISIT(TYPE) \
+  Status Visit(const TYPE##Type& type) override { return SortInternal<TYPE##Type>(); }
+
+  VISIT(Int8)
+  VISIT(Int16)
+  VISIT(Int32)
+  VISIT(Int64)
+  VISIT(UInt8)
+  VISIT(UInt16)
+  VISIT(UInt32)
+  VISIT(UInt64)
+  VISIT(Float)
+  VISIT(Double)
+  VISIT(String)
+  VISIT(Binary)
+  VISIT(LargeString)
+  VISIT(LargeBinary)
+
+#undef VISIT
+
+ private:
+  template <typename Type>
+  Status SortInternal() {
+    using ArrayType = typename TypeTraits<Type>::ArrayType;
+    std::iota(indices_begin_, indices_end_, 0);
+
+    auto& comparer = comparer_;
+    const auto& first_sort_key = comparer.sort_keys()[0];
+    auto nulls_begin = indices_end_;
+    nulls_begin = PartitionNullsInternal<Type>(first_sort_key);
+    std::stable_sort(
+        indices_begin_, nulls_begin,
+        [&first_sort_key, &comparer](uint64_t left, uint64_t right) {
+          int64_t index_left = 0;
+          auto array_left = first_sort_key.ResolveChunk<ArrayType>(left, index_left);
+          int64_t index_right = 0;
+          auto array_right = first_sort_key.ResolveChunk<ArrayType>(right, index_right);
+          auto value_left = array_left->GetView(index_left);
+          auto value_right = array_right->GetView(index_right);
+          if (value_left == value_right) {
+            return comparer.Compare(left, right, 1);
+          } else {
+            auto compared = value_left < value_right;
+            if (first_sort_key.order == SortOrder::ASCENDING) {
+              return compared;
+            } else {
+              return !compared;
+            }
+          }
+        });
+    return Status::OK();
+  }
+
+  template <typename Type>
+  enable_if_t<!is_floating_type<Type>::value, uint64_t*> PartitionNullsInternal(
+      const ResolvedSortKey& first_sort_key) {
+    using ArrayType = typename TypeTraits<Type>::ArrayType;
+    if (first_sort_key.null_count == 0) {
+      return indices_end_;
+    }
+    StablePartitioner partitioner;
+    auto nulls_begin =
+        partitioner(indices_begin_, indices_end_, [&first_sort_key](uint64_t index) {
+          int64_t index_chunk = 0;
+          auto chunk = first_sort_key.ResolveChunk<ArrayType>(index, index_chunk);
+          return !chunk->IsNull(index_chunk);
+        });
+    auto& comparer = comparer_;
+    std::stable_sort(nulls_begin, indices_end_,
+                     [&comparer](uint64_t left, uint64_t right) {
+                       return comparer.Compare(left, right, 1);
+                     });
+    return nulls_begin;
+  }
+
+  template <typename Type>
+  enable_if_t<is_floating_type<Type>::value, uint64_t*> PartitionNullsInternal(
+      const ResolvedSortKey& first_sort_key) {
+    using ArrayType = typename TypeTraits<Type>::ArrayType;
+    StablePartitioner partitioner;
+    if (first_sort_key.null_count == 0) {
+      return partitioner(indices_begin_, indices_end_, [&first_sort_key](uint64_t index) {
+        int64_t index_chunk = 0;
+        auto chunk = first_sort_key.ResolveChunk<ArrayType>(index, index_chunk);
+        return !std::isnan(chunk->GetView(index_chunk));
+      });
+    }
+    auto nans_and_nulls_begin =
+        partitioner(indices_begin_, indices_end_, [&first_sort_key](uint64_t index) {
+          int64_t index_chunk = 0;
+          auto chunk = first_sort_key.ResolveChunk<ArrayType>(index, index_chunk);
+          return !chunk->IsNull(index_chunk) && !std::isnan(chunk->GetView(index_chunk));
+        });
+    auto nulls_begin = nans_and_nulls_begin;
+    if (first_sort_key.null_count < static_cast<int64_t>(indices_end_ - nulls_begin)) {
+      // move Nulls after NaN
+      nulls_begin = partitioner(
+          nans_and_nulls_begin, indices_end_, [&first_sort_key](uint64_t index) {
+            int64_t index_chunk = 0;
+            auto chunk = first_sort_key.ResolveChunk<ArrayType>(index, index_chunk);
+            return !chunk->IsNull(index_chunk);
+          });
+    }
+    auto& comparer = comparer_;
+    if (nans_and_nulls_begin != nulls_begin) {
+      std::stable_sort(nans_and_nulls_begin, nulls_begin,
+                       [&comparer](uint64_t left, uint64_t right) {
+                         return comparer.Compare(left, right, 1);
+                       });
+    }
+    std::stable_sort(nulls_begin, indices_end_,
+                     [&comparer](uint64_t left, uint64_t right) {
+                       return comparer.Compare(left, right, 1);
+                     });
+    return nans_and_nulls_begin;
+  }
+
+  uint64_t* indices_begin_;
+  uint64_t* indices_end_;
+  Comparer comparer_;
+};
+
 const FunctionDoc sort_indices_doc(
+    "Return the indices that would sort an array, record batch or table",
+    ("This function computes an array of indices that define a stable sort\n"
+     "of the input array, record batch or table.  Null values are considered\n"
+     "greater than any other value and are therefore sorted at the end of the\n"
+     "input. For floating-point types, NaNs are considered greater than any\n"
+     "other non-null value, but smaller than null values."),
+    {"input"}, "SortOptions");
+
+class SortIndicesMetaFunction : public MetaFunction {
+ public:
+  SortIndicesMetaFunction()
+      : MetaFunction("sort_indices", Arity::Unary(), &sort_indices_doc) {}
+
+  Result<Datum> ExecuteImpl(const std::vector<Datum>& args,
+                            const FunctionOptions* options,
+                            ExecContext* ctx) const override {
+    const SortOptions& sort_options = static_cast<const SortOptions&>(*options);
+    switch (args[0].kind()) {
+      case Datum::ARRAY:
+        return SortIndices(*args[0].make_array(), sort_options, ctx);
+        break;
+      case Datum::CHUNKED_ARRAY:
+        return SortIndices(*args[0].chunked_array(), sort_options, ctx);
+        break;
+      case Datum::RECORD_BATCH: {
+        ARROW_ASSIGN_OR_RAISE(auto table,
+                              Table::FromRecordBatches({args[0].record_batch()}));
+        return SortIndices(*table, sort_options, ctx);
+      } break;
+      case Datum::TABLE:
+        return SortIndices(*args[0].table(), sort_options, ctx);
+        break;
+      default:
+        break;
+    }
+    return Status::NotImplemented(
+        "Unsupported types for sort_indices operation: "
+        "values=",
+        args[0].ToString());
+  }
+
+ private:
+  Result<std::shared_ptr<Array>> SortIndices(const Array& values,
+                                             const SortOptions& options,
+                                             ExecContext* ctx) const {
+    SortOrder order = SortOrder::ASCENDING;
+    if (!options.sort_keys.empty()) {
+      order = options.sort_keys[0].order;
+    }
+    ArraySortOptions array_options(order);
+    ARROW_ASSIGN_OR_RAISE(
+        Datum result, CallFunction("array_sort_indices", {values}, &array_options, ctx));
+    return result.make_array();
+  }
+
+  Result<std::shared_ptr<Array>> SortIndices(const ChunkedArray& values,
+                                             const SortOptions& options,
+                                             ExecContext* ctx) const {
+    SortOrder order = SortOrder::ASCENDING;
+    if (!options.sort_keys.empty()) {
+      order = options.sort_keys[0].order;
+    }
+    ArraySortOptions array_options(order);
+
+    std::shared_ptr<Array> array_values;
+    if (values.num_chunks() == 1) {
+      array_values = values.chunk(0);
+    } else {
+      ARROW_ASSIGN_OR_RAISE(array_values,
+                            Concatenate(values.chunks(), ctx->memory_pool()));
+    }
+    ARROW_ASSIGN_OR_RAISE(Datum result, CallFunction("array_sort_indices", {array_values},
+                                                     &array_options, ctx));
+    return result.make_array();
+  }
+
+  Result<Datum> SortIndices(const Table& table, const SortOptions& options,
+                            ExecContext* ctx) const {
+    auto n_sort_keys = options.sort_keys.size();
+    if (n_sort_keys == 0) {
+      return Status::Invalid("Must specify one or more sort keys");
+    }
+    if (n_sort_keys == 1) {
+      auto chunked_array = table.GetColumnByName(options.sort_keys[0].name);
+      if (!chunked_array) {
+        return Status::Invalid("Nonexistent sort key column: ",
+                               options.sort_keys[0].name);
+      }
+      return SortIndices(*chunked_array, options, ctx);
+    }
+
+    auto out_type = uint64();
+    auto length = table.num_rows();
+    auto buffer_size = BitUtil::BytesForBits(
+        length * std::static_pointer_cast<UInt64Type>(out_type)->bit_width());

Review comment:
       If we want to use `sizeof()`, we need to use `sizeof() * 8`. Because the unit is bit not byte.
   Should we use `sizeof() * 8` here?




----------------------------------------------------------------
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.

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



[GitHub] [arrow] kou commented on a change in pull request #8612: ARROW-8199: [C++] Add support for multi-column sort indices on Table

Posted by GitBox <gi...@apache.org>.
kou commented on a change in pull request #8612:
URL: https://github.com/apache/arrow/pull/8612#discussion_r519538131



##########
File path: cpp/src/arrow/compute/kernels/vector_sort.cc
##########
@@ -112,11 +114,12 @@ inline void VisitRawValuesInline(const ArrayType& values,
 }
 
 template <typename ArrowType>
-class CompareSorter {
+class ArrayCompareSorter {
   using ArrayType = typename TypeTraits<ArrowType>::ArrayType;
 
  public:
-  void Sort(uint64_t* indices_begin, uint64_t* indices_end, const ArrayType& values) {
+  void Sort(uint64_t* indices_begin, uint64_t* indices_end, const ArrayType& values,
+            const ArraySortOptions& options) {

Review comment:
       This change is for order support on array.

##########
File path: cpp/src/arrow/compute/api_vector.cc
##########
@@ -135,5 +149,9 @@ Result<std::shared_ptr<Table>> Take(const Table& table, const ChunkedArray& indi
   return result.table();
 }
 
+Result<std::shared_ptr<Array>> SortToIndices(const Array& values, ExecContext* ctx) {
+  return SortIndices(values, ctx);
+}
+

Review comment:
       This hunk is for `SortToIndices()` -> `SortIndices()` rename.

##########
File path: cpp/src/arrow/compute/kernels/vector_sort.cc
##########
@@ -125,35 +128,43 @@ class CompareSorter {
           std::stable_partition(indices_begin, indices_end,
                                 [&values](uint64_t ind) { return !values.IsNull(ind); });
     }
-    std::stable_sort(indices_begin, nulls_begin,
-                     [&values](uint64_t left, uint64_t right) {
-                       return values.GetView(left) < values.GetView(right);
-                     });
+    if (options.order == SortOrder::ASCENDING) {
+      std::stable_sort(indices_begin, nulls_begin,
+                       [&values](uint64_t left, uint64_t right) {
+                         return values.GetView(left) < values.GetView(right);
+                       });
+    } else {
+      std::stable_sort(indices_begin, nulls_begin,
+                       [&values](uint64_t left, uint64_t right) {
+                         return values.GetView(left) > values.GetView(right);
+                       });
+    }
   }
 };
 
 template <typename ArrowType>
-class CountSorter {
+class ArrayCountSorter {
   using ArrayType = typename TypeTraits<ArrowType>::ArrayType;
   using c_type = typename ArrowType::c_type;
 
  public:
-  CountSorter() = default;
+  ArrayCountSorter() = default;
 
-  explicit CountSorter(c_type min, c_type max) { SetMinMax(min, max); }
+  explicit ArrayCountSorter(c_type min, c_type max) { SetMinMax(min, max); }
 
   // Assume: max >= min && (max - min) < 4Gi
   void SetMinMax(c_type min, c_type max) {
     min_ = min;
     value_range_ = static_cast<uint32_t>(max - min) + 1;
   }
 
-  void Sort(uint64_t* indices_begin, uint64_t* indices_end, const ArrayType& values) {
+  void Sort(uint64_t* indices_begin, uint64_t* indices_end, const ArrayType& values,
+            const ArraySortOptions& options) {
     // 32bit counter performs much better than 64bit one
     if (values.length() < (1LL << 32)) {
-      SortInternal<uint32_t>(indices_begin, indices_end, values);
+      SortInternal<uint32_t>(indices_begin, indices_end, values, options);
     } else {
-      SortInternal<uint64_t>(indices_begin, indices_end, values);
+      SortInternal<uint64_t>(indices_begin, indices_end, values, options);

Review comment:
       This change is for order support on array.
   

##########
File path: cpp/src/arrow/compute/kernels/vector_sort.cc
##########
@@ -125,35 +128,43 @@ class CompareSorter {
           std::stable_partition(indices_begin, indices_end,
                                 [&values](uint64_t ind) { return !values.IsNull(ind); });
     }
-    std::stable_sort(indices_begin, nulls_begin,
-                     [&values](uint64_t left, uint64_t right) {
-                       return values.GetView(left) < values.GetView(right);
-                     });
+    if (options.order == SortOrder::ASCENDING) {
+      std::stable_sort(indices_begin, nulls_begin,
+                       [&values](uint64_t left, uint64_t right) {
+                         return values.GetView(left) < values.GetView(right);
+                       });
+    } else {
+      std::stable_sort(indices_begin, nulls_begin,
+                       [&values](uint64_t left, uint64_t right) {
+                         return values.GetView(left) > values.GetView(right);
+                       });
+    }

Review comment:
       This change is for order support on array.

##########
File path: cpp/src/arrow/compute/kernels/vector_sort.cc
##########
@@ -163,36 +174,49 @@ class CountSorter {
 
   template <typename CounterType>
   void SortInternal(uint64_t* indices_begin, uint64_t* indices_end,
-                    const ArrayType& values) {
+                    const ArrayType& values, const ArraySortOptions& options) {
     const uint32_t value_range = value_range_;
 
     // first slot reserved for prefix sum
     std::vector<CounterType> counts(1 + value_range);
 
-    VisitRawValuesInline(
-        values, [&](c_type v) { ++counts[v - min_ + 1]; }, []() {});
-
-    for (uint32_t i = 1; i <= value_range; ++i) {
-      counts[i] += counts[i - 1];
+    if (options.order == SortOrder::ASCENDING) {
+      VisitRawValuesInline(
+          values, [&](c_type v) { ++counts[v - min_ + 1]; }, []() {});
+      for (uint32_t i = 1; i <= value_range; ++i) {
+        counts[i] += counts[i - 1];
+      }
+      uint32_t null_position = counts[value_range];
+      int64_t index = 0;
+      VisitRawValuesInline(
+          values, [&](c_type v) { indices_begin[counts[v - min_]++] = index++; },
+          [&]() { indices_begin[null_position++] = index++; });
+    } else {
+      VisitRawValuesInline(
+          values, [&](c_type v) { ++counts[v - min_]; }, []() {});
+      for (uint32_t i = value_range; i >= 1; --i) {
+        counts[i - 1] += counts[i];
+      }
+      uint32_t null_position = counts[0];
+      int64_t index = 0;
+      VisitRawValuesInline(
+          values, [&](c_type v) { indices_begin[counts[v - min_ + 1]++] = index++; },
+          [&]() { indices_begin[null_position++] = index++; });
     }
-
-    int64_t index = 0;
-    VisitRawValuesInline(
-        values, [&](c_type v) { indices_begin[counts[v - min_]++] = index++; },
-        [&]() { indices_begin[counts[value_range]++] = index++; });
   }
 };

Review comment:
       This change is for order support on array.

##########
File path: cpp/src/arrow/compute/kernels/vector_sort_test.cc
##########
@@ -209,138 +214,155 @@ TYPED_TEST(TestNthToIndicesRandom, RandomValues) {
 using arrow::internal::checked_pointer_cast;
 
 template <typename ArrowType>
-class TestSortToIndicesKernel : public TestBase {
+class TestArraySortIndicesKernel : public TestBase {

Review comment:
       This hunk is for renaming `SortToIndices()` -> `SortIndices()`. No logic change.

##########
File path: cpp/src/arrow/compute/kernels/vector_sort.cc
##########
@@ -236,36 +260,40 @@ class CountOrCompareSorter {
 };
 
 template <typename Type, typename Enable = void>
-struct Sorter;
+struct ArraySorter;
 
 template <>
-struct Sorter<UInt8Type> {
-  CountSorter<UInt8Type> impl;
-  Sorter() : impl(0, 255) {}
+struct ArraySorter<UInt8Type> {
+  ArrayCountSorter<UInt8Type> impl;
+  ArraySorter() : impl(0, 255) {}
 };
 
 template <>
-struct Sorter<Int8Type> {
-  CountSorter<Int8Type> impl;
-  Sorter() : impl(-128, 127) {}
+struct ArraySorter<Int8Type> {
+  ArrayCountSorter<Int8Type> impl;
+  ArraySorter() : impl(-128, 127) {}
 };
 
 template <typename Type>
-struct Sorter<Type, enable_if_t<is_integer_type<Type>::value &&
-                                (sizeof(typename Type::c_type) > 1)>> {
-  CountOrCompareSorter<Type> impl;
+struct ArraySorter<Type, enable_if_t<is_integer_type<Type>::value &&
+                                     (sizeof(typename Type::c_type) > 1)>> {
+  ArrayCountOrCompareSorter<Type> impl;
 };
 
 template <typename Type>
-struct Sorter<Type, enable_if_t<is_floating_type<Type>::value ||
-                                is_base_binary_type<Type>::value>> {
-  CompareSorter<Type> impl;
+struct ArraySorter<Type, enable_if_t<is_floating_type<Type>::value ||
+                                     is_base_binary_type<Type>::value>> {
+  ArrayCompareSorter<Type> impl;
 };

Review comment:
       `Array` prefix is added to distinguish array and table related codes.

##########
File path: cpp/src/arrow/compute/kernels/vector_sort.cc
##########
@@ -112,11 +114,12 @@ inline void VisitRawValuesInline(const ArrayType& values,
 }
 
 template <typename ArrowType>
-class CompareSorter {
+class ArrayCompareSorter {

Review comment:
       `Array` prefix is added to distinguish array and table related codes.

##########
File path: cpp/src/arrow/compute/kernels/vector_sort.cc
##########
@@ -125,35 +128,43 @@ class CompareSorter {
           std::stable_partition(indices_begin, indices_end,
                                 [&values](uint64_t ind) { return !values.IsNull(ind); });
     }
-    std::stable_sort(indices_begin, nulls_begin,
-                     [&values](uint64_t left, uint64_t right) {
-                       return values.GetView(left) < values.GetView(right);
-                     });
+    if (options.order == SortOrder::ASCENDING) {
+      std::stable_sort(indices_begin, nulls_begin,
+                       [&values](uint64_t left, uint64_t right) {
+                         return values.GetView(left) < values.GetView(right);
+                       });
+    } else {
+      std::stable_sort(indices_begin, nulls_begin,
+                       [&values](uint64_t left, uint64_t right) {
+                         return values.GetView(left) > values.GetView(right);
+                       });
+    }
   }
 };
 
 template <typename ArrowType>
-class CountSorter {
+class ArrayCountSorter {
   using ArrayType = typename TypeTraits<ArrowType>::ArrayType;
   using c_type = typename ArrowType::c_type;
 
  public:
-  CountSorter() = default;
+  ArrayCountSorter() = default;
 
-  explicit CountSorter(c_type min, c_type max) { SetMinMax(min, max); }
+  explicit ArrayCountSorter(c_type min, c_type max) { SetMinMax(min, max); }

Review comment:
       `Array` prefix is added to distinguish array and table related codes.

##########
File path: cpp/src/arrow/compute/kernels/vector_sort.cc
##########
@@ -299,12 +327,344 @@ void AddSortingKernels(VectorKernel base, VectorFunction* func) {
   }
 }
 
+class TableSorter : public TypeVisitor {

Review comment:
       For multi-column sorting on table.




----------------------------------------------------------------
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.

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



[GitHub] [arrow] kou commented on pull request #8612: ARROW-8199: [C++] Add support for multi-column sort indices on Table

Posted by GitBox <gi...@apache.org>.
kou commented on pull request #8612:
URL: https://github.com/apache/arrow/pull/8612#issuecomment-725086749


   @cyb70289 @pitrou Do you want to review 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.

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



[GitHub] [arrow] kou commented on a change in pull request #8612: ARROW-8199: [C++] Add support for multi-column sort indices on Table

Posted by GitBox <gi...@apache.org>.
kou commented on a change in pull request #8612:
URL: https://github.com/apache/arrow/pull/8612#discussion_r526611674



##########
File path: cpp/src/arrow/compute/api_vector.h
##########
@@ -165,8 +194,50 @@ Result<std::shared_ptr<Array>> NthToIndices(const Array& values, int64_t n,
 /// \param[in] ctx the function execution context, optional
 /// \return offsets indices that would sort an array
 ARROW_EXPORT
-Result<std::shared_ptr<Array>> SortToIndices(const Array& values,
-                                             ExecContext* ctx = NULLPTR);
+Result<std::shared_ptr<Array>> SortIndices(const Array& values,
+                                           ExecContext* ctx = NULLPTR);
+
+/// \brief Returns the indices that would sort an array in the
+/// specified order.
+///
+/// Perform an indirect sort of array. The output array will contain
+/// indices that would sort an array, which would be the same length
+/// as input. Nulls will be stably partitioned to the end of the output.
+///
+/// For example given values = [null, 1, 3.3, null, 2, 5.3] and order
+/// = SortOrder::DESCENDING, the output will be [5, 2, 4, 1, 0,
+/// 3].
+///
+/// \param[in] values array to sort
+/// \param[in] order ascending or descending
+/// \param[in] ctx the function execution context, optional
+/// \return offsets indices that would sort an array
+ARROW_EXPORT
+Result<std::shared_ptr<Array>> SortIndices(const Array& values, SortOrder order,

Review comment:
       I wanted to accept `SortIndices(array, ctx)` usage but it may not be used.
   I've removed the SortIndices(array, ctx)` and added `SortOrder::Ascending` as the default value.




----------------------------------------------------------------
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.

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



[GitHub] [arrow] kou commented on pull request #8612: ARROW-8199: [C++] Add support for multi-column sort indices on Table

Posted by GitBox <gi...@apache.org>.
kou commented on pull request #8612:
URL: https://github.com/apache/arrow/pull/8612#issuecomment-725098578


   Done.


----------------------------------------------------------------
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.

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



[GitHub] [arrow] kou commented on pull request #8612: ARROW-8199: [C++] Add support for multi-column sort indices on Table

Posted by GitBox <gi...@apache.org>.
kou commented on pull request #8612:
URL: https://github.com/apache/arrow/pull/8612#issuecomment-725225424


   Thanks for your comments!
   
   > Looks you are returning a flat index array, does it make sense to return array of tuple (chunk_index, offset_in_chunk)? Maybe easier for client code to use?
   
   Each column in table may have the different number of chunks. For example, `{"a": [[1, 2], [3], [4, 5, 6]], "b": [[1, 2, 3], [4, 5, 6]]}`. If we want to return `chunk_index` and `offset_in_chunk`, we need to return them for each column. It may decrease performance.
   
   > For multi column sorting, in one iteration, current code compares values column by column till first non-equal found. I don't know if a radix sort approach is better, e.g. sort by 2nd-order column first, then sort by 1st-order column. It may be possible to leverage existing array based sorting code(counting sort, etc).
   
   It's interesting! I've added the idea to follow-up tasks in the pull request description.


----------------------------------------------------------------
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.

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



[GitHub] [arrow] kou commented on a change in pull request #8612: ARROW-8199: [C++] Add support for multi-column sort indices on Table

Posted by GitBox <gi...@apache.org>.
kou commented on a change in pull request #8612:
URL: https://github.com/apache/arrow/pull/8612#discussion_r526612209



##########
File path: cpp/src/arrow/compute/api_vector.h
##########
@@ -58,6 +58,34 @@ struct ARROW_EXPORT TakeOptions : public FunctionOptions {
   static TakeOptions Defaults() { return BoundsCheck(); }
 };
 
+enum SortOrder {
+  ASCENDING,
+  DESCENDING,
+};
+
+/// \brief One sort key for PartitionNthIndices (TODO) and SortIndices
+struct ARROW_EXPORT SortKey {
+  explicit SortKey(std::string name, SortOrder order = ASCENDING)
+      : name(name), order(order) {}
+
+  /// The name of the sort key.
+  std::string name;
+  /// How to order by this sort key.
+  SortOrder order;
+};
+
+struct ARROW_EXPORT ArraySortOptions : public FunctionOptions {
+  explicit ArraySortOptions(SortOrder order = SortOrder::ASCENDING) : order(order) {}
+
+  SortOrder order;
+};
+
+struct ARROW_EXPORT SortOptions : public FunctionOptions {

Review comment:
       I want to keep this because this is used by all inputs (`Array`, `ChunkedArray`, `RecordBatch` and `Table`) with the `sort_indices()` compute kernel.
   So I think that no `Table` prefix is suitable.




----------------------------------------------------------------
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.

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



[GitHub] [arrow] kou commented on a change in pull request #8612: ARROW-8199: [C++] Add support for multi-column sort indices on Table

Posted by GitBox <gi...@apache.org>.
kou commented on a change in pull request #8612:
URL: https://github.com/apache/arrow/pull/8612#discussion_r526619466



##########
File path: cpp/src/arrow/compute/kernels/vector_sort_benchmark.cc
##########
@@ -56,17 +57,99 @@ static void SortToIndicesInt64Compare(benchmark::State& state) {
   auto max = std::numeric_limits<int64_t>::max();
   auto values = rand.Int64(array_size, min, max, args.null_proportion);
 
-  SortToIndicesBenchmark(state, values);
+  ArraySortIndicesBenchmark(state, values);
 }
 
-BENCHMARK(SortToIndicesInt64Count)
+static void TableSortIndicesBenchmark(benchmark::State& state,
+                                      const std::shared_ptr<Table>& table,
+                                      const SortOptions& options) {
+  for (auto _ : state) {
+    ABORT_NOT_OK(SortIndices(*table, options).status());
+  }
+  state.SetItemsProcessed(state.iterations() * table->num_rows());
+}
+
+static void TableSortIndicesInt64Count(benchmark::State& state) {
+  RegressionArgs args(state);
+
+  const int64_t array_size = args.size / sizeof(int64_t);
+  auto rand = random::RandomArrayGenerator(kSeed);
+  auto values = rand.Int64(array_size, -100, 100, args.null_proportion);
+  std::vector<std::shared_ptr<Field>> fields = {{field("int64", int64())}};
+  auto table = Table::Make(schema(fields), {values}, array_size);
+  SortOptions options({SortKey("int64", SortOrder::ASCENDING)});
+
+  TableSortIndicesBenchmark(state, table, options);
+}
+
+static void TableSortIndicesInt64Compare(benchmark::State& state) {
+  RegressionArgs args(state);
+
+  const int64_t array_size = args.size / sizeof(int64_t);
+  auto rand = random::RandomArrayGenerator(kSeed);
+
+  auto min = std::numeric_limits<int64_t>::min();
+  auto max = std::numeric_limits<int64_t>::max();
+  auto values = rand.Int64(array_size, min, max, args.null_proportion);
+  std::vector<std::shared_ptr<Field>> fields = {{field("int64", int64())}};
+  auto table = Table::Make(schema(fields), {values}, array_size);
+  SortOptions options({SortKey("int64", SortOrder::ASCENDING)});
+
+  TableSortIndicesBenchmark(state, table, options);
+}
+
+static void TableSortIndicesInt64Int64(benchmark::State& state) {
+  RegressionArgs args(state);
+
+  const int64_t array_size = args.size / sizeof(int64_t);
+  auto rand = random::RandomArrayGenerator(kSeed);
+
+  auto min = std::numeric_limits<int64_t>::min();
+  auto max = std::numeric_limits<int64_t>::max();

Review comment:
       Yes.
   I've added narrow range cases that have many duplicate values.

##########
File path: cpp/src/arrow/compute/kernels/vector_sort.cc
##########
@@ -346,14 +374,396 @@ void AddSortingKernels(VectorKernel base, VectorFunction* func) {
   }
 }
 
+class TableSorter : public TypeVisitor {
+ private:
+  struct ResolvedSortKey {
+    ResolvedSortKey(const ChunkedArray& chunked_array, const SortOrder order)
+        : order(order) {
+      type = chunked_array.type().get();
+      null_count = chunked_array.null_count();
+      num_chunks = chunked_array.num_chunks();
+      for (const auto& chunk : chunked_array.chunks()) {
+        chunks.push_back(chunk.get());
+      }
+    }
+
+    template <typename ArrayType>
+    ArrayType* ResolveChunk(int64_t index, int64_t& chunk_index) const {
+      if (num_chunks == 1) {
+        chunk_index = index;
+        return static_cast<ArrayType*>(chunks[0]);
+      } else {
+        int64_t offset = 0;
+        for (size_t i = 0; i < num_chunks; ++i) {
+          if (index < offset + chunks[i]->length()) {
+            chunk_index = index - offset;
+            return static_cast<ArrayType*>(chunks[i]);
+          }
+          offset += chunks[i]->length();
+        }
+        return nullptr;
+      }
+    }
+
+    SortOrder order;
+    DataType* type;
+    int64_t null_count;
+    size_t num_chunks;
+    std::vector<Array*> chunks;
+  };
+
+  class Comparer : public TypeVisitor {
+   public:
+    Comparer(const Table& table, const std::vector<SortKey>& sort_keys)
+        : TypeVisitor(), status_(Status::OK()) {
+      for (const auto& sort_key : sort_keys) {
+        const auto& chunked_array = table.GetColumnByName(sort_key.name);
+        if (!chunked_array) {
+          status_ = Status::Invalid("Nonexistent sort key column: ", sort_key.name);
+          return;
+        }
+        sort_keys_.emplace_back(*chunked_array, sort_key.order);
+      }
+    }
+
+    Status status() { return status_; }
+
+    const std::vector<ResolvedSortKey>& sort_keys() { return sort_keys_; }
+
+    bool Compare(uint64_t left, uint64_t right, size_t start_sort_key_index) {
+      current_left_ = left;
+      current_right_ = right;
+      current_compared_ = 0;
+      auto num_sort_keys = sort_keys_.size();
+      for (size_t i = start_sort_key_index; i < num_sort_keys; ++i) {
+        current_sort_key_index_ = i;
+        status_ = sort_keys_[i].type->Accept(this);
+        if (current_compared_ != 0) {
+          break;
+        }
+      }
+      return current_compared_ < 0;
+    }
+
+#define VISIT(TYPE)                                \
+  Status Visit(const TYPE##Type& type) override {  \
+    current_compared_ = CompareType<TYPE##Type>(); \
+    return Status::OK();                           \
+  }
+
+    VISIT(Int8)
+    VISIT(Int16)
+    VISIT(Int32)
+    VISIT(Int64)
+    VISIT(UInt8)
+    VISIT(UInt16)
+    VISIT(UInt32)
+    VISIT(UInt64)
+    VISIT(Float)
+    VISIT(Double)
+    VISIT(String)
+    VISIT(Binary)
+    VISIT(LargeString)
+    VISIT(LargeBinary)
+
+#undef VISIT
+
+   private:
+    template <typename Type>
+    int32_t CompareType() {
+      using ArrayType = typename TypeTraits<Type>::ArrayType;
+      const auto& sort_key = sort_keys_[current_sort_key_index_];
+      auto order = sort_key.order;
+      int64_t index_left = 0;
+      auto array_left = sort_key.ResolveChunk<ArrayType>(current_left_, index_left);
+      int64_t index_right = 0;
+      auto array_right = sort_key.ResolveChunk<ArrayType>(current_right_, index_right);
+      if (sort_key.null_count > 0) {
+        auto is_null_left = array_left->IsNull(index_left);
+        auto is_null_right = array_right->IsNull(index_right);
+        if (is_null_left && is_null_right) {
+          return 0;
+        } else if (is_null_left) {
+          return 1;
+        } else if (is_null_right) {
+          return -1;
+        }
+      }
+      auto left = array_left->GetView(index_left);
+      auto right = array_right->GetView(index_right);
+      int32_t compared;
+      if (left == right) {
+        compared = 0;
+      } else if (left > right) {
+        compared = 1;
+      } else {
+        compared = -1;
+      }
+      if (order == SortOrder::DESCENDING) {
+        compared = -compared;
+      }
+      return compared;
+    }
+
+    Status status_;
+    std::vector<ResolvedSortKey> sort_keys_;
+    int64_t current_left_;
+    int64_t current_right_;
+    size_t current_sort_key_index_;
+    int32_t current_compared_;
+  };
+
+ public:
+  TableSorter(uint64_t* indices_begin, uint64_t* indices_end, const Table& table,
+              const SortOptions& options)
+      : indices_begin_(indices_begin),
+        indices_end_(indices_end),
+        comparer_(table, options.sort_keys) {}
+
+  Status Sort() {
+    ARROW_RETURN_NOT_OK(comparer_.status());
+    return comparer_.sort_keys()[0].type->Accept(this);
+  }
+
+#define VISIT(TYPE) \
+  Status Visit(const TYPE##Type& type) override { return SortInternal<TYPE##Type>(); }
+
+  VISIT(Int8)
+  VISIT(Int16)
+  VISIT(Int32)
+  VISIT(Int64)
+  VISIT(UInt8)
+  VISIT(UInt16)
+  VISIT(UInt32)
+  VISIT(UInt64)
+  VISIT(Float)
+  VISIT(Double)
+  VISIT(String)
+  VISIT(Binary)
+  VISIT(LargeString)
+  VISIT(LargeBinary)
+
+#undef VISIT
+
+ private:
+  template <typename Type>
+  Status SortInternal() {

Review comment:
       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.

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



[GitHub] [arrow] kou commented on a change in pull request #8612: ARROW-8199: [C++] Add support for multi-column sort indices on Table

Posted by GitBox <gi...@apache.org>.
kou commented on a change in pull request #8612:
URL: https://github.com/apache/arrow/pull/8612#discussion_r526616431



##########
File path: cpp/src/arrow/compute/kernels/vector_sort.cc
##########
@@ -346,14 +374,396 @@ void AddSortingKernels(VectorKernel base, VectorFunction* func) {
   }
 }
 
+class TableSorter : public TypeVisitor {
+ private:
+  struct ResolvedSortKey {
+    ResolvedSortKey(const ChunkedArray& chunked_array, const SortOrder order)
+        : order(order) {
+      type = chunked_array.type().get();
+      null_count = chunked_array.null_count();
+      num_chunks = chunked_array.num_chunks();
+      for (const auto& chunk : chunked_array.chunks()) {
+        chunks.push_back(chunk.get());
+      }
+    }
+
+    template <typename ArrayType>
+    ArrayType* ResolveChunk(int64_t index, int64_t& chunk_index) const {
+      if (num_chunks == 1) {
+        chunk_index = index;
+        return static_cast<ArrayType*>(chunks[0]);
+      } else {
+        int64_t offset = 0;
+        for (size_t i = 0; i < num_chunks; ++i) {
+          if (index < offset + chunks[i]->length()) {
+            chunk_index = index - offset;
+            return static_cast<ArrayType*>(chunks[i]);
+          }
+          offset += chunks[i]->length();
+        }
+        return nullptr;
+      }
+    }
+
+    SortOrder order;
+    DataType* type;
+    int64_t null_count;
+    size_t num_chunks;
+    std::vector<Array*> chunks;
+  };
+
+  class Comparer : public TypeVisitor {
+   public:
+    Comparer(const Table& table, const std::vector<SortKey>& sort_keys)
+        : TypeVisitor(), status_(Status::OK()) {
+      for (const auto& sort_key : sort_keys) {
+        const auto& chunked_array = table.GetColumnByName(sort_key.name);
+        if (!chunked_array) {
+          status_ = Status::Invalid("Nonexistent sort key column: ", sort_key.name);
+          return;
+        }
+        sort_keys_.emplace_back(*chunked_array, sort_key.order);
+      }
+    }
+
+    Status status() { return status_; }
+
+    const std::vector<ResolvedSortKey>& sort_keys() { return sort_keys_; }
+
+    bool Compare(uint64_t left, uint64_t right, size_t start_sort_key_index) {
+      current_left_ = left;
+      current_right_ = right;
+      current_compared_ = 0;
+      auto num_sort_keys = sort_keys_.size();
+      for (size_t i = start_sort_key_index; i < num_sort_keys; ++i) {
+        current_sort_key_index_ = i;
+        status_ = sort_keys_[i].type->Accept(this);
+        if (current_compared_ != 0) {
+          break;
+        }
+      }
+      return current_compared_ < 0;
+    }
+
+#define VISIT(TYPE)                                \
+  Status Visit(const TYPE##Type& type) override {  \
+    current_compared_ = CompareType<TYPE##Type>(); \
+    return Status::OK();                           \
+  }
+
+    VISIT(Int8)
+    VISIT(Int16)
+    VISIT(Int32)
+    VISIT(Int64)
+    VISIT(UInt8)
+    VISIT(UInt16)
+    VISIT(UInt32)
+    VISIT(UInt64)
+    VISIT(Float)
+    VISIT(Double)
+    VISIT(String)
+    VISIT(Binary)
+    VISIT(LargeString)
+    VISIT(LargeBinary)
+
+#undef VISIT
+
+   private:
+    template <typename Type>
+    int32_t CompareType() {
+      using ArrayType = typename TypeTraits<Type>::ArrayType;
+      const auto& sort_key = sort_keys_[current_sort_key_index_];
+      auto order = sort_key.order;
+      int64_t index_left = 0;
+      auto array_left = sort_key.ResolveChunk<ArrayType>(current_left_, index_left);
+      int64_t index_right = 0;
+      auto array_right = sort_key.ResolveChunk<ArrayType>(current_right_, index_right);
+      if (sort_key.null_count > 0) {
+        auto is_null_left = array_left->IsNull(index_left);
+        auto is_null_right = array_right->IsNull(index_right);
+        if (is_null_left && is_null_right) {
+          return 0;
+        } else if (is_null_left) {
+          return 1;
+        } else if (is_null_right) {
+          return -1;
+        }
+      }
+      auto left = array_left->GetView(index_left);
+      auto right = array_right->GetView(index_right);
+      int32_t compared;
+      if (left == right) {
+        compared = 0;
+      } else if (left > right) {
+        compared = 1;
+      } else {
+        compared = -1;
+      }
+      if (order == SortOrder::DESCENDING) {
+        compared = -compared;
+      }
+      return compared;
+    }
+
+    Status status_;
+    std::vector<ResolvedSortKey> sort_keys_;
+    int64_t current_left_;
+    int64_t current_right_;
+    size_t current_sort_key_index_;
+    int32_t current_compared_;
+  };
+
+ public:
+  TableSorter(uint64_t* indices_begin, uint64_t* indices_end, const Table& table,
+              const SortOptions& options)
+      : indices_begin_(indices_begin),
+        indices_end_(indices_end),
+        comparer_(table, options.sort_keys) {}
+
+  Status Sort() {
+    ARROW_RETURN_NOT_OK(comparer_.status());
+    return comparer_.sort_keys()[0].type->Accept(this);
+  }
+
+#define VISIT(TYPE) \
+  Status Visit(const TYPE##Type& type) override { return SortInternal<TYPE##Type>(); }
+
+  VISIT(Int8)
+  VISIT(Int16)
+  VISIT(Int32)
+  VISIT(Int64)
+  VISIT(UInt8)
+  VISIT(UInt16)
+  VISIT(UInt32)
+  VISIT(UInt64)
+  VISIT(Float)
+  VISIT(Double)
+  VISIT(String)
+  VISIT(Binary)
+  VISIT(LargeString)
+  VISIT(LargeBinary)
+
+#undef VISIT
+
+ private:
+  template <typename Type>
+  Status SortInternal() {
+    using ArrayType = typename TypeTraits<Type>::ArrayType;
+    std::iota(indices_begin_, indices_end_, 0);
+
+    auto& comparer = comparer_;
+    const auto& first_sort_key = comparer.sort_keys()[0];
+    auto nulls_begin = indices_end_;
+    nulls_begin = PartitionNullsInternal<Type>(first_sort_key);
+    std::stable_sort(
+        indices_begin_, nulls_begin,
+        [&first_sort_key, &comparer](uint64_t left, uint64_t right) {
+          int64_t index_left = 0;
+          auto array_left = first_sort_key.ResolveChunk<ArrayType>(left, index_left);
+          int64_t index_right = 0;
+          auto array_right = first_sort_key.ResolveChunk<ArrayType>(right, index_right);
+          auto value_left = array_left->GetView(index_left);
+          auto value_right = array_right->GetView(index_right);
+          if (value_left == value_right) {
+            return comparer.Compare(left, right, 1);

Review comment:
       Confirmed. 2x-3x slower in the following cases:
   
   The number of records: 1048576
   
   Narrow range: Almost elements may be same
   
   Wide range: Almost elements will be different
   
   N sort keys   | 2           | 8           | 16
   ------------- | ----------- | ----------- | -----------
   Narrow range  | 373997366ns | 556003297ns | 519211265ns
   Wide range    | 167679014ns | 167135310ns | 166726078ns
   Narrow / Wide | 2.23        | 3.32        | 3.11
   
   In wide range cases, the number of sort keys don't affect performance.
   




----------------------------------------------------------------
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.

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



[GitHub] [arrow] kou commented on a change in pull request #8612: ARROW-8199: [C++] Add support for multi-column sort indices on Table

Posted by GitBox <gi...@apache.org>.
kou commented on a change in pull request #8612:
URL: https://github.com/apache/arrow/pull/8612#discussion_r526619205



##########
File path: cpp/src/arrow/compute/kernels/vector_sort_test.cc
##########
@@ -364,32 +400,264 @@ TYPED_TEST(TestSortToIndicesKernelRandomCount, SortRandomValuesCount) {
   int range = 2000;
   for (int test = 0; test < times; test++) {
     for (auto null_probability : {0.0, 0.1, 0.5, 1.0}) {
-      auto array = rand.Generate(length, range, null_probability);
-      ASSERT_OK_AND_ASSIGN(std::shared_ptr<Array> offsets, SortToIndices(*array));
-      ValidateSorted<ArrayType>(*checked_pointer_cast<ArrayType>(array),
-                                *checked_pointer_cast<UInt64Array>(offsets));
+      for (auto order : {SortOrder::ASCENDING, SortOrder::DESCENDING}) {
+        auto array = rand.Generate(length, range, null_probability);
+        ASSERT_OK_AND_ASSIGN(std::shared_ptr<Array> offsets, SortIndices(*array, order));
+        ValidateSorted<ArrayType>(*checked_pointer_cast<ArrayType>(array),
+                                  *checked_pointer_cast<UInt64Array>(offsets), order);
+      }
     }
   }
 }
 
 // Long array with big value range: std::stable_sort
-TYPED_TEST_SUITE(TestSortToIndicesKernelRandomCompare, IntegralArrowTypes);
+TYPED_TEST_SUITE(TestArraySortIndicesKernelRandomCompare, IntegralArrowTypes);
 
-TYPED_TEST(TestSortToIndicesKernelRandomCompare, SortRandomValuesCompare) {
+TYPED_TEST(TestArraySortIndicesKernelRandomCompare, SortRandomValuesCompare) {
   using ArrayType = typename TypeTraits<TypeParam>::ArrayType;
 
   Random<TypeParam> rand(0x5487657);
   int times = 5;
   int length = 4000;
   for (int test = 0; test < times; test++) {
     for (auto null_probability : {0.0, 0.1, 0.5, 1.0}) {
-      auto array = rand.Generate(length, null_probability);
-      ASSERT_OK_AND_ASSIGN(std::shared_ptr<Array> offsets, SortToIndices(*array));
-      ValidateSorted<ArrayType>(*checked_pointer_cast<ArrayType>(array),
-                                *checked_pointer_cast<UInt64Array>(offsets));
+      for (auto order : {SortOrder::ASCENDING, SortOrder::DESCENDING}) {
+        auto array = rand.Generate(length, null_probability);
+        ASSERT_OK_AND_ASSIGN(std::shared_ptr<Array> offsets, SortIndices(*array, order));
+        ValidateSorted<ArrayType>(*checked_pointer_cast<ArrayType>(array),
+                                  *checked_pointer_cast<UInt64Array>(offsets), order);
+      }
     }
   }
 }
 
+class TestTableSortIndices : public ::testing::Test {
+ protected:
+  void AssertSortIndices(const std::shared_ptr<Table> table, const SortOptions& options,
+                         const std::shared_ptr<Array> expected) {
+    ASSERT_OK_AND_ASSIGN(auto actual, SortIndices(*table, options));
+    AssertArraysEqual(*expected, *actual);
+  }
+
+  void AssertSortIndices(const std::shared_ptr<Table> table, const SortOptions& options,
+                         const std::string expected) {
+    AssertSortIndices(table, options, ArrayFromJSON(uint64(), expected));
+  }
+};
+
+TEST_F(TestTableSortIndices, SortNull) {
+  auto table = TableFromJSON(schema({
+                                 {field("a", uint8())},
+                                 {field("b", uint8())},
+                             }),
+                             {"["
+                              "{\"a\": null, \"b\": 5},"
+                              "{\"a\": 1,    \"b\": 3},"
+                              "{\"a\": 3,    \"b\": null},"
+                              "{\"a\": null, \"b\": null},"
+                              "{\"a\": 2,    \"b\": 5},"
+                              "{\"a\": 1,    \"b\": 5}"
+                              "]"});
+  SortOptions options(
+      {SortKey("a", SortOrder::ASCENDING), SortKey("b", SortOrder::DESCENDING)});
+  this->AssertSortIndices(table, options, "[5, 1, 4, 2, 0, 3]");
+}
+
+TEST_F(TestTableSortIndices, SortNaN) {
+  auto table = TableFromJSON(schema({
+                                 {field("a", float32())},
+                                 {field("b", float32())},
+                             }),
+                             {"["
+                              "{\"a\": null, \"b\": 5},"
+                              "{\"a\": 1,    \"b\": 3},"
+                              "{\"a\": 3,    \"b\": null},"
+                              "{\"a\": null, \"b\": null},"
+                              "{\"a\": NaN,  \"b\": null},"
+                              "{\"a\": NaN,  \"b\": 5},"
+                              "{\"a\": NaN,  \"b\": NaN},"
+                              "{\"a\": 1,    \"b\": 5}"
+                              "]"});
+  SortOptions options(
+      {SortKey("a", SortOrder::ASCENDING), SortKey("b", SortOrder::DESCENDING)});
+  this->AssertSortIndices(table, options, "[7, 1, 2, 5, 6, 4, 0, 3]");
+}
+
+using RandomParam = std::tuple<std::string, double>;
+class TestTableSortIndicesRandom : public testing::TestWithParam<RandomParam> {
+  class Comparator : public TypeVisitor {
+   public:
+    bool operator()(const Table& table, const SortOptions& options, uint64_t lhs,
+                    uint64_t rhs) {
+      lhs_ = lhs;
+      rhs_ = rhs;
+      for (const auto& sort_key : options.sort_keys) {
+        auto chunked_array = table.GetColumnByName(sort_key.name);
+        lhs_array_ = findTargetArray(chunked_array, lhs, lhs_index_);
+        rhs_array_ = findTargetArray(chunked_array, rhs, rhs_index_);
+        if (rhs_array_->IsNull(rhs_index_) && lhs_array_->IsNull(lhs_index_)) continue;
+        if (rhs_array_->IsNull(rhs_index_)) return true;
+        if (lhs_array_->IsNull(lhs_index_)) return false;
+        status_ = lhs_array_->type()->Accept(this);
+        if (compared_ == 0) continue;
+        if (sort_key.order == SortOrder::ASCENDING) {
+          return compared_ < 0;
+        } else {
+          return compared_ > 0;
+        }
+      }
+      return lhs < rhs;
+    }
+
+    Status status() const { return status_; }
+
+#define VISIT(TYPE)                               \
+  Status Visit(const TYPE##Type& type) override { \
+    compared_ = CompareType<TYPE##Type>();        \
+    return Status::OK();                          \
+  }
+
+    VISIT(Int8)
+    VISIT(Int16)
+    VISIT(Int32)
+    VISIT(Int64)
+    VISIT(UInt8)
+    VISIT(UInt16)
+    VISIT(UInt32)
+    VISIT(UInt64)
+    VISIT(Float)
+    VISIT(Double)
+    VISIT(String)
+
+#undef VISIT
+
+   private:
+    std::shared_ptr<Array> findTargetArray(std::shared_ptr<ChunkedArray> chunked_array,

Review comment:
       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.

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



[GitHub] [arrow] kou commented on a change in pull request #8612: ARROW-8199: [C++] Add support for multi-column sort indices on Table

Posted by GitBox <gi...@apache.org>.
kou commented on a change in pull request #8612:
URL: https://github.com/apache/arrow/pull/8612#discussion_r526630171



##########
File path: cpp/src/arrow/compute/kernels/vector_sort.cc
##########
@@ -346,14 +499,644 @@ void AddSortingKernels(VectorKernel base, VectorFunction* func) {
   }
 }
 
+// Sort a chunked array directly without sorting each array in the
+// chunked array. This is used for processing the second and following
+// sort keys in TableRadixSorter.
+//
+// This uses the same algorithm as ArrayCompareSorter.
+template <typename Type>
+class ChunkedArrayCompareSorter {
+  using ArrayType = typename TypeTraits<Type>::ArrayType;
+
+ public:
+  // Returns where null starts.
+  uint64_t* Sort(uint64_t* indices_begin, uint64_t* indices_end,
+                 std::vector<const Array*>& arrays, int64_t null_count,
+                 const ArraySortOptions& options) {
+    auto nulls_begin = PartitionNulls<ArrayType, StablePartitioner>(
+        indices_begin, indices_end, arrays, null_count);
+    if (options.order == SortOrder::Ascending) {
+      std::stable_sort(indices_begin, nulls_begin,
+                       [&arrays](uint64_t left, uint64_t right) {
+                         const auto chunk_left = ResolveChunk<ArrayType>(arrays, left);
+                         const auto chunk_right = ResolveChunk<ArrayType>(arrays, right);
+                         return chunk_left.GetView() < chunk_right.GetView();
+                       });
+    } else {
+      std::stable_sort(indices_begin, nulls_begin,
+                       [&arrays](uint64_t left, uint64_t right) {
+                         const auto chunk_left = ResolveChunk<ArrayType>(arrays, left);
+                         const auto chunk_right = ResolveChunk<ArrayType>(arrays, right);
+                         // We don't use 'left > right' here to reduce required operator.
+                         // If we use 'right < left' here, '<' is only required.
+                         return chunk_right.GetView() < chunk_left.GetView();
+                       });
+    }
+    return nulls_begin;
+  }
+};
+
+// Sort a chunked array by sorting each array in the chunked array.
+//
+// TODO: This is a naive implementation. We'll be able to improve
+// performance of this. For example, we'll be able to use threads for
+// sorting each array.
+class ChunkedArraySorter : public TypeVisitor {
+ public:
+  ChunkedArraySorter(uint64_t* indices_begin, uint64_t* indices_end,
+                     const ChunkedArray& chunked_array, const SortOrder order,
+                     bool can_use_array_sorter = true)
+      : TypeVisitor(),
+        indices_begin_(indices_begin),
+        indices_end_(indices_end),
+        chunked_array_(chunked_array),
+        order_(order),
+        can_use_array_sorter_(can_use_array_sorter) {}
+
+  Status Sort() { return chunked_array_.type()->Accept(this); }
+
+#define VISIT(TYPE) \
+  Status Visit(const TYPE##Type& type) override { return SortInternal<TYPE##Type>(); }
+
+  VISIT(Int8)
+  VISIT(Int16)
+  VISIT(Int32)
+  VISIT(Int64)
+  VISIT(UInt8)
+  VISIT(UInt16)
+  VISIT(UInt32)
+  VISIT(UInt64)
+  VISIT(Float)
+  VISIT(Double)
+  VISIT(String)
+  VISIT(Binary)
+  VISIT(LargeString)
+  VISIT(LargeBinary)
+
+#undef VISIT
+
+ private:
+  template <typename Type>
+  Status SortInternal() {
+    using ArrayType = typename TypeTraits<Type>::ArrayType;
+    ArraySortOptions options(order_);
+    const auto num_chunks = chunked_array_.num_chunks();
+    const auto& shared_arrays = chunked_array_.chunks();
+    std::vector<const Array*> arrays(num_chunks);
+    for (int i = 0; i < num_chunks; ++i) {
+      const auto& array = shared_arrays[i];
+      arrays[i] = array.get();
+    }
+    if (can_use_array_sorter_) {
+      // Sort each chunk from the beginning and merge to sorted indices.
+      // This is a naive implementation.
+      ArraySorter<Type> sorter;
+      int64_t begin_offset = 0;
+      int64_t end_offset = 0;
+      int64_t null_count = 0;
+      uint64_t* left_nulls_begin = indices_begin_;
+      for (int i = 0; i < num_chunks; ++i) {
+        const auto array = static_cast<const ArrayType*>(arrays[i]);
+        end_offset += array->length();
+        null_count += array->null_count();
+        uint64_t* right_nulls_begin;
+        right_nulls_begin =
+            sorter.impl.Sort(indices_begin_ + begin_offset, indices_begin_ + end_offset,
+                             *array, begin_offset, options);
+        if (i > 0) {
+          left_nulls_begin = Merge<ArrayType>(
+              indices_begin_, indices_begin_ + begin_offset, indices_begin_ + end_offset,
+              left_nulls_begin, right_nulls_begin, arrays, null_count, order_);
+        } else {
+          left_nulls_begin = right_nulls_begin;
+        }
+        begin_offset = end_offset;
+      }
+    } else {
+      // Sort the chunked array directory.
+      ChunkedArrayCompareSorter<Type> sorter;
+      sorter.Sort(indices_begin_, indices_end_, arrays, chunked_array_.null_count(),
+                  options);
+    }
+    return Status::OK();
+  }
+
+  // Merges two sorted indices arrays and returns where nulls starts.
+  // Where nulls starts is used when the next merge to detect the
+  // sorted indices locations.
+  template <typename ArrayType>
+  uint64_t* Merge(uint64_t* indices_begin, uint64_t* indices_middle,
+                  uint64_t* indices_end, uint64_t* left_nulls_begin,
+                  uint64_t* right_nulls_begin, std::vector<const Array*> arrays,
+                  int64_t null_count, const SortOrder order) {
+    auto left_num_non_nulls = left_nulls_begin - indices_begin;
+    auto right_num_non_nulls = right_nulls_begin - indices_middle;
+    auto nulls_begin = PartitionNulls<ArrayType, StablePartitioner>(
+        indices_begin, indices_end, arrays, null_count);
+    indices_middle = indices_begin + left_num_non_nulls;
+    indices_end = indices_middle + right_num_non_nulls;
+    if (order == SortOrder::Ascending) {
+      std::inplace_merge(indices_begin, indices_middle, indices_end,
+                         [&arrays](uint64_t left, uint64_t right) {
+                           const auto chunk_left = ResolveChunk<ArrayType>(arrays, left);
+                           const auto chunk_right =
+                               ResolveChunk<ArrayType>(arrays, right);
+                           return chunk_left.GetView() < chunk_right.GetView();
+                         });
+    } else {
+      std::inplace_merge(indices_begin, indices_middle, indices_end,
+                         [&arrays](uint64_t left, uint64_t right) {
+                           const auto chunk_left = ResolveChunk<ArrayType>(arrays, left);
+                           const auto chunk_right =
+                               ResolveChunk<ArrayType>(arrays, right);
+                           // We don't use 'left > right' here to reduce required
+                           // operator. If we use 'right < left' here, '<' is only
+                           // required.
+                           return chunk_right.GetView() < chunk_left.GetView();
+                         });
+    }
+    return nulls_begin;
+  }
+
+  uint64_t* indices_begin_;
+  uint64_t* indices_end_;
+  const ChunkedArray& chunked_array_;
+  const SortOrder order_;
+  const bool can_use_array_sorter_;
+};
+
+// Sort a table from the back like radix sort.
+class TableRadixSorter {
+ public:
+  Status Sort(uint64_t* indices_begin, uint64_t* indices_end, const Table& table,
+              const SortOptions& options) {
+    for (auto i = options.sort_keys.size(); i > 0; --i) {
+      const auto& sort_key = options.sort_keys[i - 1];
+      const auto& chunked_array = table.GetColumnByName(sort_key.name);
+      if (!chunked_array) {
+        return Status::Invalid("Nonexistent sort key column: ", sort_key.name);
+      }
+      // We can use ArraySorter only for the sort key that is
+      // processed first because ArraySorter doesn't care about
+      // existing indices.
+      const auto can_use_array_sorter = (i == 0);
+      ChunkedArraySorter sorter(indices_begin, indices_end, *chunked_array.get(),
+                                sort_key.order, can_use_array_sorter);
+      ARROW_RETURN_NOT_OK(sorter.Sort());
+    }
+    return Status::OK();
+  }
+};
+
+// Sort a table from the beginning.
+class TableFromTheBeginningSorter : public TypeVisitor {

Review comment:
       Can anyone suggest better name...?




----------------------------------------------------------------
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.

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



[GitHub] [arrow] kou commented on a change in pull request #8612: ARROW-8199: [C++] Add support for multi-column sort indices on Table

Posted by GitBox <gi...@apache.org>.
kou commented on a change in pull request #8612:
URL: https://github.com/apache/arrow/pull/8612#discussion_r526616431



##########
File path: cpp/src/arrow/compute/kernels/vector_sort.cc
##########
@@ -346,14 +374,396 @@ void AddSortingKernels(VectorKernel base, VectorFunction* func) {
   }
 }
 
+class TableSorter : public TypeVisitor {
+ private:
+  struct ResolvedSortKey {
+    ResolvedSortKey(const ChunkedArray& chunked_array, const SortOrder order)
+        : order(order) {
+      type = chunked_array.type().get();
+      null_count = chunked_array.null_count();
+      num_chunks = chunked_array.num_chunks();
+      for (const auto& chunk : chunked_array.chunks()) {
+        chunks.push_back(chunk.get());
+      }
+    }
+
+    template <typename ArrayType>
+    ArrayType* ResolveChunk(int64_t index, int64_t& chunk_index) const {
+      if (num_chunks == 1) {
+        chunk_index = index;
+        return static_cast<ArrayType*>(chunks[0]);
+      } else {
+        int64_t offset = 0;
+        for (size_t i = 0; i < num_chunks; ++i) {
+          if (index < offset + chunks[i]->length()) {
+            chunk_index = index - offset;
+            return static_cast<ArrayType*>(chunks[i]);
+          }
+          offset += chunks[i]->length();
+        }
+        return nullptr;
+      }
+    }
+
+    SortOrder order;
+    DataType* type;
+    int64_t null_count;
+    size_t num_chunks;
+    std::vector<Array*> chunks;
+  };
+
+  class Comparer : public TypeVisitor {
+   public:
+    Comparer(const Table& table, const std::vector<SortKey>& sort_keys)
+        : TypeVisitor(), status_(Status::OK()) {
+      for (const auto& sort_key : sort_keys) {
+        const auto& chunked_array = table.GetColumnByName(sort_key.name);
+        if (!chunked_array) {
+          status_ = Status::Invalid("Nonexistent sort key column: ", sort_key.name);
+          return;
+        }
+        sort_keys_.emplace_back(*chunked_array, sort_key.order);
+      }
+    }
+
+    Status status() { return status_; }
+
+    const std::vector<ResolvedSortKey>& sort_keys() { return sort_keys_; }
+
+    bool Compare(uint64_t left, uint64_t right, size_t start_sort_key_index) {
+      current_left_ = left;
+      current_right_ = right;
+      current_compared_ = 0;
+      auto num_sort_keys = sort_keys_.size();
+      for (size_t i = start_sort_key_index; i < num_sort_keys; ++i) {
+        current_sort_key_index_ = i;
+        status_ = sort_keys_[i].type->Accept(this);
+        if (current_compared_ != 0) {
+          break;
+        }
+      }
+      return current_compared_ < 0;
+    }
+
+#define VISIT(TYPE)                                \
+  Status Visit(const TYPE##Type& type) override {  \
+    current_compared_ = CompareType<TYPE##Type>(); \
+    return Status::OK();                           \
+  }
+
+    VISIT(Int8)
+    VISIT(Int16)
+    VISIT(Int32)
+    VISIT(Int64)
+    VISIT(UInt8)
+    VISIT(UInt16)
+    VISIT(UInt32)
+    VISIT(UInt64)
+    VISIT(Float)
+    VISIT(Double)
+    VISIT(String)
+    VISIT(Binary)
+    VISIT(LargeString)
+    VISIT(LargeBinary)
+
+#undef VISIT
+
+   private:
+    template <typename Type>
+    int32_t CompareType() {
+      using ArrayType = typename TypeTraits<Type>::ArrayType;
+      const auto& sort_key = sort_keys_[current_sort_key_index_];
+      auto order = sort_key.order;
+      int64_t index_left = 0;
+      auto array_left = sort_key.ResolveChunk<ArrayType>(current_left_, index_left);
+      int64_t index_right = 0;
+      auto array_right = sort_key.ResolveChunk<ArrayType>(current_right_, index_right);
+      if (sort_key.null_count > 0) {
+        auto is_null_left = array_left->IsNull(index_left);
+        auto is_null_right = array_right->IsNull(index_right);
+        if (is_null_left && is_null_right) {
+          return 0;
+        } else if (is_null_left) {
+          return 1;
+        } else if (is_null_right) {
+          return -1;
+        }
+      }
+      auto left = array_left->GetView(index_left);
+      auto right = array_right->GetView(index_right);
+      int32_t compared;
+      if (left == right) {
+        compared = 0;
+      } else if (left > right) {
+        compared = 1;
+      } else {
+        compared = -1;
+      }
+      if (order == SortOrder::DESCENDING) {
+        compared = -compared;
+      }
+      return compared;
+    }
+
+    Status status_;
+    std::vector<ResolvedSortKey> sort_keys_;
+    int64_t current_left_;
+    int64_t current_right_;
+    size_t current_sort_key_index_;
+    int32_t current_compared_;
+  };
+
+ public:
+  TableSorter(uint64_t* indices_begin, uint64_t* indices_end, const Table& table,
+              const SortOptions& options)
+      : indices_begin_(indices_begin),
+        indices_end_(indices_end),
+        comparer_(table, options.sort_keys) {}
+
+  Status Sort() {
+    ARROW_RETURN_NOT_OK(comparer_.status());
+    return comparer_.sort_keys()[0].type->Accept(this);
+  }
+
+#define VISIT(TYPE) \
+  Status Visit(const TYPE##Type& type) override { return SortInternal<TYPE##Type>(); }
+
+  VISIT(Int8)
+  VISIT(Int16)
+  VISIT(Int32)
+  VISIT(Int64)
+  VISIT(UInt8)
+  VISIT(UInt16)
+  VISIT(UInt32)
+  VISIT(UInt64)
+  VISIT(Float)
+  VISIT(Double)
+  VISIT(String)
+  VISIT(Binary)
+  VISIT(LargeString)
+  VISIT(LargeBinary)
+
+#undef VISIT
+
+ private:
+  template <typename Type>
+  Status SortInternal() {
+    using ArrayType = typename TypeTraits<Type>::ArrayType;
+    std::iota(indices_begin_, indices_end_, 0);
+
+    auto& comparer = comparer_;
+    const auto& first_sort_key = comparer.sort_keys()[0];
+    auto nulls_begin = indices_end_;
+    nulls_begin = PartitionNullsInternal<Type>(first_sort_key);
+    std::stable_sort(
+        indices_begin_, nulls_begin,
+        [&first_sort_key, &comparer](uint64_t left, uint64_t right) {
+          int64_t index_left = 0;
+          auto array_left = first_sort_key.ResolveChunk<ArrayType>(left, index_left);
+          int64_t index_right = 0;
+          auto array_right = first_sort_key.ResolveChunk<ArrayType>(right, index_right);
+          auto value_left = array_left->GetView(index_left);
+          auto value_right = array_right->GetView(index_right);
+          if (value_left == value_right) {
+            return comparer.Compare(left, right, 1);

Review comment:
       Confirmed. 2x-3x slower in the following cases:
   
   The number of records: 1048576
   
   Wide range: Almost elements will be different
   
   Narrow range: Almost elements may be same
   
   N sort keys   | 2           | 8           | 16
   ------------- | ----------- | ----------- | -----------
   Narrow range  | 373997366ns | 556003297ns | 519211265ns
   Wide range    | 167679014ns | 167135310ns | 166726078ns
   Narrow / Wide | 2.23        | 3.32        | 3.11
   
   In wide range cases, the number of sort keys don't affect performance.
   




----------------------------------------------------------------
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.

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



[GitHub] [arrow] github-actions[bot] commented on pull request #8612: ARROW-8199: [C++] Add support for multi-column sort indices on Table

Posted by GitBox <gi...@apache.org>.
github-actions[bot] commented on pull request #8612:
URL: https://github.com/apache/arrow/pull/8612#issuecomment-723737307


   https://issues.apache.org/jira/browse/ARROW-8199


----------------------------------------------------------------
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.

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



[GitHub] [arrow] kou commented on a change in pull request #8612: ARROW-8199: [C++] Add support for multi-column sort indices on Table

Posted by GitBox <gi...@apache.org>.
kou commented on a change in pull request #8612:
URL: https://github.com/apache/arrow/pull/8612#discussion_r526611732



##########
File path: cpp/src/arrow/compute/api_vector.h
##########
@@ -165,8 +194,50 @@ Result<std::shared_ptr<Array>> NthToIndices(const Array& values, int64_t n,
 /// \param[in] ctx the function execution context, optional
 /// \return offsets indices that would sort an array
 ARROW_EXPORT
-Result<std::shared_ptr<Array>> SortToIndices(const Array& values,
-                                             ExecContext* ctx = NULLPTR);
+Result<std::shared_ptr<Array>> SortIndices(const Array& values,
+                                           ExecContext* ctx = NULLPTR);
+
+/// \brief Returns the indices that would sort an array in the
+/// specified order.
+///
+/// Perform an indirect sort of array. The output array will contain
+/// indices that would sort an array, which would be the same length
+/// as input. Nulls will be stably partitioned to the end of the output.

Review comment:
       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.

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



[GitHub] [arrow] kou commented on a change in pull request #8612: ARROW-8199: [C++] Add support for multi-column sort indices on Table

Posted by GitBox <gi...@apache.org>.
kou commented on a change in pull request #8612:
URL: https://github.com/apache/arrow/pull/8612#discussion_r526619094



##########
File path: cpp/src/arrow/compute/kernels/vector_sort_test.cc
##########
@@ -364,32 +400,264 @@ TYPED_TEST(TestSortToIndicesKernelRandomCount, SortRandomValuesCount) {
   int range = 2000;
   for (int test = 0; test < times; test++) {
     for (auto null_probability : {0.0, 0.1, 0.5, 1.0}) {
-      auto array = rand.Generate(length, range, null_probability);
-      ASSERT_OK_AND_ASSIGN(std::shared_ptr<Array> offsets, SortToIndices(*array));
-      ValidateSorted<ArrayType>(*checked_pointer_cast<ArrayType>(array),
-                                *checked_pointer_cast<UInt64Array>(offsets));
+      for (auto order : {SortOrder::ASCENDING, SortOrder::DESCENDING}) {
+        auto array = rand.Generate(length, range, null_probability);
+        ASSERT_OK_AND_ASSIGN(std::shared_ptr<Array> offsets, SortIndices(*array, order));
+        ValidateSorted<ArrayType>(*checked_pointer_cast<ArrayType>(array),
+                                  *checked_pointer_cast<UInt64Array>(offsets), order);
+      }
     }
   }
 }
 
 // Long array with big value range: std::stable_sort
-TYPED_TEST_SUITE(TestSortToIndicesKernelRandomCompare, IntegralArrowTypes);
+TYPED_TEST_SUITE(TestArraySortIndicesKernelRandomCompare, IntegralArrowTypes);
 
-TYPED_TEST(TestSortToIndicesKernelRandomCompare, SortRandomValuesCompare) {
+TYPED_TEST(TestArraySortIndicesKernelRandomCompare, SortRandomValuesCompare) {
   using ArrayType = typename TypeTraits<TypeParam>::ArrayType;
 
   Random<TypeParam> rand(0x5487657);
   int times = 5;
   int length = 4000;
   for (int test = 0; test < times; test++) {
     for (auto null_probability : {0.0, 0.1, 0.5, 1.0}) {
-      auto array = rand.Generate(length, null_probability);
-      ASSERT_OK_AND_ASSIGN(std::shared_ptr<Array> offsets, SortToIndices(*array));
-      ValidateSorted<ArrayType>(*checked_pointer_cast<ArrayType>(array),
-                                *checked_pointer_cast<UInt64Array>(offsets));
+      for (auto order : {SortOrder::ASCENDING, SortOrder::DESCENDING}) {
+        auto array = rand.Generate(length, null_probability);
+        ASSERT_OK_AND_ASSIGN(std::shared_ptr<Array> offsets, SortIndices(*array, order));
+        ValidateSorted<ArrayType>(*checked_pointer_cast<ArrayType>(array),
+                                  *checked_pointer_cast<UInt64Array>(offsets), order);
+      }
     }
   }
 }
 
+class TestTableSortIndices : public ::testing::Test {
+ protected:
+  void AssertSortIndices(const std::shared_ptr<Table> table, const SortOptions& options,
+                         const std::shared_ptr<Array> expected) {
+    ASSERT_OK_AND_ASSIGN(auto actual, SortIndices(*table, options));
+    AssertArraysEqual(*expected, *actual);
+  }
+
+  void AssertSortIndices(const std::shared_ptr<Table> table, const SortOptions& options,
+                         const std::string expected) {
+    AssertSortIndices(table, options, ArrayFromJSON(uint64(), expected));
+  }
+};
+
+TEST_F(TestTableSortIndices, SortNull) {
+  auto table = TableFromJSON(schema({
+                                 {field("a", uint8())},
+                                 {field("b", uint8())},
+                             }),
+                             {"["
+                              "{\"a\": null, \"b\": 5},"
+                              "{\"a\": 1,    \"b\": 3},"
+                              "{\"a\": 3,    \"b\": null},"
+                              "{\"a\": null, \"b\": null},"
+                              "{\"a\": 2,    \"b\": 5},"
+                              "{\"a\": 1,    \"b\": 5}"
+                              "]"});
+  SortOptions options(
+      {SortKey("a", SortOrder::ASCENDING), SortKey("b", SortOrder::DESCENDING)});
+  this->AssertSortIndices(table, options, "[5, 1, 4, 2, 0, 3]");
+}
+
+TEST_F(TestTableSortIndices, SortNaN) {
+  auto table = TableFromJSON(schema({
+                                 {field("a", float32())},
+                                 {field("b", float32())},
+                             }),
+                             {"["
+                              "{\"a\": null, \"b\": 5},"
+                              "{\"a\": 1,    \"b\": 3},"
+                              "{\"a\": 3,    \"b\": null},"
+                              "{\"a\": null, \"b\": null},"
+                              "{\"a\": NaN,  \"b\": null},"
+                              "{\"a\": NaN,  \"b\": 5},"
+                              "{\"a\": NaN,  \"b\": NaN},"
+                              "{\"a\": 1,    \"b\": 5}"
+                              "]"});
+  SortOptions options(
+      {SortKey("a", SortOrder::ASCENDING), SortKey("b", SortOrder::DESCENDING)});
+  this->AssertSortIndices(table, options, "[7, 1, 2, 5, 6, 4, 0, 3]");
+}
+
+using RandomParam = std::tuple<std::string, double>;
+class TestTableSortIndicesRandom : public testing::TestWithParam<RandomParam> {
+  class Comparator : public TypeVisitor {

Review comment:
       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.

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



[GitHub] [arrow] kou commented on a change in pull request #8612: ARROW-8199: [C++] Add support for multi-column sort indices on Table

Posted by GitBox <gi...@apache.org>.
kou commented on a change in pull request #8612:
URL: https://github.com/apache/arrow/pull/8612#discussion_r526619025



##########
File path: cpp/src/arrow/compute/kernels/vector_sort_test.cc
##########
@@ -228,134 +233,165 @@ TYPED_TEST(TestNthToIndicesRandom, RandomValues) {
 using arrow::internal::checked_pointer_cast;
 
 template <typename ArrowType>
-class TestSortToIndicesKernel : public TestBase {
+class TestArraySortIndicesKernel : public TestBase {
  private:
-  void AssertSortToIndicesArrays(const std::shared_ptr<Array> values,
-                                 const std::shared_ptr<Array> expected) {
-    ASSERT_OK_AND_ASSIGN(std::shared_ptr<Array> actual, SortToIndices(*values));
+  void AssertArraysSortIndices(const std::shared_ptr<Array> values, SortOrder order,
+                               const std::shared_ptr<Array> expected) {
+    ASSERT_OK_AND_ASSIGN(std::shared_ptr<Array> actual, SortIndices(*values, order));
     ASSERT_OK(actual->ValidateFull());
     AssertArraysEqual(*expected, *actual);
   }
 
  protected:
-  virtual void AssertSortToIndices(const std::string& values,
-                                   const std::string& expected) {
+  virtual void AssertSortIndices(const std::string& values, SortOrder order,
+                                 const std::string& expected) {
     auto type = TypeTraits<ArrowType>::type_singleton();
-    AssertSortToIndicesArrays(ArrayFromJSON(type, values),
-                              ArrayFromJSON(uint64(), expected));
+    AssertArraysSortIndices(ArrayFromJSON(type, values), order,
+                            ArrayFromJSON(uint64(), expected));
+  }
+
+  virtual void AssertSortIndices(const std::string& values, const std::string& expected) {
+    AssertSortIndices(values, SortOrder::ASCENDING, expected);
   }
 };
 
 template <typename ArrowType>
-class TestSortToIndicesKernelForReal : public TestSortToIndicesKernel<ArrowType> {};
-TYPED_TEST_SUITE(TestSortToIndicesKernelForReal, RealArrowTypes);
+class TestArraySortIndicesKernelForReal : public TestArraySortIndicesKernel<ArrowType> {};
+TYPED_TEST_SUITE(TestArraySortIndicesKernelForReal, RealArrowTypes);
 
 template <typename ArrowType>
-class TestSortToIndicesKernelForIntegral : public TestSortToIndicesKernel<ArrowType> {};
-TYPED_TEST_SUITE(TestSortToIndicesKernelForIntegral, IntegralArrowTypes);
+class TestArraySortIndicesKernelForIntegral
+    : public TestArraySortIndicesKernel<ArrowType> {};
+TYPED_TEST_SUITE(TestArraySortIndicesKernelForIntegral, IntegralArrowTypes);
 
 template <typename ArrowType>
-class TestSortToIndicesKernelForStrings : public TestSortToIndicesKernel<ArrowType> {};
-TYPED_TEST_SUITE(TestSortToIndicesKernelForStrings, testing::Types<StringType>);
+class TestArraySortIndicesKernelForStrings
+    : public TestArraySortIndicesKernel<ArrowType> {};
+TYPED_TEST_SUITE(TestArraySortIndicesKernelForStrings, testing::Types<StringType>);
+
+TYPED_TEST(TestArraySortIndicesKernelForReal, SortReal) {
+  this->AssertSortIndices("[]", "[]");
+
+  this->AssertSortIndices("[3.4, 2.6, 6.3]", "[1, 0, 2]");
+  this->AssertSortIndices("[1.1, 2.4, 3.5, 4.3, 5.1, 6.8, 7.3]", "[0,1,2,3,4,5,6]");

Review comment:
       Added a space after `,` including existing JSON 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.

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



[GitHub] [arrow] kou commented on a change in pull request #8612: ARROW-8199: [C++] Add support for multi-column sort indices on Table

Posted by GitBox <gi...@apache.org>.
kou commented on a change in pull request #8612:
URL: https://github.com/apache/arrow/pull/8612#discussion_r526612977



##########
File path: cpp/src/arrow/compute/kernels/vector_sort.cc
##########
@@ -346,14 +374,396 @@ void AddSortingKernels(VectorKernel base, VectorFunction* func) {
   }
 }
 
+class TableSorter : public TypeVisitor {
+ private:
+  struct ResolvedSortKey {
+    ResolvedSortKey(const ChunkedArray& chunked_array, const SortOrder order)
+        : order(order) {
+      type = chunked_array.type().get();
+      null_count = chunked_array.null_count();
+      num_chunks = chunked_array.num_chunks();
+      for (const auto& chunk : chunked_array.chunks()) {
+        chunks.push_back(chunk.get());
+      }
+    }
+
+    template <typename ArrayType>
+    ArrayType* ResolveChunk(int64_t index, int64_t& chunk_index) const {
+      if (num_chunks == 1) {
+        chunk_index = index;
+        return static_cast<ArrayType*>(chunks[0]);
+      } else {
+        int64_t offset = 0;
+        for (size_t i = 0; i < num_chunks; ++i) {
+          if (index < offset + chunks[i]->length()) {
+            chunk_index = index - offset;
+            return static_cast<ArrayType*>(chunks[i]);
+          }
+          offset += chunks[i]->length();
+        }
+        return nullptr;
+      }
+    }
+
+    SortOrder order;
+    DataType* type;
+    int64_t null_count;
+    size_t num_chunks;
+    std::vector<Array*> chunks;
+  };
+
+  class Comparer : public TypeVisitor {
+   public:
+    Comparer(const Table& table, const std::vector<SortKey>& sort_keys)
+        : TypeVisitor(), status_(Status::OK()) {
+      for (const auto& sort_key : sort_keys) {
+        const auto& chunked_array = table.GetColumnByName(sort_key.name);
+        if (!chunked_array) {
+          status_ = Status::Invalid("Nonexistent sort key column: ", sort_key.name);
+          return;
+        }
+        sort_keys_.emplace_back(*chunked_array, sort_key.order);
+      }
+    }
+
+    Status status() { return status_; }
+
+    const std::vector<ResolvedSortKey>& sort_keys() { return sort_keys_; }
+
+    bool Compare(uint64_t left, uint64_t right, size_t start_sort_key_index) {

Review comment:
       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.

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



[GitHub] [arrow] kou commented on a change in pull request #8612: ARROW-8199: [C++] Add support for multi-column sort indices on Table

Posted by GitBox <gi...@apache.org>.
kou commented on a change in pull request #8612:
URL: https://github.com/apache/arrow/pull/8612#discussion_r526612518



##########
File path: cpp/src/arrow/compute/kernels/vector_sort.cc
##########
@@ -346,14 +374,396 @@ void AddSortingKernels(VectorKernel base, VectorFunction* func) {
   }
 }
 
+class TableSorter : public TypeVisitor {
+ private:
+  struct ResolvedSortKey {
+    ResolvedSortKey(const ChunkedArray& chunked_array, const SortOrder order)
+        : order(order) {
+      type = chunked_array.type().get();
+      null_count = chunked_array.null_count();
+      num_chunks = chunked_array.num_chunks();
+      for (const auto& chunk : chunked_array.chunks()) {
+        chunks.push_back(chunk.get());
+      }
+    }
+
+    template <typename ArrayType>
+    ArrayType* ResolveChunk(int64_t index, int64_t& chunk_index) const {

Review comment:
       Added comments and changed to use new dedicated struct.




----------------------------------------------------------------
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.

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



[GitHub] [arrow] pitrou closed pull request #8612: ARROW-8199: [C++] Add support for multi-column sort indices on Table

Posted by GitBox <gi...@apache.org>.
pitrou closed pull request #8612:
URL: https://github.com/apache/arrow/pull/8612


   


----------------------------------------------------------------
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.

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



[GitHub] [arrow] kou commented on a change in pull request #8612: ARROW-8199: [C++] Add support for multi-column sort indices on Table

Posted by GitBox <gi...@apache.org>.
kou commented on a change in pull request #8612:
URL: https://github.com/apache/arrow/pull/8612#discussion_r526610856



##########
File path: cpp/src/arrow/compute/api_vector.h
##########
@@ -58,6 +58,34 @@ struct ARROW_EXPORT TakeOptions : public FunctionOptions {
   static TakeOptions Defaults() { return BoundsCheck(); }
 };
 
+enum SortOrder {
+  ASCENDING,
+  DESCENDING,
+};
+
+/// \brief One sort key for PartitionNthIndices (TODO) and SortIndices
+struct ARROW_EXPORT SortKey {
+  explicit SortKey(std::string name, SortOrder order = ASCENDING)
+      : name(name), order(order) {}
+
+  /// The name of the sort key.

Review comment:
       Thanks. Fixed.




----------------------------------------------------------------
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.

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



[GitHub] [arrow] pitrou commented on a change in pull request #8612: ARROW-8199: [C++] Add support for multi-column sort indices on Table

Posted by GitBox <gi...@apache.org>.
pitrou commented on a change in pull request #8612:
URL: https://github.com/apache/arrow/pull/8612#discussion_r521405090



##########
File path: cpp/src/arrow/compute/api_vector.h
##########
@@ -58,6 +58,34 @@ struct ARROW_EXPORT TakeOptions : public FunctionOptions {
   static TakeOptions Defaults() { return BoundsCheck(); }
 };
 
+enum SortOrder {

Review comment:
       Make this a `enum class`?

##########
File path: cpp/src/arrow/compute/api_vector.h
##########
@@ -58,6 +58,34 @@ struct ARROW_EXPORT TakeOptions : public FunctionOptions {
   static TakeOptions Defaults() { return BoundsCheck(); }
 };
 
+enum SortOrder {
+  ASCENDING,
+  DESCENDING,

Review comment:
       Nit, but sometimes all-uppercase values conflict with some C macros (especially on Windows). `Ascending` perhaps?

##########
File path: cpp/src/arrow/compute/api_vector.h
##########
@@ -165,8 +194,50 @@ Result<std::shared_ptr<Array>> NthToIndices(const Array& values, int64_t n,
 /// \param[in] ctx the function execution context, optional
 /// \return offsets indices that would sort an array
 ARROW_EXPORT
-Result<std::shared_ptr<Array>> SortToIndices(const Array& values,
-                                             ExecContext* ctx = NULLPTR);
+Result<std::shared_ptr<Array>> SortIndices(const Array& values,
+                                           ExecContext* ctx = NULLPTR);
+
+/// \brief Returns the indices that would sort an array in the
+/// specified order.
+///
+/// Perform an indirect sort of array. The output array will contain
+/// indices that would sort an array, which would be the same length
+/// as input. Nulls will be stably partitioned to the end of the output.

Review comment:
       Add "regardless of order"?

##########
File path: cpp/src/arrow/compute/kernels/vector_sort.cc
##########
@@ -346,14 +374,396 @@ void AddSortingKernels(VectorKernel base, VectorFunction* func) {
   }
 }
 
+class TableSorter : public TypeVisitor {
+ private:
+  struct ResolvedSortKey {
+    ResolvedSortKey(const ChunkedArray& chunked_array, const SortOrder order)
+        : order(order) {
+      type = chunked_array.type().get();
+      null_count = chunked_array.null_count();
+      num_chunks = chunked_array.num_chunks();
+      for (const auto& chunk : chunked_array.chunks()) {
+        chunks.push_back(chunk.get());
+      }
+    }
+
+    template <typename ArrayType>
+    ArrayType* ResolveChunk(int64_t index, int64_t& chunk_index) const {
+      if (num_chunks == 1) {
+        chunk_index = index;
+        return static_cast<ArrayType*>(chunks[0]);
+      } else {
+        int64_t offset = 0;
+        for (size_t i = 0; i < num_chunks; ++i) {
+          if (index < offset + chunks[i]->length()) {
+            chunk_index = index - offset;
+            return static_cast<ArrayType*>(chunks[i]);
+          }
+          offset += chunks[i]->length();
+        }
+        return nullptr;
+      }
+    }
+
+    SortOrder order;
+    DataType* type;
+    int64_t null_count;
+    size_t num_chunks;

Review comment:
       `int64_t`?

##########
File path: cpp/src/arrow/compute/kernels/vector_sort.cc
##########
@@ -346,14 +374,396 @@ void AddSortingKernels(VectorKernel base, VectorFunction* func) {
   }
 }
 
+class TableSorter : public TypeVisitor {
+ private:
+  struct ResolvedSortKey {
+    ResolvedSortKey(const ChunkedArray& chunked_array, const SortOrder order)
+        : order(order) {
+      type = chunked_array.type().get();
+      null_count = chunked_array.null_count();
+      num_chunks = chunked_array.num_chunks();
+      for (const auto& chunk : chunked_array.chunks()) {
+        chunks.push_back(chunk.get());
+      }
+    }
+
+    template <typename ArrayType>
+    ArrayType* ResolveChunk(int64_t index, int64_t& chunk_index) const {
+      if (num_chunks == 1) {
+        chunk_index = index;
+        return static_cast<ArrayType*>(chunks[0]);
+      } else {
+        int64_t offset = 0;
+        for (size_t i = 0; i < num_chunks; ++i) {
+          if (index < offset + chunks[i]->length()) {
+            chunk_index = index - offset;
+            return static_cast<ArrayType*>(chunks[i]);
+          }
+          offset += chunks[i]->length();
+        }
+        return nullptr;
+      }
+    }
+
+    SortOrder order;
+    DataType* type;
+    int64_t null_count;
+    size_t num_chunks;
+    std::vector<Array*> chunks;
+  };
+
+  class Comparer : public TypeVisitor {
+   public:
+    Comparer(const Table& table, const std::vector<SortKey>& sort_keys)
+        : TypeVisitor(), status_(Status::OK()) {
+      for (const auto& sort_key : sort_keys) {
+        const auto& chunked_array = table.GetColumnByName(sort_key.name);
+        if (!chunked_array) {
+          status_ = Status::Invalid("Nonexistent sort key column: ", sort_key.name);
+          return;
+        }
+        sort_keys_.emplace_back(*chunked_array, sort_key.order);
+      }
+    }
+
+    Status status() { return status_; }
+
+    const std::vector<ResolvedSortKey>& sort_keys() { return sort_keys_; }
+
+    bool Compare(uint64_t left, uint64_t right, size_t start_sort_key_index) {
+      current_left_ = left;
+      current_right_ = right;
+      current_compared_ = 0;
+      auto num_sort_keys = sort_keys_.size();
+      for (size_t i = start_sort_key_index; i < num_sort_keys; ++i) {
+        current_sort_key_index_ = i;
+        status_ = sort_keys_[i].type->Accept(this);
+        if (current_compared_ != 0) {
+          break;
+        }
+      }
+      return current_compared_ < 0;
+    }
+
+#define VISIT(TYPE)                                \
+  Status Visit(const TYPE##Type& type) override {  \
+    current_compared_ = CompareType<TYPE##Type>(); \
+    return Status::OK();                           \
+  }
+
+    VISIT(Int8)
+    VISIT(Int16)
+    VISIT(Int32)
+    VISIT(Int64)
+    VISIT(UInt8)
+    VISIT(UInt16)
+    VISIT(UInt32)
+    VISIT(UInt64)
+    VISIT(Float)
+    VISIT(Double)
+    VISIT(String)
+    VISIT(Binary)
+    VISIT(LargeString)
+    VISIT(LargeBinary)
+
+#undef VISIT
+
+   private:
+    template <typename Type>
+    int32_t CompareType() {
+      using ArrayType = typename TypeTraits<Type>::ArrayType;
+      const auto& sort_key = sort_keys_[current_sort_key_index_];
+      auto order = sort_key.order;
+      int64_t index_left = 0;
+      auto array_left = sort_key.ResolveChunk<ArrayType>(current_left_, index_left);
+      int64_t index_right = 0;
+      auto array_right = sort_key.ResolveChunk<ArrayType>(current_right_, index_right);
+      if (sort_key.null_count > 0) {
+        auto is_null_left = array_left->IsNull(index_left);
+        auto is_null_right = array_right->IsNull(index_right);
+        if (is_null_left && is_null_right) {
+          return 0;
+        } else if (is_null_left) {
+          return 1;
+        } else if (is_null_right) {
+          return -1;
+        }
+      }
+      auto left = array_left->GetView(index_left);
+      auto right = array_right->GetView(index_right);
+      int32_t compared;
+      if (left == right) {
+        compared = 0;
+      } else if (left > right) {
+        compared = 1;
+      } else {
+        compared = -1;
+      }
+      if (order == SortOrder::DESCENDING) {
+        compared = -compared;
+      }
+      return compared;
+    }
+
+    Status status_;
+    std::vector<ResolvedSortKey> sort_keys_;
+    int64_t current_left_;
+    int64_t current_right_;
+    size_t current_sort_key_index_;
+    int32_t current_compared_;
+  };
+
+ public:
+  TableSorter(uint64_t* indices_begin, uint64_t* indices_end, const Table& table,
+              const SortOptions& options)
+      : indices_begin_(indices_begin),
+        indices_end_(indices_end),
+        comparer_(table, options.sort_keys) {}
+
+  Status Sort() {
+    ARROW_RETURN_NOT_OK(comparer_.status());
+    return comparer_.sort_keys()[0].type->Accept(this);
+  }
+
+#define VISIT(TYPE) \
+  Status Visit(const TYPE##Type& type) override { return SortInternal<TYPE##Type>(); }
+
+  VISIT(Int8)
+  VISIT(Int16)
+  VISIT(Int32)
+  VISIT(Int64)
+  VISIT(UInt8)
+  VISIT(UInt16)
+  VISIT(UInt32)
+  VISIT(UInt64)
+  VISIT(Float)
+  VISIT(Double)
+  VISIT(String)
+  VISIT(Binary)
+  VISIT(LargeString)
+  VISIT(LargeBinary)
+
+#undef VISIT
+
+ private:
+  template <typename Type>
+  Status SortInternal() {
+    using ArrayType = typename TypeTraits<Type>::ArrayType;
+    std::iota(indices_begin_, indices_end_, 0);
+
+    auto& comparer = comparer_;
+    const auto& first_sort_key = comparer.sort_keys()[0];
+    auto nulls_begin = indices_end_;
+    nulls_begin = PartitionNullsInternal<Type>(first_sort_key);
+    std::stable_sort(
+        indices_begin_, nulls_begin,
+        [&first_sort_key, &comparer](uint64_t left, uint64_t right) {
+          int64_t index_left = 0;
+          auto array_left = first_sort_key.ResolveChunk<ArrayType>(left, index_left);
+          int64_t index_right = 0;
+          auto array_right = first_sort_key.ResolveChunk<ArrayType>(right, index_right);
+          auto value_left = array_left->GetView(index_left);
+          auto value_right = array_right->GetView(index_right);
+          if (value_left == value_right) {
+            return comparer.Compare(left, right, 1);
+          } else {
+            auto compared = value_left < value_right;
+            if (first_sort_key.order == SortOrder::ASCENDING) {
+              return compared;
+            } else {
+              return !compared;
+            }
+          }
+        });
+    return Status::OK();
+  }
+
+  template <typename Type>
+  enable_if_t<!is_floating_type<Type>::value, uint64_t*> PartitionNullsInternal(
+      const ResolvedSortKey& first_sort_key) {
+    using ArrayType = typename TypeTraits<Type>::ArrayType;
+    if (first_sort_key.null_count == 0) {
+      return indices_end_;
+    }
+    StablePartitioner partitioner;
+    auto nulls_begin =
+        partitioner(indices_begin_, indices_end_, [&first_sort_key](uint64_t index) {
+          int64_t index_chunk = 0;
+          auto chunk = first_sort_key.ResolveChunk<ArrayType>(index, index_chunk);
+          return !chunk->IsNull(index_chunk);
+        });
+    auto& comparer = comparer_;
+    std::stable_sort(nulls_begin, indices_end_,
+                     [&comparer](uint64_t left, uint64_t right) {
+                       return comparer.Compare(left, right, 1);
+                     });
+    return nulls_begin;
+  }
+
+  template <typename Type>
+  enable_if_t<is_floating_type<Type>::value, uint64_t*> PartitionNullsInternal(
+      const ResolvedSortKey& first_sort_key) {
+    using ArrayType = typename TypeTraits<Type>::ArrayType;
+    StablePartitioner partitioner;
+    if (first_sort_key.null_count == 0) {
+      return partitioner(indices_begin_, indices_end_, [&first_sort_key](uint64_t index) {
+        int64_t index_chunk = 0;
+        auto chunk = first_sort_key.ResolveChunk<ArrayType>(index, index_chunk);
+        return !std::isnan(chunk->GetView(index_chunk));
+      });
+    }
+    auto nans_and_nulls_begin =
+        partitioner(indices_begin_, indices_end_, [&first_sort_key](uint64_t index) {
+          int64_t index_chunk = 0;
+          auto chunk = first_sort_key.ResolveChunk<ArrayType>(index, index_chunk);
+          return !chunk->IsNull(index_chunk) && !std::isnan(chunk->GetView(index_chunk));
+        });
+    auto nulls_begin = nans_and_nulls_begin;
+    if (first_sort_key.null_count < static_cast<int64_t>(indices_end_ - nulls_begin)) {
+      // move Nulls after NaN
+      nulls_begin = partitioner(
+          nans_and_nulls_begin, indices_end_, [&first_sort_key](uint64_t index) {
+            int64_t index_chunk = 0;
+            auto chunk = first_sort_key.ResolveChunk<ArrayType>(index, index_chunk);
+            return !chunk->IsNull(index_chunk);
+          });
+    }
+    auto& comparer = comparer_;
+    if (nans_and_nulls_begin != nulls_begin) {
+      std::stable_sort(nans_and_nulls_begin, nulls_begin,
+                       [&comparer](uint64_t left, uint64_t right) {
+                         return comparer.Compare(left, right, 1);
+                       });
+    }
+    std::stable_sort(nulls_begin, indices_end_,
+                     [&comparer](uint64_t left, uint64_t right) {
+                       return comparer.Compare(left, right, 1);
+                     });
+    return nans_and_nulls_begin;
+  }
+
+  uint64_t* indices_begin_;
+  uint64_t* indices_end_;
+  Comparer comparer_;
+};
+
 const FunctionDoc sort_indices_doc(
+    "Return the indices that would sort an array, record batch or table",
+    ("This function computes an array of indices that define a stable sort\n"
+     "of the input array, record batch or table.  Null values are considered\n"
+     "greater than any other value and are therefore sorted at the end of the\n"
+     "input. For floating-point types, NaNs are considered greater than any\n"
+     "other non-null value, but smaller than null values."),
+    {"input"}, "SortOptions");
+
+class SortIndicesMetaFunction : public MetaFunction {
+ public:
+  SortIndicesMetaFunction()
+      : MetaFunction("sort_indices", Arity::Unary(), &sort_indices_doc) {}
+
+  Result<Datum> ExecuteImpl(const std::vector<Datum>& args,
+                            const FunctionOptions* options,
+                            ExecContext* ctx) const override {
+    const SortOptions& sort_options = static_cast<const SortOptions&>(*options);
+    switch (args[0].kind()) {
+      case Datum::ARRAY:
+        return SortIndices(*args[0].make_array(), sort_options, ctx);
+        break;
+      case Datum::CHUNKED_ARRAY:
+        return SortIndices(*args[0].chunked_array(), sort_options, ctx);
+        break;
+      case Datum::RECORD_BATCH: {
+        ARROW_ASSIGN_OR_RAISE(auto table,
+                              Table::FromRecordBatches({args[0].record_batch()}));
+        return SortIndices(*table, sort_options, ctx);
+      } break;
+      case Datum::TABLE:
+        return SortIndices(*args[0].table(), sort_options, ctx);
+        break;
+      default:
+        break;
+    }
+    return Status::NotImplemented(
+        "Unsupported types for sort_indices operation: "
+        "values=",
+        args[0].ToString());
+  }
+
+ private:
+  Result<std::shared_ptr<Array>> SortIndices(const Array& values,
+                                             const SortOptions& options,
+                                             ExecContext* ctx) const {
+    SortOrder order = SortOrder::ASCENDING;
+    if (!options.sort_keys.empty()) {
+      order = options.sort_keys[0].order;
+    }
+    ArraySortOptions array_options(order);
+    ARROW_ASSIGN_OR_RAISE(
+        Datum result, CallFunction("array_sort_indices", {values}, &array_options, ctx));
+    return result.make_array();
+  }
+
+  Result<std::shared_ptr<Array>> SortIndices(const ChunkedArray& values,
+                                             const SortOptions& options,
+                                             ExecContext* ctx) const {
+    SortOrder order = SortOrder::ASCENDING;
+    if (!options.sort_keys.empty()) {
+      order = options.sort_keys[0].order;
+    }
+    ArraySortOptions array_options(order);
+
+    std::shared_ptr<Array> array_values;
+    if (values.num_chunks() == 1) {
+      array_values = values.chunk(0);
+    } else {
+      ARROW_ASSIGN_OR_RAISE(array_values,
+                            Concatenate(values.chunks(), ctx->memory_pool()));

Review comment:
       This is weird. Why are you concatenating chunks for the ChunkedArray case but not for the Table case? I would expect both cases to be handled similarly (regardless of the solution).

##########
File path: cpp/src/arrow/compute/kernels/vector_sort.cc
##########
@@ -346,14 +374,396 @@ void AddSortingKernels(VectorKernel base, VectorFunction* func) {
   }
 }
 
+class TableSorter : public TypeVisitor {
+ private:
+  struct ResolvedSortKey {
+    ResolvedSortKey(const ChunkedArray& chunked_array, const SortOrder order)
+        : order(order) {
+      type = chunked_array.type().get();
+      null_count = chunked_array.null_count();
+      num_chunks = chunked_array.num_chunks();
+      for (const auto& chunk : chunked_array.chunks()) {
+        chunks.push_back(chunk.get());
+      }
+    }
+
+    template <typename ArrayType>
+    ArrayType* ResolveChunk(int64_t index, int64_t& chunk_index) const {
+      if (num_chunks == 1) {
+        chunk_index = index;
+        return static_cast<ArrayType*>(chunks[0]);
+      } else {
+        int64_t offset = 0;
+        for (size_t i = 0; i < num_chunks; ++i) {
+          if (index < offset + chunks[i]->length()) {
+            chunk_index = index - offset;
+            return static_cast<ArrayType*>(chunks[i]);
+          }
+          offset += chunks[i]->length();
+        }
+        return nullptr;
+      }
+    }
+
+    SortOrder order;
+    DataType* type;
+    int64_t null_count;
+    size_t num_chunks;
+    std::vector<Array*> chunks;
+  };
+
+  class Comparer : public TypeVisitor {
+   public:
+    Comparer(const Table& table, const std::vector<SortKey>& sort_keys)
+        : TypeVisitor(), status_(Status::OK()) {
+      for (const auto& sort_key : sort_keys) {
+        const auto& chunked_array = table.GetColumnByName(sort_key.name);
+        if (!chunked_array) {
+          status_ = Status::Invalid("Nonexistent sort key column: ", sort_key.name);
+          return;
+        }
+        sort_keys_.emplace_back(*chunked_array, sort_key.order);
+      }
+    }
+
+    Status status() { return status_; }
+
+    const std::vector<ResolvedSortKey>& sort_keys() { return sort_keys_; }
+
+    bool Compare(uint64_t left, uint64_t right, size_t start_sort_key_index) {
+      current_left_ = left;
+      current_right_ = right;
+      current_compared_ = 0;
+      auto num_sort_keys = sort_keys_.size();
+      for (size_t i = start_sort_key_index; i < num_sort_keys; ++i) {
+        current_sort_key_index_ = i;
+        status_ = sort_keys_[i].type->Accept(this);
+        if (current_compared_ != 0) {
+          break;
+        }
+      }
+      return current_compared_ < 0;
+    }
+
+#define VISIT(TYPE)                                \
+  Status Visit(const TYPE##Type& type) override {  \
+    current_compared_ = CompareType<TYPE##Type>(); \
+    return Status::OK();                           \
+  }
+
+    VISIT(Int8)
+    VISIT(Int16)
+    VISIT(Int32)
+    VISIT(Int64)
+    VISIT(UInt8)
+    VISIT(UInt16)
+    VISIT(UInt32)
+    VISIT(UInt64)
+    VISIT(Float)
+    VISIT(Double)
+    VISIT(String)
+    VISIT(Binary)
+    VISIT(LargeString)
+    VISIT(LargeBinary)
+
+#undef VISIT
+
+   private:
+    template <typename Type>
+    int32_t CompareType() {
+      using ArrayType = typename TypeTraits<Type>::ArrayType;
+      const auto& sort_key = sort_keys_[current_sort_key_index_];
+      auto order = sort_key.order;
+      int64_t index_left = 0;
+      auto array_left = sort_key.ResolveChunk<ArrayType>(current_left_, index_left);
+      int64_t index_right = 0;
+      auto array_right = sort_key.ResolveChunk<ArrayType>(current_right_, index_right);
+      if (sort_key.null_count > 0) {
+        auto is_null_left = array_left->IsNull(index_left);
+        auto is_null_right = array_right->IsNull(index_right);
+        if (is_null_left && is_null_right) {
+          return 0;
+        } else if (is_null_left) {
+          return 1;
+        } else if (is_null_right) {
+          return -1;
+        }
+      }
+      auto left = array_left->GetView(index_left);
+      auto right = array_right->GetView(index_right);
+      int32_t compared;
+      if (left == right) {
+        compared = 0;
+      } else if (left > right) {
+        compared = 1;
+      } else {
+        compared = -1;
+      }
+      if (order == SortOrder::DESCENDING) {
+        compared = -compared;
+      }
+      return compared;
+    }
+
+    Status status_;
+    std::vector<ResolvedSortKey> sort_keys_;
+    int64_t current_left_;
+    int64_t current_right_;
+    size_t current_sort_key_index_;
+    int32_t current_compared_;
+  };
+
+ public:
+  TableSorter(uint64_t* indices_begin, uint64_t* indices_end, const Table& table,
+              const SortOptions& options)
+      : indices_begin_(indices_begin),
+        indices_end_(indices_end),
+        comparer_(table, options.sort_keys) {}
+
+  Status Sort() {
+    ARROW_RETURN_NOT_OK(comparer_.status());
+    return comparer_.sort_keys()[0].type->Accept(this);
+  }
+
+#define VISIT(TYPE) \
+  Status Visit(const TYPE##Type& type) override { return SortInternal<TYPE##Type>(); }
+
+  VISIT(Int8)
+  VISIT(Int16)
+  VISIT(Int32)
+  VISIT(Int64)
+  VISIT(UInt8)
+  VISIT(UInt16)
+  VISIT(UInt32)
+  VISIT(UInt64)
+  VISIT(Float)
+  VISIT(Double)
+  VISIT(String)
+  VISIT(Binary)
+  VISIT(LargeString)
+  VISIT(LargeBinary)
+
+#undef VISIT
+
+ private:
+  template <typename Type>
+  Status SortInternal() {

Review comment:
       Can you add comments when you define a non-trivial class or method?

##########
File path: cpp/src/arrow/compute/api_vector.h
##########
@@ -58,6 +58,34 @@ struct ARROW_EXPORT TakeOptions : public FunctionOptions {
   static TakeOptions Defaults() { return BoundsCheck(); }
 };
 
+enum SortOrder {
+  ASCENDING,
+  DESCENDING,
+};
+
+/// \brief One sort key for PartitionNthIndices (TODO) and SortIndices
+struct ARROW_EXPORT SortKey {
+  explicit SortKey(std::string name, SortOrder order = ASCENDING)
+      : name(name), order(order) {}
+
+  /// The name of the sort key.
+  std::string name;
+  /// How to order by this sort key.
+  SortOrder order;
+};
+
+struct ARROW_EXPORT ArraySortOptions : public FunctionOptions {
+  explicit ArraySortOptions(SortOrder order = SortOrder::ASCENDING) : order(order) {}
+
+  SortOrder order;
+};
+
+struct ARROW_EXPORT SortOptions : public FunctionOptions {

Review comment:
       Perhaps name this "TableSortOptions"?

##########
File path: cpp/src/arrow/compute/api_vector.h
##########
@@ -58,6 +58,34 @@ struct ARROW_EXPORT TakeOptions : public FunctionOptions {
   static TakeOptions Defaults() { return BoundsCheck(); }
 };
 
+enum SortOrder {
+  ASCENDING,
+  DESCENDING,
+};
+
+/// \brief One sort key for PartitionNthIndices (TODO) and SortIndices
+struct ARROW_EXPORT SortKey {
+  explicit SortKey(std::string name, SortOrder order = ASCENDING)
+      : name(name), order(order) {}
+
+  /// The name of the sort key.

Review comment:
       You mean sort column?

##########
File path: cpp/src/arrow/compute/api_vector.h
##########
@@ -165,8 +194,50 @@ Result<std::shared_ptr<Array>> NthToIndices(const Array& values, int64_t n,
 /// \param[in] ctx the function execution context, optional
 /// \return offsets indices that would sort an array
 ARROW_EXPORT
-Result<std::shared_ptr<Array>> SortToIndices(const Array& values,
-                                             ExecContext* ctx = NULLPTR);
+Result<std::shared_ptr<Array>> SortIndices(const Array& values,
+                                           ExecContext* ctx = NULLPTR);
+
+/// \brief Returns the indices that would sort an array in the
+/// specified order.
+///
+/// Perform an indirect sort of array. The output array will contain
+/// indices that would sort an array, which would be the same length
+/// as input. Nulls will be stably partitioned to the end of the output.
+///
+/// For example given values = [null, 1, 3.3, null, 2, 5.3] and order
+/// = SortOrder::DESCENDING, the output will be [5, 2, 4, 1, 0,
+/// 3].
+///
+/// \param[in] values array to sort
+/// \param[in] order ascending or descending
+/// \param[in] ctx the function execution context, optional
+/// \return offsets indices that would sort an array
+ARROW_EXPORT
+Result<std::shared_ptr<Array>> SortIndices(const Array& values, SortOrder order,

Review comment:
       Why not `order = SortOrder::Ascending`? This would avoid declaring two separate overloads.

##########
File path: cpp/src/arrow/compute/kernels/vector_sort.cc
##########
@@ -346,14 +374,396 @@ void AddSortingKernels(VectorKernel base, VectorFunction* func) {
   }
 }
 
+class TableSorter : public TypeVisitor {
+ private:
+  struct ResolvedSortKey {
+    ResolvedSortKey(const ChunkedArray& chunked_array, const SortOrder order)
+        : order(order) {
+      type = chunked_array.type().get();
+      null_count = chunked_array.null_count();
+      num_chunks = chunked_array.num_chunks();
+      for (const auto& chunk : chunked_array.chunks()) {
+        chunks.push_back(chunk.get());
+      }
+    }
+
+    template <typename ArrayType>
+    ArrayType* ResolveChunk(int64_t index, int64_t& chunk_index) const {

Review comment:
       Can you add a comment describing what this method does?

##########
File path: cpp/src/arrow/compute/kernels/vector_sort.cc
##########
@@ -346,14 +374,396 @@ void AddSortingKernels(VectorKernel base, VectorFunction* func) {
   }
 }
 
+class TableSorter : public TypeVisitor {
+ private:
+  struct ResolvedSortKey {
+    ResolvedSortKey(const ChunkedArray& chunked_array, const SortOrder order)
+        : order(order) {
+      type = chunked_array.type().get();
+      null_count = chunked_array.null_count();
+      num_chunks = chunked_array.num_chunks();
+      for (const auto& chunk : chunked_array.chunks()) {
+        chunks.push_back(chunk.get());
+      }
+    }
+
+    template <typename ArrayType>
+    ArrayType* ResolveChunk(int64_t index, int64_t& chunk_index) const {
+      if (num_chunks == 1) {
+        chunk_index = index;
+        return static_cast<ArrayType*>(chunks[0]);
+      } else {
+        int64_t offset = 0;
+        for (size_t i = 0; i < num_chunks; ++i) {
+          if (index < offset + chunks[i]->length()) {
+            chunk_index = index - offset;
+            return static_cast<ArrayType*>(chunks[i]);
+          }
+          offset += chunks[i]->length();
+        }
+        return nullptr;
+      }
+    }
+
+    SortOrder order;
+    DataType* type;
+    int64_t null_count;
+    size_t num_chunks;
+    std::vector<Array*> chunks;
+  };
+
+  class Comparer : public TypeVisitor {
+   public:
+    Comparer(const Table& table, const std::vector<SortKey>& sort_keys)
+        : TypeVisitor(), status_(Status::OK()) {
+      for (const auto& sort_key : sort_keys) {
+        const auto& chunked_array = table.GetColumnByName(sort_key.name);
+        if (!chunked_array) {
+          status_ = Status::Invalid("Nonexistent sort key column: ", sort_key.name);
+          return;
+        }
+        sort_keys_.emplace_back(*chunked_array, sort_key.order);
+      }
+    }
+
+    Status status() { return status_; }
+
+    const std::vector<ResolvedSortKey>& sort_keys() { return sort_keys_; }
+
+    bool Compare(uint64_t left, uint64_t right, size_t start_sort_key_index) {

Review comment:
       Add a comment?

##########
File path: cpp/src/arrow/compute/kernels/vector_sort_test.cc
##########
@@ -364,32 +400,264 @@ TYPED_TEST(TestSortToIndicesKernelRandomCount, SortRandomValuesCount) {
   int range = 2000;
   for (int test = 0; test < times; test++) {
     for (auto null_probability : {0.0, 0.1, 0.5, 1.0}) {
-      auto array = rand.Generate(length, range, null_probability);
-      ASSERT_OK_AND_ASSIGN(std::shared_ptr<Array> offsets, SortToIndices(*array));
-      ValidateSorted<ArrayType>(*checked_pointer_cast<ArrayType>(array),
-                                *checked_pointer_cast<UInt64Array>(offsets));
+      for (auto order : {SortOrder::ASCENDING, SortOrder::DESCENDING}) {
+        auto array = rand.Generate(length, range, null_probability);
+        ASSERT_OK_AND_ASSIGN(std::shared_ptr<Array> offsets, SortIndices(*array, order));
+        ValidateSorted<ArrayType>(*checked_pointer_cast<ArrayType>(array),
+                                  *checked_pointer_cast<UInt64Array>(offsets), order);
+      }
     }
   }
 }
 
 // Long array with big value range: std::stable_sort
-TYPED_TEST_SUITE(TestSortToIndicesKernelRandomCompare, IntegralArrowTypes);
+TYPED_TEST_SUITE(TestArraySortIndicesKernelRandomCompare, IntegralArrowTypes);
 
-TYPED_TEST(TestSortToIndicesKernelRandomCompare, SortRandomValuesCompare) {
+TYPED_TEST(TestArraySortIndicesKernelRandomCompare, SortRandomValuesCompare) {
   using ArrayType = typename TypeTraits<TypeParam>::ArrayType;
 
   Random<TypeParam> rand(0x5487657);
   int times = 5;
   int length = 4000;
   for (int test = 0; test < times; test++) {
     for (auto null_probability : {0.0, 0.1, 0.5, 1.0}) {
-      auto array = rand.Generate(length, null_probability);
-      ASSERT_OK_AND_ASSIGN(std::shared_ptr<Array> offsets, SortToIndices(*array));
-      ValidateSorted<ArrayType>(*checked_pointer_cast<ArrayType>(array),
-                                *checked_pointer_cast<UInt64Array>(offsets));
+      for (auto order : {SortOrder::ASCENDING, SortOrder::DESCENDING}) {
+        auto array = rand.Generate(length, null_probability);
+        ASSERT_OK_AND_ASSIGN(std::shared_ptr<Array> offsets, SortIndices(*array, order));
+        ValidateSorted<ArrayType>(*checked_pointer_cast<ArrayType>(array),
+                                  *checked_pointer_cast<UInt64Array>(offsets), order);
+      }
     }
   }
 }
 
+class TestTableSortIndices : public ::testing::Test {
+ protected:
+  void AssertSortIndices(const std::shared_ptr<Table> table, const SortOptions& options,
+                         const std::shared_ptr<Array> expected) {
+    ASSERT_OK_AND_ASSIGN(auto actual, SortIndices(*table, options));
+    AssertArraysEqual(*expected, *actual);
+  }
+
+  void AssertSortIndices(const std::shared_ptr<Table> table, const SortOptions& options,
+                         const std::string expected) {
+    AssertSortIndices(table, options, ArrayFromJSON(uint64(), expected));
+  }
+};
+
+TEST_F(TestTableSortIndices, SortNull) {
+  auto table = TableFromJSON(schema({
+                                 {field("a", uint8())},
+                                 {field("b", uint8())},
+                             }),
+                             {"["
+                              "{\"a\": null, \"b\": 5},"
+                              "{\"a\": 1,    \"b\": 3},"
+                              "{\"a\": 3,    \"b\": null},"
+                              "{\"a\": null, \"b\": null},"
+                              "{\"a\": 2,    \"b\": 5},"
+                              "{\"a\": 1,    \"b\": 5}"
+                              "]"});
+  SortOptions options(
+      {SortKey("a", SortOrder::ASCENDING), SortKey("b", SortOrder::DESCENDING)});
+  this->AssertSortIndices(table, options, "[5, 1, 4, 2, 0, 3]");
+}
+
+TEST_F(TestTableSortIndices, SortNaN) {
+  auto table = TableFromJSON(schema({
+                                 {field("a", float32())},
+                                 {field("b", float32())},
+                             }),
+                             {"["
+                              "{\"a\": null, \"b\": 5},"
+                              "{\"a\": 1,    \"b\": 3},"
+                              "{\"a\": 3,    \"b\": null},"
+                              "{\"a\": null, \"b\": null},"
+                              "{\"a\": NaN,  \"b\": null},"
+                              "{\"a\": NaN,  \"b\": 5},"
+                              "{\"a\": NaN,  \"b\": NaN},"
+                              "{\"a\": 1,    \"b\": 5}"
+                              "]"});
+  SortOptions options(
+      {SortKey("a", SortOrder::ASCENDING), SortKey("b", SortOrder::DESCENDING)});
+  this->AssertSortIndices(table, options, "[7, 1, 2, 5, 6, 4, 0, 3]");
+}
+
+using RandomParam = std::tuple<std::string, double>;
+class TestTableSortIndicesRandom : public testing::TestWithParam<RandomParam> {
+  class Comparator : public TypeVisitor {
+   public:
+    bool operator()(const Table& table, const SortOptions& options, uint64_t lhs,
+                    uint64_t rhs) {
+      lhs_ = lhs;
+      rhs_ = rhs;
+      for (const auto& sort_key : options.sort_keys) {
+        auto chunked_array = table.GetColumnByName(sort_key.name);
+        lhs_array_ = findTargetArray(chunked_array, lhs, lhs_index_);
+        rhs_array_ = findTargetArray(chunked_array, rhs, rhs_index_);
+        if (rhs_array_->IsNull(rhs_index_) && lhs_array_->IsNull(lhs_index_)) continue;
+        if (rhs_array_->IsNull(rhs_index_)) return true;
+        if (lhs_array_->IsNull(lhs_index_)) return false;
+        status_ = lhs_array_->type()->Accept(this);
+        if (compared_ == 0) continue;
+        if (sort_key.order == SortOrder::ASCENDING) {
+          return compared_ < 0;
+        } else {
+          return compared_ > 0;
+        }
+      }
+      return lhs < rhs;
+    }
+
+    Status status() const { return status_; }
+
+#define VISIT(TYPE)                               \
+  Status Visit(const TYPE##Type& type) override { \
+    compared_ = CompareType<TYPE##Type>();        \
+    return Status::OK();                          \
+  }
+
+    VISIT(Int8)
+    VISIT(Int16)
+    VISIT(Int32)
+    VISIT(Int64)
+    VISIT(UInt8)
+    VISIT(UInt16)
+    VISIT(UInt32)
+    VISIT(UInt64)
+    VISIT(Float)
+    VISIT(Double)
+    VISIT(String)
+
+#undef VISIT
+
+   private:
+    std::shared_ptr<Array> findTargetArray(std::shared_ptr<ChunkedArray> chunked_array,

Review comment:
       I would expect `const Array* FindTargetArray(const ChunkedArray&, int64_t index, int64_t* chunk_index)`

##########
File path: cpp/src/arrow/compute/kernels/vector_sort.cc
##########
@@ -346,14 +374,396 @@ void AddSortingKernels(VectorKernel base, VectorFunction* func) {
   }
 }
 
+class TableSorter : public TypeVisitor {
+ private:
+  struct ResolvedSortKey {
+    ResolvedSortKey(const ChunkedArray& chunked_array, const SortOrder order)
+        : order(order) {
+      type = chunked_array.type().get();
+      null_count = chunked_array.null_count();
+      num_chunks = chunked_array.num_chunks();
+      for (const auto& chunk : chunked_array.chunks()) {
+        chunks.push_back(chunk.get());
+      }
+    }
+
+    template <typename ArrayType>
+    ArrayType* ResolveChunk(int64_t index, int64_t& chunk_index) const {
+      if (num_chunks == 1) {
+        chunk_index = index;
+        return static_cast<ArrayType*>(chunks[0]);
+      } else {
+        int64_t offset = 0;
+        for (size_t i = 0; i < num_chunks; ++i) {
+          if (index < offset + chunks[i]->length()) {
+            chunk_index = index - offset;
+            return static_cast<ArrayType*>(chunks[i]);
+          }
+          offset += chunks[i]->length();
+        }
+        return nullptr;
+      }
+    }
+
+    SortOrder order;
+    DataType* type;
+    int64_t null_count;
+    size_t num_chunks;
+    std::vector<Array*> chunks;
+  };
+
+  class Comparer : public TypeVisitor {
+   public:
+    Comparer(const Table& table, const std::vector<SortKey>& sort_keys)
+        : TypeVisitor(), status_(Status::OK()) {
+      for (const auto& sort_key : sort_keys) {
+        const auto& chunked_array = table.GetColumnByName(sort_key.name);
+        if (!chunked_array) {
+          status_ = Status::Invalid("Nonexistent sort key column: ", sort_key.name);
+          return;
+        }
+        sort_keys_.emplace_back(*chunked_array, sort_key.order);
+      }
+    }
+
+    Status status() { return status_; }
+
+    const std::vector<ResolvedSortKey>& sort_keys() { return sort_keys_; }
+
+    bool Compare(uint64_t left, uint64_t right, size_t start_sort_key_index) {
+      current_left_ = left;
+      current_right_ = right;
+      current_compared_ = 0;
+      auto num_sort_keys = sort_keys_.size();
+      for (size_t i = start_sort_key_index; i < num_sort_keys; ++i) {
+        current_sort_key_index_ = i;
+        status_ = sort_keys_[i].type->Accept(this);
+        if (current_compared_ != 0) {
+          break;
+        }
+      }
+      return current_compared_ < 0;
+    }
+
+#define VISIT(TYPE)                                \
+  Status Visit(const TYPE##Type& type) override {  \
+    current_compared_ = CompareType<TYPE##Type>(); \
+    return Status::OK();                           \
+  }
+
+    VISIT(Int8)
+    VISIT(Int16)
+    VISIT(Int32)
+    VISIT(Int64)
+    VISIT(UInt8)
+    VISIT(UInt16)
+    VISIT(UInt32)
+    VISIT(UInt64)
+    VISIT(Float)
+    VISIT(Double)
+    VISIT(String)
+    VISIT(Binary)
+    VISIT(LargeString)
+    VISIT(LargeBinary)
+
+#undef VISIT
+
+   private:
+    template <typename Type>
+    int32_t CompareType() {
+      using ArrayType = typename TypeTraits<Type>::ArrayType;
+      const auto& sort_key = sort_keys_[current_sort_key_index_];
+      auto order = sort_key.order;
+      int64_t index_left = 0;
+      auto array_left = sort_key.ResolveChunk<ArrayType>(current_left_, index_left);
+      int64_t index_right = 0;
+      auto array_right = sort_key.ResolveChunk<ArrayType>(current_right_, index_right);
+      if (sort_key.null_count > 0) {
+        auto is_null_left = array_left->IsNull(index_left);
+        auto is_null_right = array_right->IsNull(index_right);
+        if (is_null_left && is_null_right) {
+          return 0;
+        } else if (is_null_left) {
+          return 1;
+        } else if (is_null_right) {
+          return -1;
+        }
+      }
+      auto left = array_left->GetView(index_left);
+      auto right = array_right->GetView(index_right);
+      int32_t compared;
+      if (left == right) {
+        compared = 0;
+      } else if (left > right) {
+        compared = 1;
+      } else {
+        compared = -1;
+      }
+      if (order == SortOrder::DESCENDING) {
+        compared = -compared;
+      }
+      return compared;
+    }
+
+    Status status_;
+    std::vector<ResolvedSortKey> sort_keys_;
+    int64_t current_left_;
+    int64_t current_right_;
+    size_t current_sort_key_index_;
+    int32_t current_compared_;
+  };
+
+ public:
+  TableSorter(uint64_t* indices_begin, uint64_t* indices_end, const Table& table,
+              const SortOptions& options)
+      : indices_begin_(indices_begin),
+        indices_end_(indices_end),
+        comparer_(table, options.sort_keys) {}
+
+  Status Sort() {
+    ARROW_RETURN_NOT_OK(comparer_.status());
+    return comparer_.sort_keys()[0].type->Accept(this);
+  }
+
+#define VISIT(TYPE) \
+  Status Visit(const TYPE##Type& type) override { return SortInternal<TYPE##Type>(); }
+
+  VISIT(Int8)
+  VISIT(Int16)
+  VISIT(Int32)
+  VISIT(Int64)
+  VISIT(UInt8)
+  VISIT(UInt16)
+  VISIT(UInt32)
+  VISIT(UInt64)
+  VISIT(Float)
+  VISIT(Double)
+  VISIT(String)
+  VISIT(Binary)
+  VISIT(LargeString)
+  VISIT(LargeBinary)
+
+#undef VISIT
+
+ private:
+  template <typename Type>
+  Status SortInternal() {
+    using ArrayType = typename TypeTraits<Type>::ArrayType;
+    std::iota(indices_begin_, indices_end_, 0);
+
+    auto& comparer = comparer_;
+    const auto& first_sort_key = comparer.sort_keys()[0];
+    auto nulls_begin = indices_end_;
+    nulls_begin = PartitionNullsInternal<Type>(first_sort_key);
+    std::stable_sort(
+        indices_begin_, nulls_begin,
+        [&first_sort_key, &comparer](uint64_t left, uint64_t right) {
+          int64_t index_left = 0;
+          auto array_left = first_sort_key.ResolveChunk<ArrayType>(left, index_left);
+          int64_t index_right = 0;
+          auto array_right = first_sort_key.ResolveChunk<ArrayType>(right, index_right);
+          auto value_left = array_left->GetView(index_left);
+          auto value_right = array_right->GetView(index_right);
+          if (value_left == value_right) {
+            return comparer.Compare(left, right, 1);

Review comment:
       Performance will probably be very bad if there are lots of equal values in the first column, right?

##########
File path: cpp/src/arrow/compute/kernels/vector_sort_test.cc
##########
@@ -228,134 +233,165 @@ TYPED_TEST(TestNthToIndicesRandom, RandomValues) {
 using arrow::internal::checked_pointer_cast;
 
 template <typename ArrowType>
-class TestSortToIndicesKernel : public TestBase {
+class TestArraySortIndicesKernel : public TestBase {
  private:
-  void AssertSortToIndicesArrays(const std::shared_ptr<Array> values,
-                                 const std::shared_ptr<Array> expected) {
-    ASSERT_OK_AND_ASSIGN(std::shared_ptr<Array> actual, SortToIndices(*values));
+  void AssertArraysSortIndices(const std::shared_ptr<Array> values, SortOrder order,
+                               const std::shared_ptr<Array> expected) {
+    ASSERT_OK_AND_ASSIGN(std::shared_ptr<Array> actual, SortIndices(*values, order));
     ASSERT_OK(actual->ValidateFull());
     AssertArraysEqual(*expected, *actual);
   }
 
  protected:
-  virtual void AssertSortToIndices(const std::string& values,
-                                   const std::string& expected) {
+  virtual void AssertSortIndices(const std::string& values, SortOrder order,
+                                 const std::string& expected) {
     auto type = TypeTraits<ArrowType>::type_singleton();
-    AssertSortToIndicesArrays(ArrayFromJSON(type, values),
-                              ArrayFromJSON(uint64(), expected));
+    AssertArraysSortIndices(ArrayFromJSON(type, values), order,
+                            ArrayFromJSON(uint64(), expected));
+  }
+
+  virtual void AssertSortIndices(const std::string& values, const std::string& expected) {
+    AssertSortIndices(values, SortOrder::ASCENDING, expected);
   }
 };
 
 template <typename ArrowType>
-class TestSortToIndicesKernelForReal : public TestSortToIndicesKernel<ArrowType> {};
-TYPED_TEST_SUITE(TestSortToIndicesKernelForReal, RealArrowTypes);
+class TestArraySortIndicesKernelForReal : public TestArraySortIndicesKernel<ArrowType> {};
+TYPED_TEST_SUITE(TestArraySortIndicesKernelForReal, RealArrowTypes);
 
 template <typename ArrowType>
-class TestSortToIndicesKernelForIntegral : public TestSortToIndicesKernel<ArrowType> {};
-TYPED_TEST_SUITE(TestSortToIndicesKernelForIntegral, IntegralArrowTypes);
+class TestArraySortIndicesKernelForIntegral
+    : public TestArraySortIndicesKernel<ArrowType> {};
+TYPED_TEST_SUITE(TestArraySortIndicesKernelForIntegral, IntegralArrowTypes);
 
 template <typename ArrowType>
-class TestSortToIndicesKernelForStrings : public TestSortToIndicesKernel<ArrowType> {};
-TYPED_TEST_SUITE(TestSortToIndicesKernelForStrings, testing::Types<StringType>);
+class TestArraySortIndicesKernelForStrings
+    : public TestArraySortIndicesKernel<ArrowType> {};
+TYPED_TEST_SUITE(TestArraySortIndicesKernelForStrings, testing::Types<StringType>);
+
+TYPED_TEST(TestArraySortIndicesKernelForReal, SortReal) {
+  this->AssertSortIndices("[]", "[]");
+
+  this->AssertSortIndices("[3.4, 2.6, 6.3]", "[1, 0, 2]");
+  this->AssertSortIndices("[1.1, 2.4, 3.5, 4.3, 5.1, 6.8, 7.3]", "[0,1,2,3,4,5,6]");

Review comment:
       Nit, but can you always use the same convention for spacing JSON values?

##########
File path: cpp/src/arrow/compute/kernels/vector_sort_benchmark.cc
##########
@@ -56,17 +57,99 @@ static void SortToIndicesInt64Compare(benchmark::State& state) {
   auto max = std::numeric_limits<int64_t>::max();
   auto values = rand.Int64(array_size, min, max, args.null_proportion);
 
-  SortToIndicesBenchmark(state, values);
+  ArraySortIndicesBenchmark(state, values);
 }
 
-BENCHMARK(SortToIndicesInt64Count)
+static void TableSortIndicesBenchmark(benchmark::State& state,
+                                      const std::shared_ptr<Table>& table,
+                                      const SortOptions& options) {
+  for (auto _ : state) {
+    ABORT_NOT_OK(SortIndices(*table, options).status());
+  }
+  state.SetItemsProcessed(state.iterations() * table->num_rows());
+}
+
+static void TableSortIndicesInt64Count(benchmark::State& state) {
+  RegressionArgs args(state);
+
+  const int64_t array_size = args.size / sizeof(int64_t);
+  auto rand = random::RandomArrayGenerator(kSeed);
+  auto values = rand.Int64(array_size, -100, 100, args.null_proportion);
+  std::vector<std::shared_ptr<Field>> fields = {{field("int64", int64())}};
+  auto table = Table::Make(schema(fields), {values}, array_size);
+  SortOptions options({SortKey("int64", SortOrder::ASCENDING)});
+
+  TableSortIndicesBenchmark(state, table, options);
+}
+
+static void TableSortIndicesInt64Compare(benchmark::State& state) {
+  RegressionArgs args(state);
+
+  const int64_t array_size = args.size / sizeof(int64_t);
+  auto rand = random::RandomArrayGenerator(kSeed);
+
+  auto min = std::numeric_limits<int64_t>::min();
+  auto max = std::numeric_limits<int64_t>::max();
+  auto values = rand.Int64(array_size, min, max, args.null_proportion);
+  std::vector<std::shared_ptr<Field>> fields = {{field("int64", int64())}};
+  auto table = Table::Make(schema(fields), {values}, array_size);
+  SortOptions options({SortKey("int64", SortOrder::ASCENDING)});
+
+  TableSortIndicesBenchmark(state, table, options);
+}
+
+static void TableSortIndicesInt64Int64(benchmark::State& state) {
+  RegressionArgs args(state);
+
+  const int64_t array_size = args.size / sizeof(int64_t);
+  auto rand = random::RandomArrayGenerator(kSeed);
+
+  auto min = std::numeric_limits<int64_t>::min();
+  auto max = std::numeric_limits<int64_t>::max();

Review comment:
       You will probably get almost no duplicate values with this.

##########
File path: cpp/src/arrow/compute/kernels/vector_sort.cc
##########
@@ -346,14 +374,396 @@ void AddSortingKernels(VectorKernel base, VectorFunction* func) {
   }
 }
 
+class TableSorter : public TypeVisitor {
+ private:
+  struct ResolvedSortKey {
+    ResolvedSortKey(const ChunkedArray& chunked_array, const SortOrder order)
+        : order(order) {
+      type = chunked_array.type().get();
+      null_count = chunked_array.null_count();
+      num_chunks = chunked_array.num_chunks();
+      for (const auto& chunk : chunked_array.chunks()) {
+        chunks.push_back(chunk.get());
+      }
+    }
+
+    template <typename ArrayType>
+    ArrayType* ResolveChunk(int64_t index, int64_t& chunk_index) const {
+      if (num_chunks == 1) {
+        chunk_index = index;
+        return static_cast<ArrayType*>(chunks[0]);
+      } else {
+        int64_t offset = 0;
+        for (size_t i = 0; i < num_chunks; ++i) {
+          if (index < offset + chunks[i]->length()) {
+            chunk_index = index - offset;
+            return static_cast<ArrayType*>(chunks[i]);
+          }
+          offset += chunks[i]->length();
+        }
+        return nullptr;
+      }
+    }
+
+    SortOrder order;
+    DataType* type;
+    int64_t null_count;
+    size_t num_chunks;
+    std::vector<Array*> chunks;
+  };
+
+  class Comparer : public TypeVisitor {
+   public:
+    Comparer(const Table& table, const std::vector<SortKey>& sort_keys)
+        : TypeVisitor(), status_(Status::OK()) {
+      for (const auto& sort_key : sort_keys) {
+        const auto& chunked_array = table.GetColumnByName(sort_key.name);
+        if (!chunked_array) {
+          status_ = Status::Invalid("Nonexistent sort key column: ", sort_key.name);
+          return;
+        }
+        sort_keys_.emplace_back(*chunked_array, sort_key.order);
+      }
+    }
+
+    Status status() { return status_; }
+
+    const std::vector<ResolvedSortKey>& sort_keys() { return sort_keys_; }
+
+    bool Compare(uint64_t left, uint64_t right, size_t start_sort_key_index) {
+      current_left_ = left;
+      current_right_ = right;
+      current_compared_ = 0;
+      auto num_sort_keys = sort_keys_.size();
+      for (size_t i = start_sort_key_index; i < num_sort_keys; ++i) {
+        current_sort_key_index_ = i;
+        status_ = sort_keys_[i].type->Accept(this);
+        if (current_compared_ != 0) {
+          break;
+        }
+      }
+      return current_compared_ < 0;
+    }
+
+#define VISIT(TYPE)                                \
+  Status Visit(const TYPE##Type& type) override {  \
+    current_compared_ = CompareType<TYPE##Type>(); \
+    return Status::OK();                           \
+  }
+
+    VISIT(Int8)
+    VISIT(Int16)
+    VISIT(Int32)
+    VISIT(Int64)
+    VISIT(UInt8)
+    VISIT(UInt16)
+    VISIT(UInt32)
+    VISIT(UInt64)
+    VISIT(Float)
+    VISIT(Double)
+    VISIT(String)
+    VISIT(Binary)
+    VISIT(LargeString)
+    VISIT(LargeBinary)
+
+#undef VISIT
+
+   private:
+    template <typename Type>
+    int32_t CompareType() {
+      using ArrayType = typename TypeTraits<Type>::ArrayType;
+      const auto& sort_key = sort_keys_[current_sort_key_index_];
+      auto order = sort_key.order;
+      int64_t index_left = 0;
+      auto array_left = sort_key.ResolveChunk<ArrayType>(current_left_, index_left);
+      int64_t index_right = 0;
+      auto array_right = sort_key.ResolveChunk<ArrayType>(current_right_, index_right);
+      if (sort_key.null_count > 0) {
+        auto is_null_left = array_left->IsNull(index_left);
+        auto is_null_right = array_right->IsNull(index_right);
+        if (is_null_left && is_null_right) {
+          return 0;
+        } else if (is_null_left) {
+          return 1;
+        } else if (is_null_right) {
+          return -1;
+        }
+      }
+      auto left = array_left->GetView(index_left);
+      auto right = array_right->GetView(index_right);
+      int32_t compared;
+      if (left == right) {
+        compared = 0;
+      } else if (left > right) {
+        compared = 1;
+      } else {
+        compared = -1;
+      }
+      if (order == SortOrder::DESCENDING) {
+        compared = -compared;
+      }
+      return compared;
+    }
+
+    Status status_;
+    std::vector<ResolvedSortKey> sort_keys_;
+    int64_t current_left_;
+    int64_t current_right_;
+    size_t current_sort_key_index_;
+    int32_t current_compared_;
+  };
+
+ public:
+  TableSorter(uint64_t* indices_begin, uint64_t* indices_end, const Table& table,
+              const SortOptions& options)
+      : indices_begin_(indices_begin),
+        indices_end_(indices_end),
+        comparer_(table, options.sort_keys) {}
+
+  Status Sort() {
+    ARROW_RETURN_NOT_OK(comparer_.status());
+    return comparer_.sort_keys()[0].type->Accept(this);
+  }
+
+#define VISIT(TYPE) \
+  Status Visit(const TYPE##Type& type) override { return SortInternal<TYPE##Type>(); }
+
+  VISIT(Int8)
+  VISIT(Int16)
+  VISIT(Int32)
+  VISIT(Int64)
+  VISIT(UInt8)
+  VISIT(UInt16)
+  VISIT(UInt32)
+  VISIT(UInt64)
+  VISIT(Float)
+  VISIT(Double)
+  VISIT(String)
+  VISIT(Binary)
+  VISIT(LargeString)
+  VISIT(LargeBinary)
+
+#undef VISIT
+
+ private:
+  template <typename Type>
+  Status SortInternal() {
+    using ArrayType = typename TypeTraits<Type>::ArrayType;
+    std::iota(indices_begin_, indices_end_, 0);
+
+    auto& comparer = comparer_;
+    const auto& first_sort_key = comparer.sort_keys()[0];
+    auto nulls_begin = indices_end_;
+    nulls_begin = PartitionNullsInternal<Type>(first_sort_key);
+    std::stable_sort(
+        indices_begin_, nulls_begin,
+        [&first_sort_key, &comparer](uint64_t left, uint64_t right) {
+          int64_t index_left = 0;
+          auto array_left = first_sort_key.ResolveChunk<ArrayType>(left, index_left);
+          int64_t index_right = 0;
+          auto array_right = first_sort_key.ResolveChunk<ArrayType>(right, index_right);
+          auto value_left = array_left->GetView(index_left);
+          auto value_right = array_right->GetView(index_right);
+          if (value_left == value_right) {
+            return comparer.Compare(left, right, 1);
+          } else {
+            auto compared = value_left < value_right;
+            if (first_sort_key.order == SortOrder::ASCENDING) {
+              return compared;
+            } else {
+              return !compared;
+            }
+          }
+        });
+    return Status::OK();
+  }
+
+  template <typename Type>
+  enable_if_t<!is_floating_type<Type>::value, uint64_t*> PartitionNullsInternal(
+      const ResolvedSortKey& first_sort_key) {
+    using ArrayType = typename TypeTraits<Type>::ArrayType;
+    if (first_sort_key.null_count == 0) {
+      return indices_end_;
+    }
+    StablePartitioner partitioner;
+    auto nulls_begin =
+        partitioner(indices_begin_, indices_end_, [&first_sort_key](uint64_t index) {
+          int64_t index_chunk = 0;
+          auto chunk = first_sort_key.ResolveChunk<ArrayType>(index, index_chunk);
+          return !chunk->IsNull(index_chunk);
+        });
+    auto& comparer = comparer_;
+    std::stable_sort(nulls_begin, indices_end_,
+                     [&comparer](uint64_t left, uint64_t right) {
+                       return comparer.Compare(left, right, 1);
+                     });
+    return nulls_begin;
+  }
+
+  template <typename Type>
+  enable_if_t<is_floating_type<Type>::value, uint64_t*> PartitionNullsInternal(
+      const ResolvedSortKey& first_sort_key) {
+    using ArrayType = typename TypeTraits<Type>::ArrayType;
+    StablePartitioner partitioner;
+    if (first_sort_key.null_count == 0) {
+      return partitioner(indices_begin_, indices_end_, [&first_sort_key](uint64_t index) {
+        int64_t index_chunk = 0;
+        auto chunk = first_sort_key.ResolveChunk<ArrayType>(index, index_chunk);
+        return !std::isnan(chunk->GetView(index_chunk));
+      });
+    }
+    auto nans_and_nulls_begin =
+        partitioner(indices_begin_, indices_end_, [&first_sort_key](uint64_t index) {
+          int64_t index_chunk = 0;
+          auto chunk = first_sort_key.ResolveChunk<ArrayType>(index, index_chunk);
+          return !chunk->IsNull(index_chunk) && !std::isnan(chunk->GetView(index_chunk));
+        });
+    auto nulls_begin = nans_and_nulls_begin;
+    if (first_sort_key.null_count < static_cast<int64_t>(indices_end_ - nulls_begin)) {
+      // move Nulls after NaN
+      nulls_begin = partitioner(
+          nans_and_nulls_begin, indices_end_, [&first_sort_key](uint64_t index) {
+            int64_t index_chunk = 0;
+            auto chunk = first_sort_key.ResolveChunk<ArrayType>(index, index_chunk);
+            return !chunk->IsNull(index_chunk);
+          });
+    }
+    auto& comparer = comparer_;
+    if (nans_and_nulls_begin != nulls_begin) {
+      std::stable_sort(nans_and_nulls_begin, nulls_begin,
+                       [&comparer](uint64_t left, uint64_t right) {
+                         return comparer.Compare(left, right, 1);
+                       });
+    }
+    std::stable_sort(nulls_begin, indices_end_,
+                     [&comparer](uint64_t left, uint64_t right) {
+                       return comparer.Compare(left, right, 1);
+                     });
+    return nans_and_nulls_begin;
+  }
+
+  uint64_t* indices_begin_;
+  uint64_t* indices_end_;
+  Comparer comparer_;
+};
+
 const FunctionDoc sort_indices_doc(
+    "Return the indices that would sort an array, record batch or table",
+    ("This function computes an array of indices that define a stable sort\n"
+     "of the input array, record batch or table.  Null values are considered\n"
+     "greater than any other value and are therefore sorted at the end of the\n"
+     "input. For floating-point types, NaNs are considered greater than any\n"
+     "other non-null value, but smaller than null values."),
+    {"input"}, "SortOptions");
+
+class SortIndicesMetaFunction : public MetaFunction {
+ public:
+  SortIndicesMetaFunction()
+      : MetaFunction("sort_indices", Arity::Unary(), &sort_indices_doc) {}
+
+  Result<Datum> ExecuteImpl(const std::vector<Datum>& args,
+                            const FunctionOptions* options,
+                            ExecContext* ctx) const override {
+    const SortOptions& sort_options = static_cast<const SortOptions&>(*options);
+    switch (args[0].kind()) {
+      case Datum::ARRAY:
+        return SortIndices(*args[0].make_array(), sort_options, ctx);
+        break;
+      case Datum::CHUNKED_ARRAY:
+        return SortIndices(*args[0].chunked_array(), sort_options, ctx);
+        break;
+      case Datum::RECORD_BATCH: {
+        ARROW_ASSIGN_OR_RAISE(auto table,
+                              Table::FromRecordBatches({args[0].record_batch()}));
+        return SortIndices(*table, sort_options, ctx);
+      } break;
+      case Datum::TABLE:
+        return SortIndices(*args[0].table(), sort_options, ctx);
+        break;
+      default:
+        break;
+    }
+    return Status::NotImplemented(
+        "Unsupported types for sort_indices operation: "
+        "values=",
+        args[0].ToString());
+  }
+
+ private:
+  Result<std::shared_ptr<Array>> SortIndices(const Array& values,
+                                             const SortOptions& options,
+                                             ExecContext* ctx) const {
+    SortOrder order = SortOrder::ASCENDING;
+    if (!options.sort_keys.empty()) {
+      order = options.sort_keys[0].order;
+    }
+    ArraySortOptions array_options(order);
+    ARROW_ASSIGN_OR_RAISE(
+        Datum result, CallFunction("array_sort_indices", {values}, &array_options, ctx));
+    return result.make_array();
+  }
+
+  Result<std::shared_ptr<Array>> SortIndices(const ChunkedArray& values,
+                                             const SortOptions& options,
+                                             ExecContext* ctx) const {
+    SortOrder order = SortOrder::ASCENDING;
+    if (!options.sort_keys.empty()) {
+      order = options.sort_keys[0].order;
+    }
+    ArraySortOptions array_options(order);
+
+    std::shared_ptr<Array> array_values;
+    if (values.num_chunks() == 1) {
+      array_values = values.chunk(0);
+    } else {
+      ARROW_ASSIGN_OR_RAISE(array_values,
+                            Concatenate(values.chunks(), ctx->memory_pool()));
+    }
+    ARROW_ASSIGN_OR_RAISE(Datum result, CallFunction("array_sort_indices", {array_values},
+                                                     &array_options, ctx));
+    return result.make_array();
+  }
+
+  Result<Datum> SortIndices(const Table& table, const SortOptions& options,
+                            ExecContext* ctx) const {
+    auto n_sort_keys = options.sort_keys.size();
+    if (n_sort_keys == 0) {
+      return Status::Invalid("Must specify one or more sort keys");
+    }
+    if (n_sort_keys == 1) {
+      auto chunked_array = table.GetColumnByName(options.sort_keys[0].name);
+      if (!chunked_array) {
+        return Status::Invalid("Nonexistent sort key column: ",
+                               options.sort_keys[0].name);
+      }
+      return SortIndices(*chunked_array, options, ctx);
+    }
+
+    auto out_type = uint64();
+    auto length = table.num_rows();
+    auto buffer_size = BitUtil::BytesForBits(
+        length * std::static_pointer_cast<UInt64Type>(out_type)->bit_width());

Review comment:
       `sizeof(uint64_t)` perhaps?

##########
File path: cpp/src/arrow/compute/kernels/vector_sort_test.cc
##########
@@ -364,32 +400,264 @@ TYPED_TEST(TestSortToIndicesKernelRandomCount, SortRandomValuesCount) {
   int range = 2000;
   for (int test = 0; test < times; test++) {
     for (auto null_probability : {0.0, 0.1, 0.5, 1.0}) {
-      auto array = rand.Generate(length, range, null_probability);
-      ASSERT_OK_AND_ASSIGN(std::shared_ptr<Array> offsets, SortToIndices(*array));
-      ValidateSorted<ArrayType>(*checked_pointer_cast<ArrayType>(array),
-                                *checked_pointer_cast<UInt64Array>(offsets));
+      for (auto order : {SortOrder::ASCENDING, SortOrder::DESCENDING}) {
+        auto array = rand.Generate(length, range, null_probability);
+        ASSERT_OK_AND_ASSIGN(std::shared_ptr<Array> offsets, SortIndices(*array, order));
+        ValidateSorted<ArrayType>(*checked_pointer_cast<ArrayType>(array),
+                                  *checked_pointer_cast<UInt64Array>(offsets), order);
+      }
     }
   }
 }
 
 // Long array with big value range: std::stable_sort
-TYPED_TEST_SUITE(TestSortToIndicesKernelRandomCompare, IntegralArrowTypes);
+TYPED_TEST_SUITE(TestArraySortIndicesKernelRandomCompare, IntegralArrowTypes);
 
-TYPED_TEST(TestSortToIndicesKernelRandomCompare, SortRandomValuesCompare) {
+TYPED_TEST(TestArraySortIndicesKernelRandomCompare, SortRandomValuesCompare) {
   using ArrayType = typename TypeTraits<TypeParam>::ArrayType;
 
   Random<TypeParam> rand(0x5487657);
   int times = 5;
   int length = 4000;
   for (int test = 0; test < times; test++) {
     for (auto null_probability : {0.0, 0.1, 0.5, 1.0}) {
-      auto array = rand.Generate(length, null_probability);
-      ASSERT_OK_AND_ASSIGN(std::shared_ptr<Array> offsets, SortToIndices(*array));
-      ValidateSorted<ArrayType>(*checked_pointer_cast<ArrayType>(array),
-                                *checked_pointer_cast<UInt64Array>(offsets));
+      for (auto order : {SortOrder::ASCENDING, SortOrder::DESCENDING}) {
+        auto array = rand.Generate(length, null_probability);
+        ASSERT_OK_AND_ASSIGN(std::shared_ptr<Array> offsets, SortIndices(*array, order));
+        ValidateSorted<ArrayType>(*checked_pointer_cast<ArrayType>(array),
+                                  *checked_pointer_cast<UInt64Array>(offsets), order);
+      }
     }
   }
 }
 
+class TestTableSortIndices : public ::testing::Test {
+ protected:
+  void AssertSortIndices(const std::shared_ptr<Table> table, const SortOptions& options,
+                         const std::shared_ptr<Array> expected) {
+    ASSERT_OK_AND_ASSIGN(auto actual, SortIndices(*table, options));
+    AssertArraysEqual(*expected, *actual);
+  }
+
+  void AssertSortIndices(const std::shared_ptr<Table> table, const SortOptions& options,
+                         const std::string expected) {
+    AssertSortIndices(table, options, ArrayFromJSON(uint64(), expected));
+  }
+};
+
+TEST_F(TestTableSortIndices, SortNull) {
+  auto table = TableFromJSON(schema({
+                                 {field("a", uint8())},
+                                 {field("b", uint8())},
+                             }),
+                             {"["
+                              "{\"a\": null, \"b\": 5},"
+                              "{\"a\": 1,    \"b\": 3},"
+                              "{\"a\": 3,    \"b\": null},"
+                              "{\"a\": null, \"b\": null},"
+                              "{\"a\": 2,    \"b\": 5},"
+                              "{\"a\": 1,    \"b\": 5}"
+                              "]"});
+  SortOptions options(
+      {SortKey("a", SortOrder::ASCENDING), SortKey("b", SortOrder::DESCENDING)});
+  this->AssertSortIndices(table, options, "[5, 1, 4, 2, 0, 3]");
+}
+
+TEST_F(TestTableSortIndices, SortNaN) {
+  auto table = TableFromJSON(schema({
+                                 {field("a", float32())},
+                                 {field("b", float32())},
+                             }),
+                             {"["
+                              "{\"a\": null, \"b\": 5},"
+                              "{\"a\": 1,    \"b\": 3},"
+                              "{\"a\": 3,    \"b\": null},"
+                              "{\"a\": null, \"b\": null},"
+                              "{\"a\": NaN,  \"b\": null},"
+                              "{\"a\": NaN,  \"b\": 5},"
+                              "{\"a\": NaN,  \"b\": NaN},"
+                              "{\"a\": 1,    \"b\": 5}"
+                              "]"});
+  SortOptions options(
+      {SortKey("a", SortOrder::ASCENDING), SortKey("b", SortOrder::DESCENDING)});
+  this->AssertSortIndices(table, options, "[7, 1, 2, 5, 6, 4, 0, 3]");
+}
+
+using RandomParam = std::tuple<std::string, double>;
+class TestTableSortIndicesRandom : public testing::TestWithParam<RandomParam> {
+  class Comparator : public TypeVisitor {

Review comment:
       Can you add comments when you define non-trivial classes and methods? This would help reading the code later.

##########
File path: cpp/src/arrow/compute/kernels/vector_sort.cc
##########
@@ -346,14 +374,396 @@ void AddSortingKernels(VectorKernel base, VectorFunction* func) {
   }
 }
 
+class TableSorter : public TypeVisitor {
+ private:
+  struct ResolvedSortKey {
+    ResolvedSortKey(const ChunkedArray& chunked_array, const SortOrder order)
+        : order(order) {
+      type = chunked_array.type().get();
+      null_count = chunked_array.null_count();
+      num_chunks = chunked_array.num_chunks();
+      for (const auto& chunk : chunked_array.chunks()) {
+        chunks.push_back(chunk.get());
+      }
+    }
+
+    template <typename ArrayType>
+    ArrayType* ResolveChunk(int64_t index, int64_t& chunk_index) const {

Review comment:
       Also, please make it `int64_t* chunk_index`. Out-parameters should be pointers.
   (you could also return a `std::pair` or a dedicated struct... anyway)




----------------------------------------------------------------
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.

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



[GitHub] [arrow] kou commented on a change in pull request #8612: ARROW-8199: [C++] Add support for multi-column sort indices on Table

Posted by GitBox <gi...@apache.org>.
kou commented on a change in pull request #8612:
URL: https://github.com/apache/arrow/pull/8612#discussion_r526611003



##########
File path: cpp/src/arrow/compute/api_vector.h
##########
@@ -58,6 +58,34 @@ struct ARROW_EXPORT TakeOptions : public FunctionOptions {
   static TakeOptions Defaults() { return BoundsCheck(); }
 };
 
+enum SortOrder {
+  ASCENDING,
+  DESCENDING,

Review comment:
       OK. Renamed.




----------------------------------------------------------------
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.

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



[GitHub] [arrow] pitrou commented on pull request #8612: ARROW-8199: [C++] Add support for multi-column sort indices on Table

Posted by GitBox <gi...@apache.org>.
pitrou commented on pull request #8612:
URL: https://github.com/apache/arrow/pull/8612#issuecomment-732983726


   Thanks for the numbers. I didn't expect "first sort key" to be better, but I'm convinced 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.

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



[GitHub] [arrow] cyb70289 commented on pull request #8612: ARROW-8199: [C++] Add support for multi-column sort indices on Table

Posted by GitBox <gi...@apache.org>.
cyb70289 commented on pull request #8612:
URL: https://github.com/apache/arrow/pull/8612#issuecomment-725094232


   Also update kernel document? `docs/source/cpp/compute.rst`


----------------------------------------------------------------
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.

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



[GitHub] [arrow] kou commented on a change in pull request #8612: ARROW-8199: [C++] Add support for multi-column sort indices on Table

Posted by GitBox <gi...@apache.org>.
kou commented on a change in pull request #8612:
URL: https://github.com/apache/arrow/pull/8612#discussion_r526610796



##########
File path: cpp/src/arrow/compute/api_vector.h
##########
@@ -58,6 +58,34 @@ struct ARROW_EXPORT TakeOptions : public FunctionOptions {
   static TakeOptions Defaults() { return BoundsCheck(); }
 };
 
+enum SortOrder {

Review comment:
       Yes. Thanks.




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

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



[GitHub] [arrow] kou commented on pull request #8612: ARROW-8199: [C++] Add support for multi-column sort indices on Table

Posted by GitBox <gi...@apache.org>.
kou commented on pull request #8612:
URL: https://github.com/apache/arrow/pull/8612#issuecomment-730167841


   >     * sort(chunked array) sorts each chunk individually, then merges all of them (see `std::inplace_merge`)
   
   I've implemented.
   See also: https://github.com/apache/arrow/pull/8612#discussion_r526616431
   
   >     * sort(table) sorts each sort column in reverse order
   
   I wanted this a follow-up task but I've implemented this in this pull request. Because both of them mentions this approach.
   
   My implementation `TableRadixSorter` is naive but this approach is slower than the first sort key based approach:
   
   Summary:
   
     * The first sort key approach is 1.1x-27.2x faster than the radix sort approach except narrow range and 2 sort keys case.
   
     * The first sort key approach doesn't depend on the number of sort keys in wide range data.
   
     * The first sort key approach slowed down when the number of sort keys is increased in narrow range data.
   
     * The radix sort approach always slowed down when the number of sort keys is increased.
       * Because the radix sort approach always sorts all sort keys.
   
   ----
   
   Description:
   
   N records: 1048576
   
   Narrow range: Almost elements may be same
   
   Wide range: Almost elements will be different
   
   ----
   
   N chunks: 4
   
   Narrow range:
   
   N sort keys          | 2           | 8            | 16
   -------------------- | ----------- | ------------ | ------------
   Radix                | 318651531ns | 2353793768ns | 4627874931ns
   First sort key       | 397339109ns | 595568690ns  | 591632035ns
   Radix/First sort key | 0.8         | 3.9          | 7.8
   
   Wide range:
   
   N sort keys          | 2           | 8            | 16
   -------------------- | ----------- | ------------ | ------------
   Radix                | 593904971ns | 2989364923ns | 6101922415ns
   First sort key       | 220809969ns | 218214843ns  | 223708791ns
   Radix/First sort key | 2.6         | 13.6         | 27.2
   
   ----
   
   N chunks: 32
   
   Narrow range:
   
   N sort keys          | 2            | 8            | 16
   -------------------- | ------------ | ------------ | ------------
   Radix                | 1198835057ns | 6513599980ns | 13562068073ns
   First sort key       | 1035218085ns | 1373174328ns | 1350031141ns
   Radix/First sort key | 1.1          | 4.7          | 10.0
   
   Wide range:
   
   N sort keys          | 2            | 8            | 16
   -------------------- | ------------ | ------------ | ------------
   Radix                | 1585765386ns | 7305830182ns | 15323045709ns
   First sort key       | 592304437ns  | 589917731ns  | 619193843ns
   Radix/First sort key | 2.6          | 12.3         | 24.7
   
   ----
   
   Can we mark the radix sort approach improvement a follow-up task? Or should we optimize the radix sort approach in this pull request?
   


----------------------------------------------------------------
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.

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



[GitHub] [arrow] kou commented on a change in pull request #8612: ARROW-8199: [C++] Add support for multi-column sort indices on Table

Posted by GitBox <gi...@apache.org>.
kou commented on a change in pull request #8612:
URL: https://github.com/apache/arrow/pull/8612#discussion_r526617675



##########
File path: cpp/src/arrow/compute/kernels/vector_sort.cc
##########
@@ -346,14 +374,396 @@ void AddSortingKernels(VectorKernel base, VectorFunction* func) {
   }
 }
 
+class TableSorter : public TypeVisitor {
+ private:
+  struct ResolvedSortKey {
+    ResolvedSortKey(const ChunkedArray& chunked_array, const SortOrder order)
+        : order(order) {
+      type = chunked_array.type().get();
+      null_count = chunked_array.null_count();
+      num_chunks = chunked_array.num_chunks();
+      for (const auto& chunk : chunked_array.chunks()) {
+        chunks.push_back(chunk.get());
+      }
+    }
+
+    template <typename ArrayType>
+    ArrayType* ResolveChunk(int64_t index, int64_t& chunk_index) const {
+      if (num_chunks == 1) {
+        chunk_index = index;
+        return static_cast<ArrayType*>(chunks[0]);
+      } else {
+        int64_t offset = 0;
+        for (size_t i = 0; i < num_chunks; ++i) {
+          if (index < offset + chunks[i]->length()) {
+            chunk_index = index - offset;
+            return static_cast<ArrayType*>(chunks[i]);
+          }
+          offset += chunks[i]->length();
+        }
+        return nullptr;
+      }
+    }
+
+    SortOrder order;
+    DataType* type;
+    int64_t null_count;
+    size_t num_chunks;
+    std::vector<Array*> chunks;
+  };
+
+  class Comparer : public TypeVisitor {
+   public:
+    Comparer(const Table& table, const std::vector<SortKey>& sort_keys)
+        : TypeVisitor(), status_(Status::OK()) {
+      for (const auto& sort_key : sort_keys) {
+        const auto& chunked_array = table.GetColumnByName(sort_key.name);
+        if (!chunked_array) {
+          status_ = Status::Invalid("Nonexistent sort key column: ", sort_key.name);
+          return;
+        }
+        sort_keys_.emplace_back(*chunked_array, sort_key.order);
+      }
+    }
+
+    Status status() { return status_; }
+
+    const std::vector<ResolvedSortKey>& sort_keys() { return sort_keys_; }
+
+    bool Compare(uint64_t left, uint64_t right, size_t start_sort_key_index) {
+      current_left_ = left;
+      current_right_ = right;
+      current_compared_ = 0;
+      auto num_sort_keys = sort_keys_.size();
+      for (size_t i = start_sort_key_index; i < num_sort_keys; ++i) {
+        current_sort_key_index_ = i;
+        status_ = sort_keys_[i].type->Accept(this);
+        if (current_compared_ != 0) {
+          break;
+        }
+      }
+      return current_compared_ < 0;
+    }
+
+#define VISIT(TYPE)                                \
+  Status Visit(const TYPE##Type& type) override {  \
+    current_compared_ = CompareType<TYPE##Type>(); \
+    return Status::OK();                           \
+  }
+
+    VISIT(Int8)
+    VISIT(Int16)
+    VISIT(Int32)
+    VISIT(Int64)
+    VISIT(UInt8)
+    VISIT(UInt16)
+    VISIT(UInt32)
+    VISIT(UInt64)
+    VISIT(Float)
+    VISIT(Double)
+    VISIT(String)
+    VISIT(Binary)
+    VISIT(LargeString)
+    VISIT(LargeBinary)
+
+#undef VISIT
+
+   private:
+    template <typename Type>
+    int32_t CompareType() {
+      using ArrayType = typename TypeTraits<Type>::ArrayType;
+      const auto& sort_key = sort_keys_[current_sort_key_index_];
+      auto order = sort_key.order;
+      int64_t index_left = 0;
+      auto array_left = sort_key.ResolveChunk<ArrayType>(current_left_, index_left);
+      int64_t index_right = 0;
+      auto array_right = sort_key.ResolveChunk<ArrayType>(current_right_, index_right);
+      if (sort_key.null_count > 0) {
+        auto is_null_left = array_left->IsNull(index_left);
+        auto is_null_right = array_right->IsNull(index_right);
+        if (is_null_left && is_null_right) {
+          return 0;
+        } else if (is_null_left) {
+          return 1;
+        } else if (is_null_right) {
+          return -1;
+        }
+      }
+      auto left = array_left->GetView(index_left);
+      auto right = array_right->GetView(index_right);
+      int32_t compared;
+      if (left == right) {
+        compared = 0;
+      } else if (left > right) {
+        compared = 1;
+      } else {
+        compared = -1;
+      }
+      if (order == SortOrder::DESCENDING) {
+        compared = -compared;
+      }
+      return compared;
+    }
+
+    Status status_;
+    std::vector<ResolvedSortKey> sort_keys_;
+    int64_t current_left_;
+    int64_t current_right_;
+    size_t current_sort_key_index_;
+    int32_t current_compared_;
+  };
+
+ public:
+  TableSorter(uint64_t* indices_begin, uint64_t* indices_end, const Table& table,
+              const SortOptions& options)
+      : indices_begin_(indices_begin),
+        indices_end_(indices_end),
+        comparer_(table, options.sort_keys) {}
+
+  Status Sort() {
+    ARROW_RETURN_NOT_OK(comparer_.status());
+    return comparer_.sort_keys()[0].type->Accept(this);
+  }
+
+#define VISIT(TYPE) \
+  Status Visit(const TYPE##Type& type) override { return SortInternal<TYPE##Type>(); }
+
+  VISIT(Int8)
+  VISIT(Int16)
+  VISIT(Int32)
+  VISIT(Int64)
+  VISIT(UInt8)
+  VISIT(UInt16)
+  VISIT(UInt32)
+  VISIT(UInt64)
+  VISIT(Float)
+  VISIT(Double)
+  VISIT(String)
+  VISIT(Binary)
+  VISIT(LargeString)
+  VISIT(LargeBinary)
+
+#undef VISIT
+
+ private:
+  template <typename Type>
+  Status SortInternal() {
+    using ArrayType = typename TypeTraits<Type>::ArrayType;
+    std::iota(indices_begin_, indices_end_, 0);
+
+    auto& comparer = comparer_;
+    const auto& first_sort_key = comparer.sort_keys()[0];
+    auto nulls_begin = indices_end_;
+    nulls_begin = PartitionNullsInternal<Type>(first_sort_key);
+    std::stable_sort(
+        indices_begin_, nulls_begin,
+        [&first_sort_key, &comparer](uint64_t left, uint64_t right) {
+          int64_t index_left = 0;
+          auto array_left = first_sort_key.ResolveChunk<ArrayType>(left, index_left);
+          int64_t index_right = 0;
+          auto array_right = first_sort_key.ResolveChunk<ArrayType>(right, index_right);
+          auto value_left = array_left->GetView(index_left);
+          auto value_right = array_right->GetView(index_right);
+          if (value_left == value_right) {
+            return comparer.Compare(left, right, 1);
+          } else {
+            auto compared = value_left < value_right;
+            if (first_sort_key.order == SortOrder::ASCENDING) {
+              return compared;
+            } else {
+              return !compared;
+            }
+          }
+        });
+    return Status::OK();
+  }
+
+  template <typename Type>
+  enable_if_t<!is_floating_type<Type>::value, uint64_t*> PartitionNullsInternal(
+      const ResolvedSortKey& first_sort_key) {
+    using ArrayType = typename TypeTraits<Type>::ArrayType;
+    if (first_sort_key.null_count == 0) {
+      return indices_end_;
+    }
+    StablePartitioner partitioner;
+    auto nulls_begin =
+        partitioner(indices_begin_, indices_end_, [&first_sort_key](uint64_t index) {
+          int64_t index_chunk = 0;
+          auto chunk = first_sort_key.ResolveChunk<ArrayType>(index, index_chunk);
+          return !chunk->IsNull(index_chunk);
+        });
+    auto& comparer = comparer_;
+    std::stable_sort(nulls_begin, indices_end_,
+                     [&comparer](uint64_t left, uint64_t right) {
+                       return comparer.Compare(left, right, 1);
+                     });
+    return nulls_begin;
+  }
+
+  template <typename Type>
+  enable_if_t<is_floating_type<Type>::value, uint64_t*> PartitionNullsInternal(
+      const ResolvedSortKey& first_sort_key) {
+    using ArrayType = typename TypeTraits<Type>::ArrayType;
+    StablePartitioner partitioner;
+    if (first_sort_key.null_count == 0) {
+      return partitioner(indices_begin_, indices_end_, [&first_sort_key](uint64_t index) {
+        int64_t index_chunk = 0;
+        auto chunk = first_sort_key.ResolveChunk<ArrayType>(index, index_chunk);
+        return !std::isnan(chunk->GetView(index_chunk));
+      });
+    }
+    auto nans_and_nulls_begin =
+        partitioner(indices_begin_, indices_end_, [&first_sort_key](uint64_t index) {
+          int64_t index_chunk = 0;
+          auto chunk = first_sort_key.ResolveChunk<ArrayType>(index, index_chunk);
+          return !chunk->IsNull(index_chunk) && !std::isnan(chunk->GetView(index_chunk));
+        });
+    auto nulls_begin = nans_and_nulls_begin;
+    if (first_sort_key.null_count < static_cast<int64_t>(indices_end_ - nulls_begin)) {
+      // move Nulls after NaN
+      nulls_begin = partitioner(
+          nans_and_nulls_begin, indices_end_, [&first_sort_key](uint64_t index) {
+            int64_t index_chunk = 0;
+            auto chunk = first_sort_key.ResolveChunk<ArrayType>(index, index_chunk);
+            return !chunk->IsNull(index_chunk);
+          });
+    }
+    auto& comparer = comparer_;
+    if (nans_and_nulls_begin != nulls_begin) {
+      std::stable_sort(nans_and_nulls_begin, nulls_begin,
+                       [&comparer](uint64_t left, uint64_t right) {
+                         return comparer.Compare(left, right, 1);
+                       });
+    }
+    std::stable_sort(nulls_begin, indices_end_,
+                     [&comparer](uint64_t left, uint64_t right) {
+                       return comparer.Compare(left, right, 1);
+                     });
+    return nans_and_nulls_begin;
+  }
+
+  uint64_t* indices_begin_;
+  uint64_t* indices_end_;
+  Comparer comparer_;
+};
+
 const FunctionDoc sort_indices_doc(
+    "Return the indices that would sort an array, record batch or table",
+    ("This function computes an array of indices that define a stable sort\n"
+     "of the input array, record batch or table.  Null values are considered\n"
+     "greater than any other value and are therefore sorted at the end of the\n"
+     "input. For floating-point types, NaNs are considered greater than any\n"
+     "other non-null value, but smaller than null values."),
+    {"input"}, "SortOptions");
+
+class SortIndicesMetaFunction : public MetaFunction {
+ public:
+  SortIndicesMetaFunction()
+      : MetaFunction("sort_indices", Arity::Unary(), &sort_indices_doc) {}
+
+  Result<Datum> ExecuteImpl(const std::vector<Datum>& args,
+                            const FunctionOptions* options,
+                            ExecContext* ctx) const override {
+    const SortOptions& sort_options = static_cast<const SortOptions&>(*options);
+    switch (args[0].kind()) {
+      case Datum::ARRAY:
+        return SortIndices(*args[0].make_array(), sort_options, ctx);
+        break;
+      case Datum::CHUNKED_ARRAY:
+        return SortIndices(*args[0].chunked_array(), sort_options, ctx);
+        break;
+      case Datum::RECORD_BATCH: {
+        ARROW_ASSIGN_OR_RAISE(auto table,
+                              Table::FromRecordBatches({args[0].record_batch()}));
+        return SortIndices(*table, sort_options, ctx);
+      } break;
+      case Datum::TABLE:
+        return SortIndices(*args[0].table(), sort_options, ctx);
+        break;
+      default:
+        break;
+    }
+    return Status::NotImplemented(
+        "Unsupported types for sort_indices operation: "
+        "values=",
+        args[0].ToString());
+  }
+
+ private:
+  Result<std::shared_ptr<Array>> SortIndices(const Array& values,
+                                             const SortOptions& options,
+                                             ExecContext* ctx) const {
+    SortOrder order = SortOrder::ASCENDING;
+    if (!options.sort_keys.empty()) {
+      order = options.sort_keys[0].order;
+    }
+    ArraySortOptions array_options(order);
+    ARROW_ASSIGN_OR_RAISE(
+        Datum result, CallFunction("array_sort_indices", {values}, &array_options, ctx));
+    return result.make_array();
+  }
+
+  Result<std::shared_ptr<Array>> SortIndices(const ChunkedArray& values,
+                                             const SortOptions& options,
+                                             ExecContext* ctx) const {
+    SortOrder order = SortOrder::ASCENDING;
+    if (!options.sort_keys.empty()) {
+      order = options.sort_keys[0].order;
+    }
+    ArraySortOptions array_options(order);
+
+    std::shared_ptr<Array> array_values;
+    if (values.num_chunks() == 1) {
+      array_values = values.chunk(0);
+    } else {
+      ARROW_ASSIGN_OR_RAISE(array_values,
+                            Concatenate(values.chunks(), ctx->memory_pool()));

Review comment:
       Ah, I forgot to mention this.
   I wanted to make ChunkedArray case as follow-up task. I wanted to focus to Table in this pull request.
   
   But I've implemented naive ChunkedArray support that doesn't use `Concatenate()` in this pull request. It sorts each chunk and then merge them but it doesn't use threads.




----------------------------------------------------------------
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.

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



[GitHub] [arrow] kou commented on pull request #8612: ARROW-8199: [C++] Add support for multi-column sort indices on Table

Posted by GitBox <gi...@apache.org>.
kou commented on pull request #8612:
URL: https://github.com/apache/arrow/pull/8612#issuecomment-732701082


   @pitrou Could you review this 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.

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



[GitHub] [arrow] cyb70289 commented on pull request #8612: ARROW-8199: [C++] Add support for multi-column sort indices on Table

Posted by GitBox <gi...@apache.org>.
cyb70289 commented on pull request #8612:
URL: https://github.com/apache/arrow/pull/8612#issuecomment-725205535


   @kou I'm okay with this patch.
   As you listed in follow up tasks, sorting arrays separately and merging afterwards should be faster. And I think there are other chances to improve performance.
   
   Some random thoughts:
   - Looks you are returning a flat index array, does it make sense to return array of tuple (chunk_index, offset_in_chunk)? Maybe easier for client code to use?
   - For multi column sorting, in one iteration, current code compares values column by column till first non-equal found. I don't know if a radix sort approach is better, e.g. sort by 2nd-order column first, then sort by 1st-order column. It may be possible to leverage existing array based sorting code(counting sort, etc).


----------------------------------------------------------------
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.

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