You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@arrow.apache.org by GitBox <gi...@apache.org> on 2022/06/16 22:35:05 UTC

[GitHub] [arrow-datafusion] andygrove opened a new pull request, #2740: Add optimizer rule to filter out null join keys

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

   # 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 https://github.com/apache/arrow-datafusion/issues/2739
   
    # 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.  
   -->
   
   Performance optimization
   
   # 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.
   -->
   
   New optimizer rule + tests
   
   # Are there any user-facing changes?
   <!--
   If there are user-facing changes then we may require documentation to be updated before approving the PR.
   -->
   
   Yes, plans may look different
   
   <!--
   If there are any breaking changes to public APIs, please add the `api change` label.
   -->


-- 
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 #2740: Add optimizer rule to filter out null keys before a join

Posted by GitBox <gi...@apache.org>.
alamb commented on PR #2740:
URL: https://github.com/apache/arrow-datafusion/pull/2740#issuecomment-1159453162

   This looks very cool -- thanks @andygrove @xudong963  and @jdye64 👍  I plan to review this tomorrow morning but there is no need to hold up merging. 


-- 
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] andygrove merged pull request #2740: Add optimizer rule to filter out null keys before a join

Posted by GitBox <gi...@apache.org>.
andygrove merged PR #2740:
URL: https://github.com/apache/arrow-datafusion/pull/2740


-- 
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] codecov-commenter commented on pull request #2740: Add optimizer rule to filter out null join keys

