Skip to content
Merged
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
50 changes: 49 additions & 1 deletion python/pyarrow/_acero.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,10 @@ from pyarrow.includes.libarrow_dataset cimport *
from pyarrow.lib cimport (Table, pyarrow_unwrap_table, pyarrow_wrap_table,
RecordBatchReader)
from pyarrow.lib import frombytes, tobytes
from pyarrow._compute cimport Expression, FunctionOptions, _ensure_field_ref, _true
from pyarrow._compute cimport (
Expression, FunctionOptions, _ensure_field_ref, _true,
unwrap_null_placement, unwrap_sort_order
)


cdef class ExecNodeOptions(_Weakrefable):
Expand Down Expand Up @@ -223,6 +226,51 @@ class AggregateNodeOptions(_AggregateNodeOptions):
self._set_options(aggregates, keys)


cdef class _OrderByNodeOptions(ExecNodeOptions):

def _set_options(self, sort_keys, null_placement):
cdef:
vector[CSortKey] c_sort_keys

for name, order in sort_keys:
c_sort_keys.push_back(
CSortKey(_ensure_field_ref(name), unwrap_sort_order(order))
)

self.wrapped.reset(
new COrderByNodeOptions(
COrdering(c_sort_keys, unwrap_null_placement(null_placement))
)
)


class OrderByNodeOptions(_OrderByNodeOptions):
"""
Make a node which applies a new ordering to the data.

Currently this node works by accumulating all data, sorting, and then
emitting the new data with an updated batch index.
Larger-than-memory sort is not currently supported.

This is the option class for the "order_by" node factory.

Parameters
----------
sort_keys : sequence of (name, order) tuples
Names of field/column keys to sort the input on,
along with the order each field/column is sorted in.
Accepted values for `order` are "ascending", "descending".
Each field reference can be a string column name or expression.
null_placement : str, default "at_end"
Where nulls in input should be sorted, only applying to
columns/fields mentioned in `sort_keys`.
Accepted values are "at_start", "at_end".
"""

def __init__(self, sort_keys=(), *, null_placement="at_end"):
self._set_options(sort_keys, null_placement)


cdef class _HashJoinNodeOptions(ExecNodeOptions):

