Apache DataFusion SQL Query Engine
Expose DataFrame::sort (#469)
Krisztián Szűcsd0d677bb574c
diff --git a/python/Cargo.toml b/python/Cargo.tomlindex 070720554f..117190714e 100644--- a/python/Cargo.toml+++ b/python/Cargo.toml@@ -27,9 +27,10 @@ license = "Apache-2.0"edition = "2018"[dependencies]+libc = "0.2"tokio = { version = "1.0", features = ["macros", "rt", "rt-multi-thread", "sync"] }rand = "0.7"-pyo3 = { version = "0.12.1", features = ["extension-module"] }+pyo3 = { version = "0.13.2", features = ["extension-module"] }datafusion = { git = "https://github.com/apache/arrow-datafusion.git", rev = "2423ff0d" }[lib]diff --git a/python/src/dataframe.rs b/python/src/dataframe.rsindex f90a7cf2f0..66e6916b68 100644--- a/python/src/dataframe.rs+++ b/python/src/dataframe.rs@@ -93,6 +93,18 @@ impl DataFrame {})}+ /// Sort by specified sorting expressions+ fn sort(&self, exprs: Vec<expression::Expression>) -> PyResult<Self> {+ let exprs = exprs.into_iter().map(|e| e.expr);+ let builder = LogicalPlanBuilder::from(&self.plan);+ let builder = errors::wrap(builder.sort(exprs))?;+ let plan = errors::wrap(builder.build())?;+ Ok(DataFrame {+ ctx_state: self.ctx_state.clone(),+ plan,+ })+ }+/// Limits the plan to return at most `count` rowsfn limit(&self, count: usize) -> PyResult<Self> {let builder = LogicalPlanBuilder::from(&self.plan);diff --git a/python/src/expression.rs b/python/src/expression.rsindex 78ca6d7e59..4320b1d14c 100644--- a/python/src/expression.rs+++ b/python/src/expression.rs@@ -117,6 +117,14 @@ impl Expression {expr: self.expr.clone().alias(name),})}++ /// Create a sort expression from an existing expression.+ #[args(ascending = true, nulls_first = true)]+ pub fn sort(&self, ascending: bool, nulls_first: bool) -> PyResult<Expression> {+ Ok(Expression {+ expr: self.expr.clone().sort(ascending, nulls_first),+ })+ }}/// Represents a ScalarUDFdiff --git a/python/src/functions.rs b/python/src/functions.rsindex b51c76ba4b..f46dd3e0e5 100644--- a/python/src/functions.rs+++ b/python/src/functions.rs@@ -101,9 +101,17 @@ fn concat_ws(value: expression::Expression) -> expression::Expression {}#[pyfunction]-fn in_list(expr: expression::Expression, value: Vec<expression::Expression>, negated: bool) -> expression::Expression {- expression::Expression {- expr: logical_plan::in_list(expr.expr, value.into_iter().map(|x| x.expr).collect::<Vec<_>>(), negated),+fn in_list(+ expr: expression::Expression,+ value: Vec<expression::Expression>,+ negated: bool,+) -> expression::Expression {+ expression::Expression {+ expr: logical_plan::in_list(+ expr.expr,+ value.into_iter().map(|x| x.expr).collect::<Vec<_>>(),+ negated,+ ),}}diff --git a/python/src/to_py.rs b/python/src/to_py.rsindex deeb971989..ff03e03325 100644--- a/python/src/to_py.rs+++ b/python/src/to_py.rs@@ -15,8 +15,9 @@// specific language governing permissions and limitations// under the License.+use libc::uintptr_t;use pyo3::prelude::*;-use pyo3::{libc::uintptr_t, PyErr};+use pyo3::PyErr;use std::convert::From;diff --git a/python/src/to_rust.rs b/python/src/to_rust.rsindex d8f2307a49..2e3f7f05ec 100644--- a/python/src/to_rust.rs+++ b/python/src/to_rust.rs@@ -25,7 +25,8 @@ use datafusion::arrow::{record_batch::RecordBatch,};use datafusion::scalar::ScalarValue;-use pyo3::{libc::uintptr_t, prelude::*};+use libc::uintptr_t;+use pyo3::prelude::*;use crate::{errors, types::PyDataType};diff --git a/python/tests/test_df.py b/python/tests/test_df.pyindex 520d4e6a54..2da23f908d 100644--- a/python/tests/test_df.py+++ b/python/tests/test_df.py@@ -17,7 +17,7 @@import unittest-import pyarrow+import pyarrow as paimport datafusionf = datafusion.functions@@ -28,8 +28,8 @@ class TestCase(unittest.TestCase):ctx = datafusion.ExecutionContext()# create a RecordBatch and a new DataFrame from it- batch = pyarrow.RecordBatch.from_arrays(- [pyarrow.array([1, 2, 3]), pyarrow.array([4, 5, 6])],+ batch = pa.RecordBatch.from_arrays(+ [pa.array([1, 2, 3]), pa.array([4, 5, 6])],names=["a", "b"],)return ctx.create_dataframe([[batch]])@@ -45,8 +45,8 @@ class TestCase(unittest.TestCase):# execute and collect the first (and only) batchresult = df.collect()[0]- self.assertEqual(result.column(0), pyarrow.array([5, 7, 9]))- self.assertEqual(result.column(1), pyarrow.array([-3, -3, -3]))+ self.assertEqual(result.column(0), pa.array([5, 7, 9]))+ self.assertEqual(result.column(1), pa.array([-3, -3, -3]))def test_filter(self):df = self._prepare()@@ -61,8 +61,18 @@ class TestCase(unittest.TestCase):# execute and collect the first (and only) batchresult = df.collect()[0]- self.assertEqual(result.column(0), pyarrow.array([9]))- self.assertEqual(result.column(1), pyarrow.array([-3]))+ self.assertEqual(result.column(0), pa.array([9]))+ self.assertEqual(result.column(1), pa.array([-3]))++ def test_sort(self):+ df = self._prepare()+ df = df.sort([+ f.col("b").sort(ascending=False)+ ])++ table = pa.Table.from_batches(df.collect())+ expected = {'a': [3, 2, 1], 'b': [6, 5, 4]}+ self.assertEqual(table.to_pydict(), expected)def test_limit(self):df = self._prepare()@@ -78,38 +88,33 @@ class TestCase(unittest.TestCase):def test_udf(self):df = self._prepare()- # is_null is a pyarrow function over arrays- udf = f.udf(lambda x: x.is_null(), [pyarrow.int64()], pyarrow.bool_())+ # is_null is a pa function over arrays+ udf = f.udf(lambda x: x.is_null(), [pa.int64()], pa.bool_())df = df.select(udf(f.col("a")))- self.assertEqual(df.collect()[0].column(0), pyarrow.array([False, False, False]))+ self.assertEqual(df.collect()[0].column(0), pa.array([False, False, False]))def test_join(self):ctx = datafusion.ExecutionContext()- batch = pyarrow.RecordBatch.from_arrays(- [pyarrow.array([1, 2, 3]), pyarrow.array([4, 5, 6])],+ batch = pa.RecordBatch.from_arrays(+ [pa.array([1, 2, 3]), pa.array([4, 5, 6])],names=["a", "b"],)df = ctx.create_dataframe([[batch]])- batch = pyarrow.RecordBatch.from_arrays(- [pyarrow.array([1, 2]), pyarrow.array([8, 10])],+ batch = pa.RecordBatch.from_arrays(+ [pa.array([1, 2]), pa.array([8, 10])],names=["a", "c"],)df1 = ctx.create_dataframe([[batch]])df = df.join(df1, on="a", how="inner")+ df = df.sort([+ f.col("a").sort(ascending=True)+ ])+ table = pa.Table.from_batches(df.collect())- # execute and collect the first (and only) batch- batch = df.collect()[0]-- if batch.column(0) == pyarrow.array([1, 2]):- self.assertEqual(batch.column(0), pyarrow.array([1, 2]))- self.assertEqual(batch.column(1), pyarrow.array([8, 10]))- self.assertEqual(batch.column(2), pyarrow.array([4, 5]))- else:- self.assertEqual(batch.column(0), pyarrow.array([2, 1]))- self.assertEqual(batch.column(1), pyarrow.array([10, 8]))- self.assertEqual(batch.column(2), pyarrow.array([5, 4]))+ expected = {'a': [1, 2], 'c': [8, 10], 'b': [4, 5]}+ self.assertEqual(table.to_pydict(), expected)