You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@arrow.apache.org by "marshauf (via GitHub)" <gi...@apache.org> on 2023/06/18 10:47:52 UTC

[GitHub] [arrow-datafusion] marshauf opened a new pull request, #6713: Add async UDF example

marshauf opened a new pull request, #6713:
URL: https://github.com/apache/arrow-datafusion/pull/6713

   # Which issue does this PR close?
   
   <!--
   We generally require a GitHub issue to be filed for all bug fixes and enhancements and this helps us generate change logs for our releases. You can link an issue to this PR using the GitHub syntax. For example `Closes #123` indicates that this PR will close issue #123.
   -->
   
   Closes #6518.
   
   # Rationale for this change
   
   <!--
    Why are you proposing this change? If this is already explained clearly in the issue then this section is not needed.
    Explaining clearly why changes are proposed helps reviewers understand your changes and offer better suggestions for fixes.  
   -->
   
   This change provides an example on how to replace a ScalarUDF node with a user defined extension node. The node calls an async function on execution.
   
   # What changes are included in this PR?
   
   <!--
   There is no need to duplicate the description in the issue here but it is sometimes worth providing a summary of the individual changes in this PR.
   -->
   
   It only adds another example which can be run with `cargo run --example async_udf`.
   
   # Are these changes tested?
   
   <!--
   We typically require tests for all PRs in order to:
   1. Prevent the code from being accidentally broken by subsequent changes
   2. Serve as another way to document the expected behavior of the code
   
   If tests are not included in your PR, please explain why (for example, are they covered by existing tests)?
   -->
   
   I ran `cargo run --example async_udf` which ran the example to completion without an error. Example has no external dependencies towards its environment.
   
   # Are there any user-facing changes?
   
   No user facing changes.
   
   <!--
   If there are user-facing changes then we may require documentation to be updated before approving the PR.
   -->
   
   <!--
   If there are any breaking changes to public APIs, please add the `api change` label.
   -->
   
   # TODO
   
   At the moment the optimizer rule replaces the complete Projection. I would like to just replace the Expr::ScalarUDF with a Expr::ScalarSubquery or something similar which allows me to host the user defined extension node.
   An example implementation is `rewrite_expr`, but Expr::ScalarSubquery doesn't support LogicalPlan::Extension as a subquery. A function returns an error at https://github.com/apache/arrow-datafusion/blob/main/datafusion/optimizer/src/scalar_subquery_to_join.rs#L219-L219 because https://github.com/apache/arrow-datafusion/blob/main/datafusion/expr/src/logical_plan/plan.rs#L411-L411 returns None for LogicalPlan::Extension.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-datafusion] alamb commented on pull request #6713: Add `async` UDF example

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #6713:
URL: https://github.com/apache/arrow-datafusion/pull/6713#issuecomment-1681117530

   Marking as draft to signify it is not waiting on review


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-datafusion] marshauf commented on a diff in pull request #6713: Add `async` UDF example

Posted by "marshauf (via GitHub)" <gi...@apache.org>.
marshauf commented on code in PR #6713:
URL: https://github.com/apache/arrow-datafusion/pull/6713#discussion_r1235404019