def _set_options(
Expand Down
4 changes: 4 additions & 0 deletions python/pyarrow/_compute.pxd
Original file line number Diff line number Diff line change
Expand Up @@ -64,3 +64,7 @@ cdef class Expression(_Weakrefable):
cdef CExpression _true

cdef CFieldRef _ensure_field_ref(value) except *

cdef CSortOrder unwrap_sort_order(order) except *

cdef CNullPlacement unwrap_null_placement(null_placement) except *
11 changes: 7 additions & 4 deletions python/pyarrow/_compute.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -1963,7 +1963,7 @@ cdef class _SortOptions(FunctionOptions):
cdef vector[CSortKey] c_sort_keys
for name, order in sort_keys:
c_sort_keys.push_back(
CSortKey(tobytes(name), unwrap_sort_order(order))
CSortKey(_ensure_field_ref(name), unwrap_sort_order(order))
)
self.wrapped.reset(new CSortOptions(
c_sort_keys, unwrap_null_placement(null_placement)))
Expand All @@ -1979,6 +1979,7 @@ class SortOptions(_SortOptions):
Names of field/column keys to sort the input on,
along with the order each field/column is sorted in.
Accepted values for `order` are "ascending", "descending".
The field name can be a string column name or expression.
null_placement : str, default "at_end"
Where nulls in input should be sorted, only applying to
columns/fields mentioned in `sort_keys`.
Expand All @@ -1994,7 +1995,7 @@ cdef class _SelectKOptions(FunctionOptions):
cdef vector[CSortKey] c_sort_keys
for name, order in sort_keys:
c_sort_keys.push_back(
CSortKey(tobytes(name), unwrap_sort_order(order))
CSortKey(_ensure_field_ref(name), unwrap_sort_order(order))
)
self.wrapped.reset(new CSelectKOptions(k, c_sort_keys))

Expand All @@ -2013,6 +2014,7 @@ class SelectKOptions(_SelectKOptions):
Names of field/column keys to sort the input on,
along with the order each field/column is sorted in.
Accepted values for `order` are "ascending", "descending".
The field name can be a string column name or expression.
"""

def __init__(self, k, sort_keys):
Expand Down Expand Up @@ -2183,12 +2185,12 @@ cdef class _RankOptions(FunctionOptions):
cdef vector[CSortKey] c_sort_keys
if isinstance(sort_keys, str):
c_sort_keys.push_back(
CSortKey(tobytes(""), unwrap_sort_order(sort_keys))
CSortKey(_ensure_field_ref(""), unwrap_sort_order(sort_keys))
)
else:
for name, order in sort_keys:
c_sort_keys.push_back(
CSortKey(tobytes(name), unwrap_sort_order(order))
CSortKey(_ensure_field_ref(name), unwrap_sort_order(order))
)
try:
self.wrapped.reset(
Expand All @@ -2210,6 +2212,7 @@ class RankOptions(_RankOptions):
Names of field/column keys to sort the input on,
along with the order each field/column is sorted in.
Accepted values for `order` are "ascending", "descending".
The field name can be a string column name or expression.
Alternatively, one can simply pass "ascending" or "descending" as a string
if the input is array-like.
null_placement : str, default "at_end"
Expand Down
10 changes: 8 additions & 2 deletions python/pyarrow/includes/libarrow.pxd
Original file line number Diff line number Diff line change
Expand Up @@ -2361,10 +2361,13 @@ cdef extern from "arrow/compute/api.h" namespace "arrow::compute" nogil:
CNullPlacement null_placement

cdef cppclass CSortKey" arrow::compute::SortKey":
CSortKey(c_string name, CSortOrder order)
c_string name
CSortKey(CFieldRef target, CSortOrder order)
CFieldRef target
CSortOrder order

cdef cppclass COrdering" arrow::compute::Ordering":
COrdering(vector[CSortKey] sort_keys, CNullPlacement null_placement)

cdef cppclass CSortOptions \
"arrow::compute::SortOptions"(CFunctionOptions):
CSortOptions(vector[CSortKey] sort_keys, CNullPlacement)
Expand Down Expand Up @@ -2605,6 +2608,9 @@ cdef extern from "arrow/compute/exec/options.h" namespace "arrow::compute" nogil
COrderBySinkNodeOptions(vector[CSortOptions] options,
CAsyncExecBatchGenerator generator)

cdef cppclass COrderByNodeOptions "arrow::compute::OrderByNodeOptions"(CExecNodeOptions):
COrderByNodeOptions(COrdering ordering)

cdef cppclass CHashJoinNodeOptions "arrow::compute::HashJoinNodeOptions"(CExecNodeOptions):
CHashJoinNodeOptions(CJoinType, vector[CFieldRef] in_left_keys,
vector[CFieldRef] in_right_keys)
Expand Down
38 changes: 38 additions & 0 deletions python/pyarrow/tests/test_acero.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
FilterNodeOptions,
ProjectNodeOptions,
AggregateNodeOptions,
OrderByNodeOptions,
HashJoinNodeOptions,
Declaration,
)
Expand Down Expand Up @@ -237,6 +238,43 @@ def test_aggregate_hash():
_ = decl.to_table()


def test_order_by():
table = pa.table({'a': [1, 2, 3, 4], 'b': [1, 3, None, 2]})
table_source = Declaration("table_source", TableSourceNodeOptions(table))

ord_opts = OrderByNodeOptions([("b", "ascending")])
decl = Declaration.from_sequence([table_source, Declaration("order_by", ord_opts)])
result = decl.to_table()
expected = pa.table({"a": [1, 4, 2, 3], "b": [1, 2, 3, None]})
assert result.equals(expected)

ord_opts = OrderByNodeOptions([(field("b"), "descending")])
decl = Declaration.from_sequence([table_source, Declaration("order_by", ord_opts)])
result = decl.to_table()
expected = pa.table({"a": [2, 4, 1, 3], "b": [3, 2, 1, None]})
assert result.equals(expected)

ord_opts = OrderByNodeOptions([(1, "descending")], null_placement="at_start")
decl = Declaration.from_sequence([table_source, Declaration("order_by", ord_opts)])
result = decl.to_table()
expected = pa.table({"a": [3, 2, 4, 1], "b": [None, 3, 2, 1]})
assert result.equals(expected)

# emtpy ordering
ord_opts = OrderByNodeOptions([])
decl = Declaration.from_sequence([table_source, Declaration("order_by", ord_opts)])
with pytest.raises(
ValueError, match="`ordering` must be an explicit non-empty ordering"
):
_ = decl.to_table()

with pytest.raises(ValueError, match="\"decreasing\" is not a valid sort order"):
_ = OrderByNodeOptions([("b", "decreasing")])

with pytest.raises(ValueError, match="\"start\" is not a valid null placement"):
_ = OrderByNodeOptions([("b", "ascending")], null_placement="start")


def test_hash_join():
left = pa.table({'key': [1, 2, 3], 'a': [4, 5, 6]})
left_source = Declaration("table_source", options=TableSourceNodeOptions(left))
Expand Down
4 changes: 2 additions & 2 deletions python/pyarrow/tests/test_compute.py
Original file line number Diff line number Diff line change
Expand Up @@ -2400,7 +2400,7 @@ def validate_select_k(select_k_indices, tbl, sort_keys, stable_sort=False):
validate_select_k(result, table, sort_keys=[("a", "ascending")])

result = pc.select_k_unstable(
table, k=k, sort_keys=[("a", "ascending"), ("b", "ascending")])
table, k=k, sort_keys=[(pc.field("a"), "ascending"), ("b", "ascending")])
validate_select_k(
result, table, sort_keys=[("a", "ascending"), ("b", "ascending")])

Expand Down Expand Up @@ -2484,7 +2484,7 @@ def test_sort_indices_table():

result = pc.sort_indices(table, sort_keys=[("a", "ascending")])
assert result.to_pylist() == [3, 0, 1, 2]
result = pc.sort_indices(table, sort_keys=[("a", "ascending")],
result = pc.sort_indices(table, sort_keys=[(pc.field("a"), "ascending")],
null_placement="at_start")
assert result.to_pylist() == [2, 3, 0, 1]

Expand Down