edponce commented on a change in pull request #11019:
URL: https://github.com/apache/arrow/pull/11019#discussion_r706230828



##########
File path: cpp/src/arrow/compute/kernels/select_k_test.cc
##########
@@ -0,0 +1,736 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#include <functional>
+#include <iostream>
+#include <limits>
+#include <memory>
+#include <string>
+#include <vector>
+
+#include "arrow/array/array_decimal.h"
+#include "arrow/array/concatenate.h"
+#include "arrow/compute/api_vector.h"
+#include "arrow/compute/kernels/test_util.h"
+#include "arrow/compute/kernels/util_internal.h"
+#include "arrow/table.h"
+#include "arrow/testing/gtest_common.h"
+#include "arrow/testing/gtest_util.h"
+#include "arrow/testing/random.h"
+#include "arrow/testing/util.h"
+#include "arrow/type_traits.h"
+
+namespace arrow {
+
+using internal::checked_cast;
+using internal::checked_pointer_cast;
+
+namespace compute {
+
+template <typename ArrayType, SortOrder order>
+class SelectKComparator {
+ public:

Review comment:
       There are already specialized `SelectKComparators` 
[here](https://github.com/apache/arrow/pull/11019/files#diff-bf5bdbbf3ffa5d706a841eb38face9739c18d515eeb829e31749c7deff2e9384R1825-R1845).

##########
File path: cpp/src/arrow/compute/api_vector.h
##########
@@ -252,6 +292,21 @@ ARROW_EXPORT
 Result<std::shared_ptr<Array>> NthToIndices(const Array& values, int64_t n,
                                             ExecContext* ctx = NULLPTR);
 
+/// \brief Returns the first k elements ordered by `options.keys`.
+///
+/// Return a sorted array with its elements rearranged in such
+/// a way that the value of the element in k-th position (options.k) is in the 
position it
+/// would be in a sorted datum ordered by `options.keys`. Null like values 
will be not
+/// part of the output. Output is not guaranteed to be stable.
+///
+/// \param[in] datum datum to be partitioned
+/// \param[in] options options
+/// \param[in] ctx the function execution context, optional
+/// \return a datum with the same schema as the input
+ARROW_EXPORT
+Result<std::shared_ptr<Array>> SelectKUnstable(const Datum& datum, 
SelectKOptions options,
+                                               ExecContext* ctx = NULLPTR);

Review comment:
       `SelectKOptions` have default values, so set them here to make the 
options optional.
   ```c++
   Result<std::shared_ptr<Array>> SelectKUnstable(const Datum& datum, const 
SelectKOptions& options = SelectKOptions::Defaults(), ExecContext* ctx = 
NULLPTR);
   ```

##########
File path: cpp/src/arrow/compute/api_vector.cc
##########
@@ -162,6 +189,13 @@ Result<std::shared_ptr<Array>> NthToIndices(const Array& 
values, int64_t n,
   return result.make_array();
 }
 
+Result<std::shared_ptr<Array>> SelectKUnstable(const Datum& datum, 
SelectKOptions options,

Review comment:
       Change `SelectKOptions` to `const SelectKOptions&`. Also, in prototype 
in header file.

##########
File path: cpp/src/arrow/compute/kernels/select_k_test.cc
##########
@@ -0,0 +1,736 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#include <functional>
+#include <iostream>
+#include <limits>
+#include <memory>
+#include <string>
+#include <vector>
+
+#include "arrow/array/array_decimal.h"
+#include "arrow/array/concatenate.h"
+#include "arrow/compute/api_vector.h"
+#include "arrow/compute/kernels/test_util.h"
+#include "arrow/compute/kernels/util_internal.h"
+#include "arrow/table.h"
+#include "arrow/testing/gtest_common.h"
+#include "arrow/testing/gtest_util.h"
+#include "arrow/testing/random.h"
+#include "arrow/testing/util.h"
+#include "arrow/type_traits.h"
+
+namespace arrow {
+
+using internal::checked_cast;
+using internal::checked_pointer_cast;
+
+namespace compute {
+
+template <typename ArrayType, SortOrder order>
+class SelectKComparator {
+ public:
+  template <typename Type>
+  bool operator()(const Type& lval, const Type& rval) {
+    if (order == SortOrder::Ascending) {
+      return lval <= rval;
+    } else {
+      return rval <= lval;
+    }
+  }
+};
+
+template <SortOrder order>
+Result<std::shared_ptr<Array>> SelectK(const Datum& values, int64_t k) {
+  if (order == SortOrder::Descending) {
+    return SelectKUnstable(values, SelectKOptions::TopKDefault(k));
+  } else {
+    return SelectKUnstable(values, SelectKOptions::BottomKDefault(k));
+  }
+}
+
+template <SortOrder order>
+Result<std::shared_ptr<Array>> SelectK(const Datum& values,
+                                       const SelectKOptions& options) {
+  if (order == SortOrder::Descending) {
+    return SelectKUnstable(Datum(values), options);
+  } else {
+    return SelectKUnstable(Datum(values), options);
+  }

Review comment:
       What is the logic here, both paths of the conditional perform the same 
operation. Also, there is `is_top_k()` and `is_bottom_k()` which work based on 
the sort keys. So, these template function allows specifying an order that is 
different from the ones dictated by the sort keys?

##########
File path: cpp/src/arrow/compute/kernels/vector_sort.cc
##########
@@ -1778,6 +1798,621 @@ class SortIndicesMetaFunction : public MetaFunction {
   }
 };
 
+// ----------------------------------------------------------------------
+// TopK/BottomK implementations
+
+const auto kDefaultSelectKOptions = SelectKOptions::Defaults();
+
+const FunctionDoc select_k_doc(
+    "Returns the first k elements ordered by `options.keys`",
+    ("This function computes the k elements of the input\n"
+     "array, record batch or table specified in the column names 
(`options.sort_keys`).\n"
+     "The columns that are not specified are returned as well, but not used 
for\n"
+     "ordering. Null values are considered  greater than any other value and 
are\n"
+     "therefore sorted at the end of the array.\n"
+     "For floating-point types, NaNs are considered greater than any\n"
+     "other non-null value, but smaller than null values."),
+    {"input"}, "SelectKOptions");

Review comment:
       Probably a clearer phrasing is: "For floating-point types, ordering of 
values is such that: Null > NaN > Inf > number."

##########
File path: cpp/src/arrow/compute/kernels/vector_sort.cc
##########
@@ -1142,6 +1144,23 @@ class MultipleKeyComparator {
     return current_compared_ < 0;
   }
 
+  bool Equals(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_ = VisitTypeInline(*sort_keys_[i].type, this);
+      // If the left value equals to the right value, we need to
+      // continue to sort.
+      if (current_compared_ != 0) {
+        break;

Review comment:
       This `break` is followed by a check `current_compared_ == 0` which we 
already know is false, so you can `return false` here.

##########
File path: cpp/src/arrow/compute/kernels/vector_sort.cc
##########
@@ -1778,6 +1798,621 @@ class SortIndicesMetaFunction : public MetaFunction {
   }
 };
 
+// ----------------------------------------------------------------------
+// TopK/BottomK implementations
+
+const auto kDefaultSelectKOptions = SelectKOptions::Defaults();
+
+const FunctionDoc select_k_doc(
+    "Returns the first k elements ordered by `options.keys`",
+    ("This function computes the k elements of the input\n"
+     "array, record batch or table specified in the column names 
(`options.sort_keys`).\n"
+     "The columns that are not specified are returned as well, but not used 
for\n"
+     "ordering. Null values are considered  greater than any other value and 
are\n"

Review comment:
       Remove extra whitespace "considered__greater"

##########
File path: cpp/src/arrow/compute/kernels/vector_sort.cc
##########
@@ -1778,6 +1798,621 @@ class SortIndicesMetaFunction : public MetaFunction {
   }
 };
 
+// ----------------------------------------------------------------------
+// TopK/BottomK implementations
+
+const auto kDefaultSelectKOptions = SelectKOptions::Defaults();
+
+const FunctionDoc select_k_doc(
+    "Returns the first k elements ordered by `options.keys`",
+    ("This function computes the k elements of the input\n"
+     "array, record batch or table specified in the column names 
(`options.sort_keys`).\n"
+     "The columns that are not specified are returned as well, but not used 
for\n"
+     "ordering. Null values are considered  greater than any other value and 
are\n"
+     "therefore sorted at the end of the array.\n"
+     "For floating-point types, NaNs are considered greater than any\n"
+     "other non-null value, but smaller than null values."),
+    {"input"}, "SelectKOptions");
+
+Result<std::shared_ptr<ArrayData>> MakeMutableUInt64Array(
+    std::shared_ptr<DataType> out_type, int64_t length, MemoryPool* 
memory_pool) {
+  auto buffer_size = length * sizeof(uint64_t);
+  ARROW_ASSIGN_OR_RAISE(auto data, AllocateBuffer(buffer_size, memory_pool));
+  return ArrayData::Make(uint64(), length, {nullptr, std::move(data)}, 
/*null_count=*/0);
+}
+
+template <SortOrder order>
+class SelectKComparator {
+ public:
+  template <typename Type>
+  bool operator()(const Type& lval, const Type& rval);
+};
+
+template <>
+class SelectKComparator<SortOrder::Ascending> {
+ public:
+  template <typename Type>
+  bool operator()(const Type& lval, const Type& rval) {
+    return lval < rval;
+  }
+};
+
+template <>
+class SelectKComparator<SortOrder::Descending> {
+ public:
+  template <typename Type>
+  bool operator()(const Type& lval, const Type& rval) {
+    return rval < lval;
+  }
+};
+
+template <SortOrder sort_order>
+class ArraySelecter : public TypeVisitor {
+ public:
+  ArraySelecter(ExecContext* ctx, const Array& array, const SelectKOptions& 
options,
+                Datum* output)
+      : TypeVisitor(),
+        ctx_(ctx),
+        array_(array),
+        k_(options.k),
+        physical_type_(GetPhysicalType(array.type())),
+        output_(output) {}
+
+  Status Run() { return physical_type_->Accept(this); }
+
+#define VISIT(TYPE) \
+  Status Visit(const TYPE& type) { return SelectKthInternal<TYPE>(); }
+
+  VISIT_PHYSICAL_TYPES(VISIT)
+
+#undef VISIT
+
+  template <typename InType>
+  Status SelectKthInternal() {
+    using GetView = GetViewType<InType>;
+    using ArrayType = typename TypeTraits<InType>::ArrayType;
+
+    ArrayType arr(array_.data());
+    std::vector<uint64_t> indices(arr.length());
+
+    uint64_t* indices_begin = indices.data();
+    uint64_t* indices_end = indices_begin + indices.size();
+    std::iota(indices_begin, indices_end, 0);
+    if (k_ > arr.length()) {
+      k_ = arr.length();
+    }

Review comment:
       Nit: maybe use `k_ = std::min(k_, arr.length());`
   Also, there are other places this pattern appears.

##########
File path: cpp/src/arrow/compute/kernels/vector_sort.cc
##########
@@ -1778,6 +1798,621 @@ class SortIndicesMetaFunction : public MetaFunction {
   }
 };
 
+// ----------------------------------------------------------------------
+// TopK/BottomK implementations
+
+const auto kDefaultSelectKOptions = SelectKOptions::Defaults();
+
+const FunctionDoc select_k_doc(
+    "Returns the first k elements ordered by `options.keys`",
+    ("This function computes the k elements of the input\n"
+     "array, record batch or table specified in the column names 
(`options.sort_keys`).\n"
+     "The columns that are not specified are returned as well, but not used 
for\n"
+     "ordering. Null values are considered  greater than any other value and 
are\n"
+     "therefore sorted at the end of the array.\n"
+     "For floating-point types, NaNs are considered greater than any\n"
+     "other non-null value, but smaller than null values."),
+    {"input"}, "SelectKOptions");
+
+Result<std::shared_ptr<ArrayData>> MakeMutableUInt64Array(
+    std::shared_ptr<DataType> out_type, int64_t length, MemoryPool* 
memory_pool) {
+  auto buffer_size = length * sizeof(uint64_t);
+  ARROW_ASSIGN_OR_RAISE(auto data, AllocateBuffer(buffer_size, memory_pool));
+  return ArrayData::Make(uint64(), length, {nullptr, std::move(data)}, 
/*null_count=*/0);
+}
+
+template <SortOrder order>
+class SelectKComparator {
+ public:
+  template <typename Type>
+  bool operator()(const Type& lval, const Type& rval);
+};
+
+template <>
+class SelectKComparator<SortOrder::Ascending> {
+ public:
+  template <typename Type>
+  bool operator()(const Type& lval, const Type& rval) {
+    return lval < rval;
+  }
+};
+
+template <>
+class SelectKComparator<SortOrder::Descending> {
+ public:
+  template <typename Type>
+  bool operator()(const Type& lval, const Type& rval) {
+    return rval < lval;
+  }
+};
+
+template <SortOrder sort_order>
+class ArraySelecter : public TypeVisitor {
+ public:
+  ArraySelecter(ExecContext* ctx, const Array& array, const SelectKOptions& 
options,
+                Datum* output)
+      : TypeVisitor(),
+        ctx_(ctx),
+        array_(array),
+        k_(options.k),
+        physical_type_(GetPhysicalType(array.type())),
+        output_(output) {}
+
+  Status Run() { return physical_type_->Accept(this); }
+
+#define VISIT(TYPE) \
+  Status Visit(const TYPE& type) { return SelectKthInternal<TYPE>(); }
+
+  VISIT_PHYSICAL_TYPES(VISIT)
+
+#undef VISIT
+
+  template <typename InType>
+  Status SelectKthInternal() {
+    using GetView = GetViewType<InType>;
+    using ArrayType = typename TypeTraits<InType>::ArrayType;
+
+    ArrayType arr(array_.data());
+    std::vector<uint64_t> indices(arr.length());
+
+    uint64_t* indices_begin = indices.data();
+    uint64_t* indices_end = indices_begin + indices.size();
+    std::iota(indices_begin, indices_end, 0);
+    if (k_ > arr.length()) {
+      k_ = arr.length();
+    }
+    auto end_iter = PartitionNulls<ArrayType, 
NonStablePartitioner>(indices_begin,
+                                                                    
indices_end, arr, 0);
+    auto kth_begin = indices_begin + k_;
+    if (kth_begin > end_iter) {
+      kth_begin = end_iter;
+    }

Review comment:
       This can be simplified to `auto kth_begin = std::min(indices_begin + k_, 
end_iter);`

##########
File path: cpp/src/arrow/compute/kernels/vector_sort.cc
##########
@@ -1778,6 +1798,621 @@ class SortIndicesMetaFunction : public MetaFunction {
   }
 };
 
+// ----------------------------------------------------------------------
+// TopK/BottomK implementations
+
+const auto kDefaultSelectKOptions = SelectKOptions::Defaults();
+
+const FunctionDoc select_k_doc(
+    "Returns the first k elements ordered by `options.keys`",
+    ("This function computes the k elements of the input\n"
+     "array, record batch or table specified in the column names 
(`options.sort_keys`).\n"

Review comment:
       Not sure what "... computes the k elements ..." means. Probably, "... 
selects the first k ordered elements from the input ...".




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

To unsubscribe, e-mail: [email protected]

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


Reply via email to