diff --git a/cpp/src/arrow/CMakeLists.txt b/cpp/src/arrow/CMakeLists.txt index 5d01376796b6..70119df9e464 100644 --- a/cpp/src/arrow/CMakeLists.txt +++ b/cpp/src/arrow/CMakeLists.txt @@ -378,6 +378,7 @@ if(ARROW_COMPUTE) compute/exec/project_node.cc compute/exec/source_node.cc compute/exec/sink_node.cc + compute/exec/order_by_impl.cc compute/function.cc compute/function_internal.cc compute/kernel.cc diff --git a/cpp/src/arrow/compute/exec/options.h b/cpp/src/arrow/compute/exec/options.h index 3dd88210e784..7469635f0373 100644 --- a/cpp/src/arrow/compute/exec/options.h +++ b/cpp/src/arrow/compute/exec/options.h @@ -219,5 +219,20 @@ class ARROW_EXPORT HashJoinNodeOptions : public ExecNodeOptions { std::string output_prefix_for_right; }; +/// \brief Make a node which select top_k/bottom_k rows passed through it +/// +/// All batches pushed to this node will be accumulated, then selected, by the given +/// fields. Then sorted batches will be forwarded to the generator in sorted order. +class ARROW_EXPORT SelectKSinkNodeOptions : public SinkNodeOptions { + public: + explicit SelectKSinkNodeOptions( + SelectKOptions select_k_options, + std::function>()>* generator) + : SinkNodeOptions(generator), select_k_options(std::move(select_k_options)) {} + + /// SelectK options + SelectKOptions select_k_options; +}; + } // namespace compute } // namespace arrow diff --git a/cpp/src/arrow/compute/exec/order_by_impl.cc b/cpp/src/arrow/compute/exec/order_by_impl.cc new file mode 100644 index 000000000000..4afcf884f53a --- /dev/null +++ b/cpp/src/arrow/compute/exec/order_by_impl.cc @@ -0,0 +1,104 @@ +// 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 "arrow/compute/exec/order_by_impl.h" + +#include +#include +#include +#include +#include "arrow/compute/api_vector.h" +#include "arrow/compute/exec/options.h" +#include "arrow/record_batch.h" +#include "arrow/result.h" +#include "arrow/status.h" +#include "arrow/table.h" +#include "arrow/type.h" +#include "arrow/util/checked_cast.h" + +namespace arrow { +using internal::checked_cast; + +namespace compute { + +class SortBasicImpl : public OrderByImpl { + public: + SortBasicImpl(ExecContext* ctx, const std::shared_ptr& output_schema, + const SortOptions& options = SortOptions{}) + : ctx_(ctx), output_schema_(output_schema), options_(options) {} + + void InputReceived(const std::shared_ptr& batch) override { + std::unique_lock lock(mutex_); + batches_.push_back(batch); + } + + Result DoFinish() override { + std::unique_lock lock(mutex_); + ARROW_ASSIGN_OR_RAISE(auto table, + Table::FromRecordBatches(output_schema_, std::move(batches_))); + ARROW_ASSIGN_OR_RAISE(auto indices, SortIndices(table, options_, ctx_)); + return Take(table, indices, TakeOptions::NoBoundsCheck(), ctx_); + } + + std::string ToString() const override { return options_.ToString(); } + + protected: + ExecContext* ctx_; + std::shared_ptr output_schema_; + std::mutex mutex_; + std::vector> batches_; + + private: + const SortOptions options_; +}; // namespace compute + +class SelectKBasicImpl : public SortBasicImpl { + public: + SelectKBasicImpl(ExecContext* ctx, const std::shared_ptr& output_schema, + const SelectKOptions& options) + : SortBasicImpl(ctx, output_schema), options_(options) {} + + Result DoFinish() override { + std::unique_lock lock(mutex_); + ARROW_ASSIGN_OR_RAISE(auto table, + Table::FromRecordBatches(output_schema_, std::move(batches_))); + ARROW_ASSIGN_OR_RAISE(auto indices, SelectKUnstable(table, options_, ctx_)); + return Take(table, indices, TakeOptions::NoBoundsCheck(), ctx_); + } + + std::string ToString() const override { return options_.ToString(); } + + private: + const SelectKOptions options_; +}; + +Result> OrderByImpl::MakeSort( + ExecContext* ctx, const std::shared_ptr& output_schema, + const SortOptions& options) { + std::unique_ptr impl{new SortBasicImpl(ctx, output_schema, options)}; + return std::move(impl); +} + +Result> OrderByImpl::MakeSelectK( + ExecContext* ctx, const std::shared_ptr& output_schema, + const SelectKOptions& options) { + std::unique_ptr impl{new SelectKBasicImpl(ctx, output_schema, options)}; + return std::move(impl); +} + +} // namespace compute +} // namespace arrow diff --git a/cpp/src/arrow/compute/exec/order_by_impl.h b/cpp/src/arrow/compute/exec/order_by_impl.h new file mode 100644 index 000000000000..afc92aeddb2c --- /dev/null +++ b/cpp/src/arrow/compute/exec/order_by_impl.h @@ -0,0 +1,53 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include + +#include "arrow/compute/exec/options.h" +#include "arrow/record_batch.h" +#include "arrow/result.h" +#include "arrow/status.h" +#include "arrow/type.h" + +namespace arrow { +namespace compute { + +class OrderByImpl { + public: + virtual ~OrderByImpl() = default; + + virtual void InputReceived(const std::shared_ptr& batch) = 0; + + virtual Result DoFinish() = 0; + + virtual std::string ToString() const = 0; + + static Result> MakeSort( + ExecContext* ctx, const std::shared_ptr& output_schema, + const SortOptions& options); + + static Result> MakeSelectK( + ExecContext* ctx, const std::shared_ptr& output_schema, + const SelectKOptions& options); +}; + +} // namespace compute +} // namespace arrow diff --git a/cpp/src/arrow/compute/exec/plan_test.cc b/cpp/src/arrow/compute/exec/plan_test.cc index 8b1c2794bb37..85b657fe118a 100644 --- a/cpp/src/arrow/compute/exec/plan_test.cc +++ b/cpp/src/arrow/compute/exec/plan_test.cc @@ -665,6 +665,41 @@ TEST(ExecPlanExecution, SourceFilterProjectGroupedSumOrderBy) { } } +TEST(ExecPlanExecution, SourceFilterProjectGroupedSumTopK) { + for (bool parallel : {false, true}) { + SCOPED_TRACE(parallel ? "parallel/merged" : "serial"); + + int batch_multiplicity = parallel ? 100 : 1; + auto input = MakeGroupableBatches(/*multiplicity=*/batch_multiplicity); + + ASSERT_OK_AND_ASSIGN(auto plan, ExecPlan::Make()); + AsyncGenerator> sink_gen; + + SelectKOptions options = SelectKOptions::TopKDefault(/*k=*/1, {"str"}); + ASSERT_OK( + Declaration::Sequence( + { + {"source", + SourceNodeOptions{input.schema, input.gen(parallel, /*slow=*/false)}}, + {"project", ProjectNodeOptions{{ + field_ref("str"), + call("multiply", {field_ref("i32"), literal(2)}), + }}}, + {"aggregate", AggregateNodeOptions{/*aggregates=*/{{"hash_sum", nullptr}}, + /*targets=*/{"multiply(i32, 2)"}, + /*names=*/{"sum(multiply(i32, 2))"}, + /*keys=*/{"str"}}}, + {"select_k_sink", SelectKSinkNodeOptions{options, &sink_gen}}, + }) + .AddToPlan(plan.get())); + + ASSERT_THAT( + StartAndCollect(plan.get(), sink_gen), + Finishes(ResultWith(ElementsAreArray({ExecBatchFromJSON( + {int64(), utf8()}, parallel ? R"([[800, "gama"]])" : R"([[8, "gama"]])")})))); + } +} + TEST(ExecPlanExecution, SourceScalarAggSink) { ASSERT_OK_AND_ASSIGN(auto plan, ExecPlan::Make()); AsyncGenerator> sink_gen; diff --git a/cpp/src/arrow/compute/exec/sink_node.cc b/cpp/src/arrow/compute/exec/sink_node.cc index b5f3ae4ee600..76889c244d7a 100644 --- a/cpp/src/arrow/compute/exec/sink_node.cc +++ b/cpp/src/arrow/compute/exec/sink_node.cc @@ -24,6 +24,7 @@ #include "arrow/compute/exec.h" #include "arrow/compute/exec/expression.h" #include "arrow/compute/exec/options.h" +#include "arrow/compute/exec/order_by_impl.h" #include "arrow/compute/exec/util.h" #include "arrow/compute/exec_internal.h" #include "arrow/datum.h" @@ -131,36 +132,57 @@ class SinkNode : public ExecNode { PushGenerator>::Producer producer_; }; -// A sink node that accumulates inputs, then sorts them before emitting them. struct OrderBySinkNode final : public SinkNode { - OrderBySinkNode(ExecPlan* plan, std::vector inputs, SortOptions sort_options, + OrderBySinkNode(ExecPlan* plan, std::vector inputs, + std::unique_ptr impl, AsyncGenerator>* generator) - : SinkNode(plan, std::move(inputs), generator), - sort_options_(std::move(sort_options)) {} + : SinkNode(plan, std::move(inputs), generator), impl_{std::move(impl)} {} const char* kind_name() const override { return "OrderBySinkNode"; } - static Result Make(ExecPlan* plan, std::vector inputs, - const ExecNodeOptions& options) { + // A sink node that accumulates inputs, then sorts them before emitting them. + static Result MakeSort(ExecPlan* plan, std::vector inputs, + const ExecNodeOptions& options) { RETURN_NOT_OK(ValidateExecNodeInputs(plan, inputs, 1, "OrderBySinkNode")); const auto& sink_options = checked_cast(options); - return plan->EmplaceNode( - plan, std::move(inputs), sink_options.sort_options, sink_options.generator); + ARROW_ASSIGN_OR_RAISE( + std::unique_ptr impl, + OrderByImpl::MakeSort(plan->exec_context(), inputs[0]->output_schema(), + sink_options.sort_options)); + return plan->EmplaceNode(plan, std::move(inputs), std::move(impl), + sink_options.generator); + } + + // A sink node that receives inputs and then compute top_k/bottom_k. + static Result MakeSelectK(ExecPlan* plan, std::vector inputs, + const ExecNodeOptions& options) { + RETURN_NOT_OK(ValidateExecNodeInputs(plan, inputs, 1, "OrderBySinkNode")); + + const auto& sink_options = checked_cast(options); + ARROW_ASSIGN_OR_RAISE( + std::unique_ptr impl, + OrderByImpl::MakeSelectK(plan->exec_context(), inputs[0]->output_schema(), + sink_options.select_k_options)); + return plan->EmplaceNode(plan, std::move(inputs), std::move(impl), + sink_options.generator); } void InputReceived(ExecNode* input, ExecBatch batch) override { DCHECK_EQ(input, inputs_[0]); - // Accumulate data - { - std::unique_lock lock(mutex_); - auto maybe_batch = batch.ToRecordBatch(inputs_[0]->output_schema(), - plan()->exec_context()->memory_pool()); - if (ErrorIfNotOk(maybe_batch.status())) return; - batches_.push_back(maybe_batch.MoveValueUnsafe()); + auto maybe_batch = batch.ToRecordBatch(inputs_[0]->output_schema(), + plan()->exec_context()->memory_pool()); + if (ErrorIfNotOk(maybe_batch.status())) { + StopProducing(); + bool cancelled = input_counter_.Cancel(); + DCHECK(cancelled); + finished_.MarkFinished(maybe_batch.status()); + return; } + auto record_batch = maybe_batch.MoveValueUnsafe(); + impl_->InputReceived(std::move(record_batch)); if (input_counter_.Increment()) { Finish(); } @@ -168,17 +190,7 @@ struct OrderBySinkNode final : public SinkNode { protected: Status DoFinish() { - Datum sorted; - { - std::unique_lock lock(mutex_); - ARROW_ASSIGN_OR_RAISE( - auto table, - Table::FromRecordBatches(inputs_[0]->output_schema(), std::move(batches_))); - ARROW_ASSIGN_OR_RAISE(auto indices, - SortIndices(table, sort_options_, plan()->exec_context())); - ARROW_ASSIGN_OR_RAISE(sorted, Take(table, indices, TakeOptions::NoBoundsCheck(), - plan()->exec_context())); - } + ARROW_ASSIGN_OR_RAISE(Datum sorted, impl_->DoFinish()); TableBatchReader reader(*sorted.table()); while (true) { std::shared_ptr batch; @@ -199,12 +211,12 @@ struct OrderBySinkNode final : public SinkNode { } protected: - std::string ToStringExtra() const override { return "by=" + sort_options_.ToString(); } + std::string ToStringExtra() const override { + return std::string("by=") + impl_->ToString(); + } private: - SortOptions sort_options_; - std::mutex mutex_; - std::vector> batches_; + std::unique_ptr impl_; }; } // namespace @@ -212,7 +224,8 @@ struct OrderBySinkNode final : public SinkNode { namespace internal { void RegisterSinkNode(ExecFactoryRegistry* registry) { - DCHECK_OK(registry->AddFactory("order_by_sink", OrderBySinkNode::Make)); + DCHECK_OK(registry->AddFactory("select_k_sink", OrderBySinkNode::MakeSelectK)); + DCHECK_OK(registry->AddFactory("order_by_sink", OrderBySinkNode::MakeSort)); DCHECK_OK(registry->AddFactory("sink", SinkNode::Make)); }