##########
datafusion-examples/examples/async_udf.rs:
##########
@@ -0,0 +1,405 @@
+// 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.
+
+use arrow_schema::{Field, Schema, SchemaRef};
+use async_trait::async_trait;
+use datafusion::{
+    arrow::{
+        array::{ArrayRef, Float32Array, Float64Array},
+        datatypes::DataType,
+        record_batch::RecordBatch,
+    },
+    execution::{
+        context::{QueryPlanner, SessionState},
+        runtime_env::RuntimeEnv,
+        TaskContext,
+    },
+    logical_expr::Volatility,
+    physical_expr::PhysicalSortExpr,
+    physical_plan::{
+        stream::RecordBatchStreamAdapter, DisplayFormatType, Distribution, ExecutionPlan,
+        Partitioning, SendableRecordBatchStream, Statistics,
+    },
+    physical_planner::{DefaultPhysicalPlanner, ExtensionPlanner, PhysicalPlanner},
+};
+
+use datafusion::prelude::*;
+use datafusion::{error::Result, physical_plan::functions::make_scalar_function};
+use datafusion_common::{
+    cast::{as_float32_array, as_float64_array},
+    tree_node::{Transformed, TreeNode},
+    DFSchemaRef, DataFusionError,
+};
+use datafusion_expr::{
+    expr::ScalarUDF, Extension, LogicalPlan, Subquery, UserDefinedLogicalNode,
+    UserDefinedLogicalNodeCore,
+};
+use datafusion_optimizer::{optimize_children, OptimizerConfig, OptimizerRule};
+use std::{
+    any::Any,
+    fmt::{self, Debug},
+    sync::Arc,
+};
+
+use futures::{FutureExt, StreamExt};
+
+// create local execution context with an in-memory table

Review Comment:
   I agree. I updated the documentation. I am just beginning to understand how DataFusion works and hope the wording is correct.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-datafusion] alamb commented on pull request #6713: Add `async` UDF example

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #6713:
URL: https://github.com/apache/arrow-datafusion/pull/6713#issuecomment-1599583338

   > @alamb can you help me with the task in the TODO section, please.
   I would like to keep the Projection node and just replace the ScalarUDF Expr with something which can host an Extension. I hoped a SubQuery would work, but it seems to not work/be supported.
   
   
   Yes, I will be happy to -- I may not have time until later in this week however. 


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add `async` UDF example [datafusion]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #6713:
URL: https://github.com/apache/datafusion/pull/6713#issuecomment-2094543917

   Thank you for your contribution. Unfortunately, this pull request is stale because it has been open 60 days with no activity. Please remove the stale label or comment or this will be closed in 7 days.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


[GitHub] [arrow-datafusion] marshauf commented on a diff in pull request #6713: Add `async` UDF example

Posted by "marshauf (via GitHub)" <gi...@apache.org>.
marshauf commented on code in PR #6713:
URL: https://github.com/apache/arrow-datafusion/pull/6713#discussion_r1235415776


##########
datafusion-examples/examples/async_udf.rs:
##########
@@ -0,0 +1,405 @@
+// 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.
+
+use arrow_schema::{Field, Schema, SchemaRef};
+use async_trait::async_trait;
+use datafusion::{
+    arrow::{
+        array::{ArrayRef, Float32Array, Float64Array},
+        datatypes::DataType,
+        record_batch::RecordBatch,
+    },
+    execution::{
+        context::{QueryPlanner, SessionState},
+        runtime_env::RuntimeEnv,
+        TaskContext,
+    },
+    logical_expr::Volatility,
+    physical_expr::PhysicalSortExpr,
+    physical_plan::{
+        stream::RecordBatchStreamAdapter, DisplayFormatType, Distribution, ExecutionPlan,
+        Partitioning, SendableRecordBatchStream, Statistics,
+    },
+    physical_planner::{DefaultPhysicalPlanner, ExtensionPlanner, PhysicalPlanner},
+};
+
+use datafusion::prelude::*;
+use datafusion::{error::Result, physical_plan::functions::make_scalar_function};
+use datafusion_common::{
+    cast::{as_float32_array, as_float64_array},
+    tree_node::{Transformed, TreeNode},
+    DFSchemaRef, DataFusionError,
+};
+use datafusion_expr::{
+    expr::ScalarUDF, Extension, LogicalPlan, Subquery, UserDefinedLogicalNode,
+    UserDefinedLogicalNodeCore,
+};
+use datafusion_optimizer::{optimize_children, OptimizerConfig, OptimizerRule};
+use std::{
+    any::Any,
+    fmt::{self, Debug},
+    sync::Arc,
+};
+
+use futures::{FutureExt, StreamExt};
+
+// create local execution context with an in-memory table
+fn create_context() -> Result<SessionContext> {
+    // define a schema.
+    let schema = Arc::new(Schema::new(vec![
+        Field::new("a", DataType::Float32, false),
+        Field::new("b", DataType::Float64, false),
+    ]));
+
+    // define data.
+    let batch = RecordBatch::try_new(
+        schema,
+        vec![
+            Arc::new(Float32Array::from(vec![2.1, 3.1, 4.1, 5.1])),
+            Arc::new(Float64Array::from(vec![1.0, 2.0, 3.0, 4.0])),
+        ],
+    )?;
+
+    // declare a state with a query planner and an optimizer rule
+    let config = SessionConfig::new();
+    let runtime = Arc::new(RuntimeEnv::default());
+    let state = SessionState::with_config_rt(config, runtime)
+        .with_query_planner(Arc::new(PowQueryPlanner {}))
+        .add_optimizer_rule(Arc::new(PowOptimizerRule {}));
+
+    // declare a new context. In spark API, this corresponds to a new spark SQLsession
+    let ctx = SessionContext::with_state(state);
+
+    // declare a table in memory. In spark API, this corresponds to createDataFrame(...).
+    ctx.register_batch("t", batch)?;
+    Ok(ctx)
+}
+
+// pow is similar to the pow function in simple_udf example

