Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions cpp/src/arrow/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
15 changes: 15 additions & 0 deletions cpp/src/arrow/compute/exec/options.h
Original file line number Diff line number Diff line change
Expand Up @@ -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<Future<util::optional<ExecBatch>>()>* generator)
: SinkNodeOptions(generator), select_k_options(std::move(select_k_options)) {}

/// SelectK options
SelectKOptions select_k_options;
};

} // namespace compute
} // namespace arrow
104 changes: 104 additions & 0 deletions cpp/src/arrow/compute/exec/order_by_impl.cc
Original file line number Diff line number Diff line change
@@ -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 <functional>
#include <memory>
#include <mutex>
#include <vector>
#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<Schema>& output_schema,
const SortOptions& options = SortOptions{})
: ctx_(ctx), output_schema_(output_schema), options_(options) {}

void InputReceived(const std::shared_ptr<RecordBatch>& batch) override {
std::unique_lock<std::mutex> lock(mutex_);
batches_.push_back(batch);
}

Result<Datum> DoFinish() override {
std::unique_lock<std::mutex> 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<Schema> output_schema_;
std::mutex mutex_;
std::vector<std::shared_ptr<RecordBatch>> batches_;

private:
const SortOptions options_;
}; // namespace compute

class SelectKBasicImpl : public SortBasicImpl {
public:
SelectKBasicImpl(ExecContext* ctx, const std::shared_ptr<Schema>& output_schema,
const SelectKOptions& options)
: SortBasicImpl(ctx, output_schema), options_(options) {}

Result<Datum> DoFinish() override {
std::unique_lock<std::mutex> 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<std::unique_ptr<OrderByImpl>> OrderByImpl::MakeSort(
ExecContext* ctx, const std::shared_ptr<Schema>& output_schema,
const SortOptions& options) {
std::unique_ptr<OrderByImpl> impl{new SortBasicImpl(ctx, output_schema, options)};
return std::move(impl);
}

Result<std::unique_ptr<OrderByImpl>> OrderByImpl::MakeSelectK(
ExecContext* ctx, const std::shared_ptr<Schema>& output_schema,
const SelectKOptions& options) {
std::unique_ptr<OrderByImpl> impl{new SelectKBasicImpl(ctx, output_schema, options)};
return std::move(impl);
}

} // namespace compute
} // namespace arrow
53 changes: 53 additions & 0 deletions cpp/src/arrow/compute/exec/order_by_impl.h
Original file line number Diff line number Diff line change
@@ -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 <functional>
#include <memory>
#include <vector>

#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<RecordBatch>& batch) = 0;

virtual Result<Datum> DoFinish() = 0;

virtual std::string ToString() const = 0;

static Result<std::unique_ptr<OrderByImpl>> MakeSort(
ExecContext* ctx, const std::shared_ptr<Schema>& output_schema,
const SortOptions& options);

static Result<std::unique_ptr<OrderByImpl>> MakeSelectK(
ExecContext* ctx, const std::shared_ptr<Schema>& output_schema,
const SelectKOptions& options);
};

} // namespace compute
} // namespace arrow
35 changes: 35 additions & 0 deletions cpp/src/arrow/compute/exec/plan_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -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<util::optional<ExecBatch>> 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<util::optional<ExecBatch>> sink_gen;
Expand Down
75 changes: 44 additions & 31 deletions cpp/src/arrow/compute/exec/sink_node.cc
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -131,54 +132,65 @@ class SinkNode : public ExecNode {
PushGenerator<util::optional<ExecBatch>>::Producer producer_;
};

// A sink node that accumulates inputs, then sorts them before emitting them.
struct OrderBySinkNode final : public SinkNode {
OrderBySinkNode(ExecPlan* plan, std::vector<ExecNode*> inputs, SortOptions sort_options,
OrderBySinkNode(ExecPlan* plan, std::vector<ExecNode*> inputs,
std::unique_ptr<OrderByImpl> impl,
AsyncGenerator<util::optional<ExecBatch>>* 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<ExecNode*> Make(ExecPlan* plan, std::vector<ExecNode*> inputs,
const ExecNodeOptions& options) {
// A sink node that accumulates inputs, then sorts them before emitting them.
static Result<ExecNode*> MakeSort(ExecPlan* plan, std::vector<ExecNode*> inputs,
const ExecNodeOptions& options) {
RETURN_NOT_OK(ValidateExecNodeInputs(plan, inputs, 1, "OrderBySinkNode"));

const auto& sink_options = checked_cast<const OrderBySinkNodeOptions&>(options);
return plan->EmplaceNode<OrderBySinkNode>(
plan, std::move(inputs), sink_options.sort_options, sink_options.generator);
ARROW_ASSIGN_OR_RAISE(
std::unique_ptr<OrderByImpl> impl,
OrderByImpl::MakeSort(plan->exec_context(), inputs[0]->output_schema(),
sink_options.sort_options));
return plan->EmplaceNode<OrderBySinkNode>(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<ExecNode*> MakeSelectK(ExecPlan* plan, std::vector<ExecNode*> inputs,
const ExecNodeOptions& options) {
RETURN_NOT_OK(ValidateExecNodeInputs(plan, inputs, 1, "OrderBySinkNode"));

const auto& sink_options = checked_cast<const SelectKSinkNodeOptions&>(options);
ARROW_ASSIGN_OR_RAISE(
std::unique_ptr<OrderByImpl> impl,
OrderByImpl::MakeSelectK(plan->exec_context(), inputs[0]->output_schema(),
sink_options.select_k_options));
return plan->EmplaceNode<OrderBySinkNode>(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<std::mutex> 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();
}
}

protected:
Status DoFinish() {
Datum sorted;
{
std::unique_lock<std::mutex> 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<RecordBatch> batch;
Expand All @@ -199,20 +211,21 @@ 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<std::shared_ptr<RecordBatch>> batches_;
std::unique_ptr<OrderByImpl> impl_;
};

} // namespace

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));
}

Expand Down