From 8672fc5fdbee34eda27e2df4442ed0a4cf292f22 Mon Sep 17 00:00:00 2001 From: Joris Van den Bossche Date: Tue, 14 Mar 2023 12:12:52 +0100 Subject: [PATCH 1/2] add python bindings --- python/pyarrow/_acero.pyx | 50 +++++++++++++++++++++++++++- python/pyarrow/_compute.pxd | 4 +++ python/pyarrow/_compute.pyx | 8 ++--- python/pyarrow/includes/libarrow.pxd | 10 ++++-- python/pyarrow/tests/test_acero.py | 38 +++++++++++++++++++++ 5 files changed, 103 insertions(+), 7 deletions(-) diff --git a/python/pyarrow/_acero.pyx b/python/pyarrow/_acero.pyx index 411665b0b1df..522f4fd005c2 100644 --- a/python/pyarrow/_acero.pyx +++ b/python/pyarrow/_acero.pyx @@ -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): @@ -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( diff --git a/python/pyarrow/_compute.pxd b/python/pyarrow/_compute.pxd index da195f9d63d7..2dc0de2d0bfe 100644 --- a/python/pyarrow/_compute.pxd +++ b/python/pyarrow/_compute.pxd @@ -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 * diff --git a/python/pyarrow/_compute.pyx b/python/pyarrow/_compute.pyx index 0eed0564795d..5ad34c9ccc8c 100644 --- a/python/pyarrow/_compute.pyx +++ b/python/pyarrow/_compute.pyx @@ -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))) @@ -1994,7 +1994,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)) @@ -2183,12 +2183,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( diff --git a/python/pyarrow/includes/libarrow.pxd b/python/pyarrow/includes/libarrow.pxd index bc8c99770e5b..73f7294142b2 100644 --- a/python/pyarrow/includes/libarrow.pxd +++ b/python/pyarrow/includes/libarrow.pxd @@ -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) @@ -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) diff --git a/python/pyarrow/tests/test_acero.py b/python/pyarrow/tests/test_acero.py index a6d3a5bfd1e4..88d03f5dec6c 100644 --- a/python/pyarrow/tests/test_acero.py +++ b/python/pyarrow/tests/test_acero.py @@ -26,6 +26,7 @@ FilterNodeOptions, ProjectNodeOptions, AggregateNodeOptions, + OrderByNodeOptions, HashJoinNodeOptions, Declaration, ) @@ -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)) From 6de9ed23430a641362babe5387c998f494f227e5 Mon Sep 17 00:00:00 2001 From: Joris Van den Bossche Date: Wed, 22 Mar 2023 14:19:00 +0100 Subject: [PATCH 2/2] update compute docstrings and tests --- python/pyarrow/_compute.pyx | 3 +++ python/pyarrow/tests/test_compute.py | 4 ++-- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/python/pyarrow/_compute.pyx b/python/pyarrow/_compute.pyx index 5ad34c9ccc8c..cf9924baeee4 100644 --- a/python/pyarrow/_compute.pyx +++ b/python/pyarrow/_compute.pyx @@ -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`. @@ -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): @@ -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" diff --git a/python/pyarrow/tests/test_compute.py b/python/pyarrow/tests/test_compute.py index 9f615654d97e..92560e4070be 100644 --- a/python/pyarrow/tests/test_compute.py +++ b/python/pyarrow/tests/test_compute.py @@ -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")]) @@ -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]