Review Comment:
   I think the example is already complex and long. I would also like to avoid dependencies on IO, especially network.
   What do you think about sending data from main to the UDF via a channel? Tokio sync is already a dev dependency.
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-datafusion] alamb commented on pull request #6713: Add `async` UDF example

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #6713:
URL: https://github.com/apache/arrow-datafusion/pull/6713#issuecomment-1604453153

   I have not forgotten about this -- I hope/plan to spend time on the weekend 


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-datafusion] alamb commented on a diff in pull request #6713: Add async UDF example

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #6713:
URL: https://github.com/apache/arrow-datafusion/pull/6713#discussion_r1234144367


##########
datafusion-examples/examples/async_udf.rs:
##########
@@ -0,0 +1,405 @@
+// 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.
+
+use arrow_schema::{Field, Schema, SchemaRef};
+use async_trait::async_trait;
+use datafusion::{
+    arrow::{
+        array::{ArrayRef, Float32Array, Float64Array},
+        datatypes::DataType,
+        record_batch::RecordBatch,
+    },
+    execution::{
+        context::{QueryPlanner, SessionState},
+        runtime_env::RuntimeEnv,
+        TaskContext,
+    },
+    logical_expr::Volatility,
+    physical_expr::PhysicalSortExpr,
+    physical_plan::{
+        stream::RecordBatchStreamAdapter, DisplayFormatType, Distribution, ExecutionPlan,
+        Partitioning, SendableRecordBatchStream, Statistics,
+    },
+    physical_planner::{DefaultPhysicalPlanner, ExtensionPlanner, PhysicalPlanner},
+};
+
+use datafusion::prelude::*;
+use datafusion::{error::Result, physical_plan::functions::make_scalar_function};
+use datafusion_common::{
+    cast::{as_float32_array, as_float64_array},
+    tree_node::{Transformed, TreeNode},
+    DFSchemaRef, DataFusionError,
+};
+use datafusion_expr::{
+    expr::ScalarUDF, Extension, LogicalPlan, Subquery, UserDefinedLogicalNode,
+    UserDefinedLogicalNodeCore,
+};
+use datafusion_optimizer::{optimize_children, OptimizerConfig, OptimizerRule};
+use std::{
+    any::Any,
+    fmt::{self, Debug},
+    sync::Arc,
+};
+
+use futures::{FutureExt, StreamExt};
+
+// create local execution context with an in-memory table
+fn create_context() -> Result<SessionContext> {
+    // define a schema.
+    let schema = Arc::new(Schema::new(vec![
+        Field::new("a", DataType::Float32, false),
+        Field::new("b", DataType::Float64, false),
+    ]));
+
+    // define data.
+    let batch = RecordBatch::try_new(
+        schema,
+        vec![
+            Arc::new(Float32Array::from(vec![2.1, 3.1, 4.1, 5.1])),
+            Arc::new(Float64Array::from(vec![1.0, 2.0, 3.0, 4.0])),
+        ],
+    )?;
+
+    // declare a state with a query planner and an optimizer rule
+    let config = SessionConfig::new();
+    let runtime = Arc::new(RuntimeEnv::default());
+    let state = SessionState::with_config_rt(config, runtime)
+        .with_query_planner(Arc::new(PowQueryPlanner {}))
+        .add_optimizer_rule(Arc::new(PowOptimizerRule {}));
+
+    // declare a new context. In spark API, this corresponds to a new spark SQLsession
+    let ctx = SessionContext::with_state(state);
+
+    // declare a table in memory. In spark API, this corresponds to createDataFrame(...).
+    ctx.register_batch("t", batch)?;
+    Ok(ctx)
+}
+
+// pow is similar to the pow function in simple_udf example