Posted by GitBox <gi...@apache.org>.
codecov-commenter commented on PR #2740:
URL: https://github.com/apache/arrow-datafusion/pull/2740#issuecomment-1158242340

   # [Codecov](https://codecov.io/gh/apache/arrow-datafusion/pull/2740?src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation) Report
   > Merging [#2740](https://codecov.io/gh/apache/arrow-datafusion/pull/2740?src=pr&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation) (f8d8213) into [master](https://codecov.io/gh/apache/arrow-datafusion/commit/06fa71ad32dfaf9b51492dfe7c9350d1cd7163f8?el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation) (06fa71a) will **increase** coverage by `0.03%`.
   > The diff coverage is `99.09%`.
   
   ```diff
   @@            Coverage Diff             @@
   ##           master    #2740      +/-   ##
   ==========================================
   + Coverage   84.92%   84.95%   +0.03%     
   ==========================================
     Files         270      271       +1     
     Lines       47892    48025     +133     
   ==========================================
   + Hits        40672    40802     +130     
   - Misses       7220     7223       +3     
   ```
   
   
   | [Impacted Files](https://codecov.io/gh/apache/arrow-datafusion/pull/2740?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation) | Coverage Δ | |
   |---|---|---|
   | [datafusion/core/src/execution/context.rs](https://codecov.io/gh/apache/arrow-datafusion/pull/2740/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-ZGF0YWZ1c2lvbi9jb3JlL3NyYy9leGVjdXRpb24vY29udGV4dC5ycw==) | `78.64% <ø> (ø)` | |
   | [datafusion/optimizer/src/filter\_null\_join\_keys.rs](https://codecov.io/gh/apache/arrow-datafusion/pull/2740/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-ZGF0YWZ1c2lvbi9vcHRpbWl6ZXIvc3JjL2ZpbHRlcl9udWxsX2pvaW5fa2V5cy5ycw==) | `99.09% <99.09%> (ø)` | |
   | [datafusion/expr/src/logical\_plan/plan.rs](https://codecov.io/gh/apache/arrow-datafusion/pull/2740/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-ZGF0YWZ1c2lvbi9leHByL3NyYy9sb2dpY2FsX3BsYW4vcGxhbi5ycw==) | `73.71% <0.00%> (-0.60%)` | :arrow_down: |
   | [datafusion/optimizer/src/utils.rs](https://codecov.io/gh/apache/arrow-datafusion/pull/2740/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-ZGF0YWZ1c2lvbi9vcHRpbWl6ZXIvc3JjL3V0aWxzLnJz) | `33.68% <0.00%> (-0.53%)` | :arrow_down: |
   | [datafusion/expr/src/logical\_plan/builder.rs](https://codecov.io/gh/apache/arrow-datafusion/pull/2740/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-ZGF0YWZ1c2lvbi9leHByL3NyYy9sb2dpY2FsX3BsYW4vYnVpbGRlci5ycw==) | `89.51% <0.00%> (+0.18%)` | :arrow_up: |
   | [datafusion/expr/src/window\_frame.rs](https://codecov.io/gh/apache/arrow-datafusion/pull/2740/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-ZGF0YWZ1c2lvbi9leHByL3NyYy93aW5kb3dfZnJhbWUucnM=) | `93.27% <0.00%> (+0.84%)` | :arrow_up: |
   | [datafusion/data-access/src/object\_store/local.rs](https://codecov.io/gh/apache/arrow-datafusion/pull/2740/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-ZGF0YWZ1c2lvbi9kYXRhLWFjY2Vzcy9zcmMvb2JqZWN0X3N0b3JlL2xvY2FsLnJz) | `89.03% <0.00%> (+1.91%)` | :arrow_up: |
   
   ------
   
   [Continue to review full report at Codecov](https://codecov.io/gh/apache/arrow-datafusion/pull/2740?src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation).
   > **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation)
   > `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
   > Powered by [Codecov](https://codecov.io/gh/apache/arrow-datafusion/pull/2740?src=pr&el=footer&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation). Last update [06fa71a...f8d8213](https://codecov.io/gh/apache/arrow-datafusion/pull/2740?src=pr&el=lastupdated&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation).
   


-- 
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 #2740: Add optimizer rule to filter out null keys before a join

Posted by GitBox <gi...@apache.org>.
alamb commented on code in PR #2740:
URL: https://github.com/apache/arrow-datafusion/pull/2740#discussion_r901100179


##########
datafusion/optimizer/src/filter_null_join_keys.rs:
##########
@@ -0,0 +1,247 @@
+// 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.
+
+//! The FilterNullJoinKeys rule will identify inner joins with equi-join conditions
+//! where the join key is nullable on one side and non-nullable on the other side
+//! and then insert an `IsNotNull` filter on the nullable side since null values
+//! can never match.
+
+use crate::{utils, OptimizerConfig, OptimizerRule};
+use datafusion_common::{Column, DFField, DFSchemaRef};
+use datafusion_expr::{
+    and, logical_plan::Filter, logical_plan::JoinType, Expr, LogicalPlan,
+};
+use std::sync::Arc;
+
+/// The FilterNullJoinKeys rule will identify inner joins with equi-join conditions
+/// where the join key is nullable on one side and non-nullable on the other side
+/// and then insert an `IsNotNull` filter on the nullable side since null values
+/// can never match.
+#[derive(Default)]
+pub struct FilterNullJoinKeys {}
+
+impl OptimizerRule for FilterNullJoinKeys {
+    fn optimize(
+        &self,
+        plan: &LogicalPlan,
+        optimizer_config: &OptimizerConfig,
+    ) -> datafusion_common::Result<LogicalPlan> {
+        match plan {
+            LogicalPlan::Join(join) if join.join_type == JoinType::Inner => {
+                // recurse down first and optimize inputs
+                let mut join = join.clone();
+                join.left = Arc::new(self.optimize(&join.left, optimizer_config)?);
+                join.right = Arc::new(self.optimize(&join.right, optimizer_config)?);
+
+                let left_schema = join.left.schema();
+                let right_schema = join.right.schema();
+
+                let mut left_filters = vec![];
+                let mut right_filters = vec![];
+
+                for (l, r) in &join.on {
+                    if let Some((left_field, right_field)) =
+                        resolve_join_key_pair(left_schema, right_schema, l, r)
+                    {
+                        if left_field.is_nullable() && !right_field.is_nullable() {
+                            left_filters.push(l.clone());
+                        } else if !left_field.is_nullable() && right_field.is_nullable() {
+                            right_filters.push(r.clone());
+                        }
+                    }
+                }
+
+                if !left_filters.is_empty() {
+                    let predicate = create_not_null_predicate(left_filters);
+                    join.left = Arc::new(LogicalPlan::Filter(Filter {
+                        predicate,
+                        input: join.left.clone(),
+                    }));
+                }
+                if !right_filters.is_empty() {
+                    let predicate = create_not_null_predicate(right_filters);
+                    join.right = Arc::new(LogicalPlan::Filter(Filter {
+                        predicate,
+                        input: join.right.clone(),
+                    }));
+                }
+                Ok(LogicalPlan::Join(join))
+            }
+            _ => {
+                // Apply the optimization to all inputs of the plan
+                utils::optimize_children(self, plan, optimizer_config)
+            }
+        }
+    }
+
+    fn name(&self) -> &str {
+        "FilterNullJoinKeys"
+    }
+}
+
+fn create_not_null_predicate(columns: Vec<Column>) -> Expr {
+    let not_null_exprs: Vec<Expr> = columns
+        .into_iter()
+        .map(|c| Expr::IsNotNull(Box::new(Expr::Column(c))))
+        .collect();
+    // combine the IsNotNull expressions with AND
+    not_null_exprs
+        .iter()
+        .skip(1)
+        .fold(not_null_exprs[0].clone(), |a, b| and(a, b.clone()))
+}
+
+fn resolve_join_key_pair(
+    left_schema: &DFSchemaRef,
+    right_schema: &DFSchemaRef,
+    c1: &Column,
+    c2: &Column,
+) -> Option<(DFField, DFField)> {
+    resolve_fields(left_schema, right_schema, c1, c2)
+        .or_else(|| resolve_fields(left_schema, right_schema, c2, c1))
+}
+
+fn resolve_fields(
+    left_schema: &DFSchemaRef,
+    right_schema: &DFSchemaRef,
+    c1: &Column,
+    c2: &Column,
+) -> Option<(DFField, DFField)> {
+    match (
+        left_schema.index_of_column(c1),
+        right_schema.index_of_column(c2),
+    ) {
+        (Ok(left_index), Ok(right_index)) => {
+            let left_field = left_schema.field(left_index);
+            let right_field = right_schema.field(right_index);
+            Some((left_field.clone(), right_field.clone()))
+        }
+        _ => None,
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use arrow::datatypes::{DataType, Field, Schema};
+    use datafusion_common::{Column, Result};
+    use datafusion_expr::logical_plan::table_scan;
+    use datafusion_expr::{logical_plan::JoinType, LogicalPlanBuilder};
+
+    fn optimize_plan(plan: &LogicalPlan) -> LogicalPlan {
+        let rule = FilterNullJoinKeys::default();
+        rule.optimize(plan, &OptimizerConfig::new())
+            .expect("failed to optimize plan")
+    }
+
+    fn assert_optimized_plan_eq(plan: &LogicalPlan, expected: &str) {
+        let optimized_plan = optimize_plan(plan);
+        let formatted_plan = format!("{:?}", optimized_plan);
+        assert_eq!(formatted_plan, expected);
+    }
+
+    #[test]
+    fn left_nullable() -> Result<()> {

Review Comment:
   Other possible tests: 
   1. join on `t1.optional_id = t2.optional_id` (would expect filters on both join inputs)
   2. `LEFT join on t1.optional = t2.id1 (negative test, expect nothing)



##########
datafusion/optimizer/src/filter_null_join_keys.rs:
##########
@@ -0,0 +1,247 @@
+// 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.
+
+//! The FilterNullJoinKeys rule will identify inner joins with equi-join conditions
+//! where the join key is nullable on one side and non-nullable on the other side
+//! and then insert an `IsNotNull` filter on the nullable side since null values
+//! can never match.

Review Comment:
   I think this could also push `IsNotNull` filters when both sides were nullable 🤔 
   



-- 
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