Review Comment:
   Thank you @marshauf  -- really appreciated.
   
   I wonder what you would think about updating this example to be something slightly more realistic, like a UDF like "fetch_url" that gets a string as an argument and then "fetch"es some data remotely (which we would mock out for the example)?
   
   I can help update the PR if you like. 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-datafusion] marshauf commented on pull request #6713: Add `async` UDF example

Posted by "marshauf (via GitHub)" <gi...@apache.org>.
marshauf commented on PR #6713:
URL: https://github.com/apache/arrow-datafusion/pull/6713#issuecomment-1598993101

   @alamb can you help me with the task in the TODO section, please.
   I would like to keep the Projection node and just replace the ScalarUDF Expr with something which can host an Extension. I hoped a SubQuery would work, but it seems to not work/be supported.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-datafusion] alamb commented on a diff in pull request #6713: Add async UDF example

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #6713:
URL: https://github.com/apache/arrow-datafusion/pull/6713#discussion_r1234147388


##########
datafusion-examples/examples/async_udf.rs:
##########
@@ -0,0 +1,405 @@
+// 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.
+
+use arrow_schema::{Field, Schema, SchemaRef};
+use async_trait::async_trait;
+use datafusion::{
+    arrow::{
+        array::{ArrayRef, Float32Array, Float64Array},
+        datatypes::DataType,
+        record_batch::RecordBatch,
+    },
+    execution::{
+        context::{QueryPlanner, SessionState},
+        runtime_env::RuntimeEnv,
+        TaskContext,
+    },
+    logical_expr::Volatility,
+    physical_expr::PhysicalSortExpr,
+    physical_plan::{
+        stream::RecordBatchStreamAdapter, DisplayFormatType, Distribution, ExecutionPlan,
+        Partitioning, SendableRecordBatchStream, Statistics,
+    },
+    physical_planner::{DefaultPhysicalPlanner, ExtensionPlanner, PhysicalPlanner},
+};
+
+use datafusion::prelude::*;
+use datafusion::{error::Result, physical_plan::functions::make_scalar_function};
+use datafusion_common::{
+    cast::{as_float32_array, as_float64_array},
+    tree_node::{Transformed, TreeNode},
+    DFSchemaRef, DataFusionError,
+};
+use datafusion_expr::{
+    expr::ScalarUDF, Extension, LogicalPlan, Subquery, UserDefinedLogicalNode,
+    UserDefinedLogicalNodeCore,
+};
+use datafusion_optimizer::{optimize_children, OptimizerConfig, OptimizerRule};
+use std::{
+    any::Any,
+    fmt::{self, Debug},
+    sync::Arc,
+};
+
+use futures::{FutureExt, StreamExt};
+
+// create local execution context with an in-memory table

Review Comment:
   I think it would help in this file somewhere to give the larger context -- namely that this example is showing how to use the datafusion extension points (user defined nodes, and rewriters) to implement an arbitrary user defined asynchronous table function.
   
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org