You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@ignite.apache.org by "zstan (via GitHub)" <gi...@apache.org> on 2025/02/11 10:08:50 UTC

[PR] IGNITE-23969 Sql. Improve predicate selectivity estimation [ignite-3]

zstan opened a new pull request, #5211:
URL: https://github.com/apache/ignite-3/pull/5211

   Thank you for submitting the pull request.
   
   To streamline the review process of the patch and ensure better code quality
   we ask both an author and a reviewer to verify the following:
   
   ### The Review Checklist
   - [ ] **Formal criteria:** TC status, codestyle, mandatory documentation. Also make sure to complete the following:  
   \- There is a single JIRA ticket related to the pull request.  
   \- The web-link to the pull request is attached to the JIRA ticket.  
   \- The JIRA ticket has the Patch Available state.  
   \- The description of the JIRA ticket explains WHAT was made, WHY and HOW.  
   \- The pull request title is treated as the final commit message. The following pattern must be used: IGNITE-XXXX Change summary where XXXX - number of JIRA issue.
   - [ ] **Design:** new code conforms with the design principles of the components it is added to.
   - [ ] **Patch quality:** patch cannot be split into smaller pieces, its size must be reasonable.
   - [ ] **Code quality:** code is clean and readable, necessary developer documentation is added if needed.
   - [ ] **Tests code quality:** test set covers positive/negative scenarios, happy/edge cases. Tests are effective in terms of execution time and resources.
   
   ### Notes
   - [Apache Ignite Coding Guidelines](https://cwiki.apache.org/confluence/display/IGNITE/Java+Code+Style+Guide)


-- 
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: notifications-unsubscribe@ignite.apache.org

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


Re: [PR] IGNITE-23969 Sql. Improve predicate selectivity estimation [ignite-3]

Posted by "zstan (via GitHub)" <gi...@apache.org>.
zstan commented on code in PR #5211:
URL: https://github.com/apache/ignite-3/pull/5211#discussion_r1954225866


##########
modules/sql-engine/src/main/java/org/apache/ignite/internal/sql/engine/metadata/IgniteMdSelectivity.java:
##########
@@ -17,49 +17,226 @@
 
 package org.apache.ignite.internal.sql.engine.metadata;
 
+import static org.apache.calcite.rex.RexUtil.expandSearch;
+
+import com.google.common.collect.ImmutableList;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import org.apache.calcite.plan.RelOptUtil;
 import org.apache.calcite.rel.metadata.ReflectiveRelMetadataProvider;
 import org.apache.calcite.rel.metadata.RelMdSelectivity;
 import org.apache.calcite.rel.metadata.RelMdUtil;
 import org.apache.calcite.rel.metadata.RelMetadataProvider;
 import org.apache.calcite.rel.metadata.RelMetadataQuery;
 import org.apache.calcite.rex.RexCall;
+import org.apache.calcite.rex.RexLocalRef;
 import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.rex.RexVisitor;
+import org.apache.calcite.rex.RexVisitorImpl;
 import org.apache.calcite.sql.SqlKind;
 import org.apache.calcite.util.BuiltInMethod;
+import org.apache.calcite.util.Util;
 import org.apache.ignite.internal.sql.engine.prepare.bounds.ExactBounds;
 import org.apache.ignite.internal.sql.engine.prepare.bounds.MultiBounds;
 import org.apache.ignite.internal.sql.engine.prepare.bounds.RangeBounds;
 import org.apache.ignite.internal.sql.engine.prepare.bounds.SearchBounds;
 import org.apache.ignite.internal.sql.engine.rel.IgniteHashIndexSpool;
 import org.apache.ignite.internal.sql.engine.rel.IgniteSortedIndexSpool;
 import org.apache.ignite.internal.sql.engine.rel.ProjectableFilterableTableScan;
+import org.apache.ignite.internal.sql.engine.util.Commons;
 import org.apache.ignite.internal.sql.engine.util.RexUtils;
+import org.checkerframework.checker.nullness.qual.Nullable;
 
 /**
- * IgniteMdSelectivity.
- * TODO Documentation https://issues.apache.org/jira/browse/IGNITE-15859
+ * IgniteMdSelectivity supplies implementation of {@link RelMetadataQuery#getSelectivity}.
  */
 public class IgniteMdSelectivity extends RelMdSelectivity {
     public static final RelMetadataProvider SOURCE =
             ReflectiveRelMetadataProvider.reflectiveSource(
                     BuiltInMethod.SELECTIVITY.method, new IgniteMdSelectivity());
 
+    private static final double EQ_SELECTIVITY = 0.333;
+
+    private static double computeOpsSelectivity(Map<RexNode, List<SqlKind>> operands, double baseSelectivity) {
+        double result = baseSelectivity;
+
+        for (Map.Entry<RexNode, List<SqlKind>> e : operands.entrySet()) {
+            int eqNum = 0;
+            double result0 = 0.0;
+
+            for (SqlKind kind : e.getValue()) {
+                switch (kind) {
+                    case IS_NOT_NULL:
+                        result0 = Math.max(result0, 0.9);
+                        break;
+                    case EQUALS:
+                        // Take into account Zipf`s distribution.
+                        result0 = Math.min(result0 + (EQ_SELECTIVITY / Math.sqrt(++eqNum)), 1.0);
+                        break;
+                    case GREATER_THAN:
+                    case LESS_THAN:
+                    case GREATER_THAN_OR_EQUAL:
+                    case LESS_THAN_OR_EQUAL:
+                        result0 = Math.min(result0 + 0.5, 1.0);
+                        break;
+                    default:
+                        // Not clear here, proceed with default.
+                        result0 += 0.05;
+                }
+            }
+
+            result = Math.max(result, result0);
+        }
+
+        return result;
+    }
+
+    /**
+     * Implements selectivity prediction algorithm. <br>
+     * Current implementation work as follows: <br><br>
+     * 1. If mixed OR-related operands are processed i.e: OR(=($t1, 'D'), =($t1, 'M'), =($t2, 'W')) selectivity computes separately
+     * for each local ref and a big one is chosen <br>
+     * 2. If mixed OR or AND related operands are processed i.e:
+     * OR(<($t3, 110), >($t3, 150), AND(>=($t2, -($t1, 2)), <=($t2, +($t3, 2))), >($t4, $t2), <($t4, $t3)) selectivity computes separately
+     * for each local ref with AND selectivity adjustment. <br>
+     */
+    private static double computeSelectivity(RexCall call) {
+        ImmutableList<RexNode> operands = call.operands;
+        List<RexNode> andOperands = null;
+        List<RexNode> otherOperands = null;
+        double baseSelectivity = 0.0;
+        Map<RexNode, List<SqlKind>> processOperands = new HashMap<>();
+
+        assert !operands.isEmpty();
+
+        boolean andConsist = operands.stream().anyMatch(op -> op.isA(SqlKind.AND));
+
+        if (andConsist) {
+            for (RexNode op : operands) {
+                if (op.isA(SqlKind.AND)) {
+                    if (andOperands == null) {

Review Comment:
   I made it on purpose to avoid extra allocations in hot path, no need in this structures if no internal AND is present



-- 
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: notifications-unsubscribe@ignite.apache.org

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


Re: [PR] IGNITE-23969 Sql. Improve predicate selectivity estimation [ignite-3]

Posted by "ygerzhedovich (via GitHub)" <gi...@apache.org>.
ygerzhedovich commented on code in PR #5211:
URL: https://github.com/apache/ignite-3/pull/5211#discussion_r1959309643


##########
modules/sql-engine/src/integrationTest/java/org/apache/ignite/internal/sql/engine/ItLocksSystemViewTest.java:
##########
@@ -83,8 +83,16 @@ public void testMetadata() {
     public void testData() {
         Ignite node = CLUSTER.aliveNode();
 
-        sql("CREATE TABLE test (id INT PRIMARY KEY, val INT)");
-        sql("INSERT INTO test VALUES (0, 0), (2, 2)");
+        // Need 3 different tables here, because near sql flow: INSERT -> UPDATE -> DELETE leads to dead lock

Review Comment:
   can we add todo with a ticket for a fix? in some time the issue was gone, but the comment will still be there and will lead to incorrect understanding.



-- 
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: notifications-unsubscribe@ignite.apache.org

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


Re: [PR] IGNITE-23969 Sql. Improve predicate selectivity estimation [ignite-3]

Posted by "zstan (via GitHub)" <gi...@apache.org>.
zstan commented on code in PR #5211:
URL: https://github.com/apache/ignite-3/pull/5211#discussion_r1954222511


##########
modules/sql-engine/src/main/java/org/apache/ignite/internal/sql/engine/metadata/IgniteMdSelectivity.java:
##########
@@ -17,49 +17,226 @@
 
 package org.apache.ignite.internal.sql.engine.metadata;
 
+import static org.apache.calcite.rex.RexUtil.expandSearch;
+
+import com.google.common.collect.ImmutableList;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import org.apache.calcite.plan.RelOptUtil;
 import org.apache.calcite.rel.metadata.ReflectiveRelMetadataProvider;
 import org.apache.calcite.rel.metadata.RelMdSelectivity;
 import org.apache.calcite.rel.metadata.RelMdUtil;
 import org.apache.calcite.rel.metadata.RelMetadataProvider;
 import org.apache.calcite.rel.metadata.RelMetadataQuery;
 import org.apache.calcite.rex.RexCall;
+import org.apache.calcite.rex.RexLocalRef;
 import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.rex.RexVisitor;
+import org.apache.calcite.rex.RexVisitorImpl;
 import org.apache.calcite.sql.SqlKind;
 import org.apache.calcite.util.BuiltInMethod;
+import org.apache.calcite.util.Util;
 import org.apache.ignite.internal.sql.engine.prepare.bounds.ExactBounds;
 import org.apache.ignite.internal.sql.engine.prepare.bounds.MultiBounds;
 import org.apache.ignite.internal.sql.engine.prepare.bounds.RangeBounds;
 import org.apache.ignite.internal.sql.engine.prepare.bounds.SearchBounds;
 import org.apache.ignite.internal.sql.engine.rel.IgniteHashIndexSpool;
 import org.apache.ignite.internal.sql.engine.rel.IgniteSortedIndexSpool;
 import org.apache.ignite.internal.sql.engine.rel.ProjectableFilterableTableScan;
+import org.apache.ignite.internal.sql.engine.util.Commons;
 import org.apache.ignite.internal.sql.engine.util.RexUtils;
+import org.checkerframework.checker.nullness.qual.Nullable;
 
 /**
- * IgniteMdSelectivity.
- * TODO Documentation https://issues.apache.org/jira/browse/IGNITE-15859
+ * IgniteMdSelectivity supplies implementation of {@link RelMetadataQuery#getSelectivity}.
  */
 public class IgniteMdSelectivity extends RelMdSelectivity {
     public static final RelMetadataProvider SOURCE =
             ReflectiveRelMetadataProvider.reflectiveSource(
                     BuiltInMethod.SELECTIVITY.method, new IgniteMdSelectivity());
 
+    private static final double EQ_SELECTIVITY = 0.333;
+
+    private static double computeOpsSelectivity(Map<RexNode, List<SqlKind>> operands, double baseSelectivity) {
+        double result = baseSelectivity;
+
+        for (Map.Entry<RexNode, List<SqlKind>> e : operands.entrySet()) {
+            int eqNum = 0;
+            double result0 = 0.0;
+
+            for (SqlKind kind : e.getValue()) {
+                switch (kind) {
+                    case IS_NOT_NULL:
+                        result0 = Math.max(result0, 0.9);
+                        break;
+                    case EQUALS:
+                        // Take into account Zipf`s distribution.
+                        result0 = Math.min(result0 + (EQ_SELECTIVITY / Math.sqrt(++eqNum)), 1.0);
+                        break;
+                    case GREATER_THAN:
+                    case LESS_THAN:
+                    case GREATER_THAN_OR_EQUAL:
+                    case LESS_THAN_OR_EQUAL:
+                        result0 = Math.min(result0 + 0.5, 1.0);
+                        break;
+                    default:
+                        // Not clear here, proceed with default.
+                        result0 += 0.05;
+                }
+            }
+
+            result = Math.max(result, result0);
+        }
+
+        return result;
+    }
+
+    /**
+     * Implements selectivity prediction algorithm. <br>
+     * Current implementation work as follows: <br><br>
+     * 1. If mixed OR-related operands are processed i.e: OR(=($t1, 'D'), =($t1, 'M'), =($t2, 'W')) selectivity computes separately
+     * for each local ref and a big one is chosen <br>
+     * 2. If mixed OR or AND related operands are processed i.e:
+     * OR(<($t3, 110), >($t3, 150), AND(>=($t2, -($t1, 2)), <=($t2, +($t3, 2))), >($t4, $t2), <($t4, $t3)) selectivity computes separately
+     * for each local ref with AND selectivity adjustment. <br>
+     */
+    private static double computeSelectivity(RexCall call) {
+        ImmutableList<RexNode> operands = call.operands;
+        List<RexNode> andOperands = null;
+        List<RexNode> otherOperands = null;
+        double baseSelectivity = 0.0;
+        Map<RexNode, List<SqlKind>> processOperands = new HashMap<>();
+
+        assert !operands.isEmpty();
+
+        boolean andConsist = operands.stream().anyMatch(op -> op.isA(SqlKind.AND));
+
+        if (andConsist) {
+            for (RexNode op : operands) {
+                if (op.isA(SqlKind.AND)) {
+                    if (andOperands == null) {
+                        andOperands = new ArrayList<>();
+                    }
+
+                    andOperands.add(op);
+                } else {
+                    if (otherOperands == null) {
+                        otherOperands = new ArrayList<>();
+                    }
+
+                    otherOperands.add(op);
+                }
+            }
+        }
+
+        // AND inside OR
+        if (andOperands != null) {
+            for (RexNode andOp : andOperands) {
+                baseSelectivity = Math.max(baseSelectivity, RelMdUtil.guessSelectivity(andOp));
+            }
+        }
+
+        List<RexNode> operandsToProcess = otherOperands == null ? call.getOperands() : otherOperands;
+
+        for (RexNode node : operandsToProcess) {
+            RexNode res = getLocalRef(node);
+
+            // It can be null for case with expression for example: LENGTH('abc') = 3
+            if (res != null) {
+                List<SqlKind> vals = processOperands.computeIfAbsent(res, (k) -> new ArrayList<>());
+
+                vals.add(node.getKind());
+            } else {
+                baseSelectivity = Math.max(baseSelectivity, nonColumnRefSelectivity(call));
+            }
+        }
+
+        return computeOpsSelectivity(processOperands, baseSelectivity);
+    }
+
+    private static double nonColumnRefSelectivity(RexCall call) {
+        if (call.isA(SqlKind.EQUALS)) {
+            return EQ_SELECTIVITY;
+        } else if (call.isA(SqlKind.COMPARISON)) {
+            return 0.5;
+        } else {
+            // different OTHER_FUNCTION and other uncovered cases
+            return 0;
+        }
+    }
+
+    private static RexLocalRef getLocalRef(RexNode node) {
+        RexVisitor<Void> v = new RexVisitorImpl<>(true) {
+            @Override
+            public Void visitLocalRef(RexLocalRef locRef) {
+                throw new Util.FoundOne(locRef);
+            }
+        };
+
+        try {
+            node.accept(v);
+
+            return null;
+        } catch (Util.FoundOne e) {
+            return (RexLocalRef) e.getNode();
+        }
+    }
+
+    private static double guessSelectivity(@Nullable RexNode predicate) {
+        double sel = 1.0;
+        if ((predicate == null) || predicate.isAlwaysTrue()) {
+            return sel;
+        }
+
+        double artificialSel = 1.0;
+
+        // make set of AND ... AND calls
+        List<RexNode> conjunctions = RelOptUtil.conjunctions(predicate);
+
+        for (RexNode pred : conjunctions) {
+            // Expand sarg`s
+            RexNode predicateExpanded = expandSearch(Commons.rexBuilder(), null, pred);
+
+            if (predicateExpanded.isA(SqlKind.OR)) {
+                double processed = computeSelectivity((RexCall) predicateExpanded);
+                sel *= processed;
+            } else if (predicateExpanded.getKind() == SqlKind.IS_NOT_NULL) {
+                sel *= 0.9;
+            } else if (
+                    (predicateExpanded instanceof RexCall)
+                            && (((RexCall) predicateExpanded).getOperator()
+                            == RelMdUtil.ARTIFICIAL_SELECTIVITY_FUNC)) {
+                artificialSel *= RelMdUtil.getSelectivityValue(predicateExpanded);
+            } else if (predicateExpanded.isA(SqlKind.EQUALS)) {
+                sel *= 0.15;
+            } else if (predicateExpanded.isA(SqlKind.COMPARISON)) {
+                sel *= 0.5;
+            } else {
+                sel *= 0.25;
+            }
+        }
+
+        return sel * artificialSel;
+    }
+
     /**
      * GetSelectivity.
      * TODO Documentation https://issues.apache.org/jira/browse/IGNITE-15859

Review Comment:
   done



-- 
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: notifications-unsubscribe@ignite.apache.org

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


Re: [PR] IGNITE-23969 Sql. Improve predicate selectivity estimation [ignite-3]

Posted by "ygerzhedovich (via GitHub)" <gi...@apache.org>.
ygerzhedovich commented on code in PR #5211:
URL: https://github.com/apache/ignite-3/pull/5211#discussion_r1954237785


##########
modules/sql-engine/src/main/java/org/apache/ignite/internal/sql/engine/metadata/IgniteMdSelectivity.java:
##########
@@ -17,49 +17,226 @@
 
 package org.apache.ignite.internal.sql.engine.metadata;
 
+import static org.apache.calcite.rex.RexUtil.expandSearch;
+
+import com.google.common.collect.ImmutableList;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import org.apache.calcite.plan.RelOptUtil;
 import org.apache.calcite.rel.metadata.ReflectiveRelMetadataProvider;
 import org.apache.calcite.rel.metadata.RelMdSelectivity;
 import org.apache.calcite.rel.metadata.RelMdUtil;
 import org.apache.calcite.rel.metadata.RelMetadataProvider;
 import org.apache.calcite.rel.metadata.RelMetadataQuery;
 import org.apache.calcite.rex.RexCall;
+import org.apache.calcite.rex.RexLocalRef;
 import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.rex.RexVisitor;
+import org.apache.calcite.rex.RexVisitorImpl;
 import org.apache.calcite.sql.SqlKind;
 import org.apache.calcite.util.BuiltInMethod;
+import org.apache.calcite.util.Util;
 import org.apache.ignite.internal.sql.engine.prepare.bounds.ExactBounds;
 import org.apache.ignite.internal.sql.engine.prepare.bounds.MultiBounds;
 import org.apache.ignite.internal.sql.engine.prepare.bounds.RangeBounds;
 import org.apache.ignite.internal.sql.engine.prepare.bounds.SearchBounds;
 import org.apache.ignite.internal.sql.engine.rel.IgniteHashIndexSpool;
 import org.apache.ignite.internal.sql.engine.rel.IgniteSortedIndexSpool;
 import org.apache.ignite.internal.sql.engine.rel.ProjectableFilterableTableScan;
+import org.apache.ignite.internal.sql.engine.util.Commons;
 import org.apache.ignite.internal.sql.engine.util.RexUtils;
+import org.checkerframework.checker.nullness.qual.Nullable;
 
 /**
- * IgniteMdSelectivity.
- * TODO Documentation https://issues.apache.org/jira/browse/IGNITE-15859
+ * IgniteMdSelectivity supplies implementation of {@link RelMetadataQuery#getSelectivity}.
  */
 public class IgniteMdSelectivity extends RelMdSelectivity {
     public static final RelMetadataProvider SOURCE =
             ReflectiveRelMetadataProvider.reflectiveSource(
                     BuiltInMethod.SELECTIVITY.method, new IgniteMdSelectivity());
 
+    private static final double EQ_SELECTIVITY = 0.333;
+
+    private static double computeOpsSelectivity(Map<RexNode, List<SqlKind>> operands, double baseSelectivity) {
+        double result = baseSelectivity;
+
+        for (Map.Entry<RexNode, List<SqlKind>> e : operands.entrySet()) {
+            int eqNum = 0;
+            double result0 = 0.0;
+
+            for (SqlKind kind : e.getValue()) {
+                switch (kind) {
+                    case IS_NOT_NULL:
+                        result0 = Math.max(result0, 0.9);
+                        break;
+                    case EQUALS:
+                        // Take into account Zipf`s distribution.
+                        result0 = Math.min(result0 + (EQ_SELECTIVITY / Math.sqrt(++eqNum)), 1.0);
+                        break;
+                    case GREATER_THAN:
+                    case LESS_THAN:
+                    case GREATER_THAN_OR_EQUAL:
+                    case LESS_THAN_OR_EQUAL:
+                        result0 = Math.min(result0 + 0.5, 1.0);
+                        break;
+                    default:
+                        // Not clear here, proceed with default.
+                        result0 += 0.05;
+                }
+            }
+
+            result = Math.max(result, result0);
+        }
+
+        return result;
+    }
+
+    /**
+     * Implements selectivity prediction algorithm. <br>
+     * Current implementation work as follows: <br><br>
+     * 1. If mixed OR-related operands are processed i.e: OR(=($t1, 'D'), =($t1, 'M'), =($t2, 'W')) selectivity computes separately
+     * for each local ref and a big one is chosen <br>
+     * 2. If mixed OR or AND related operands are processed i.e:
+     * OR(<($t3, 110), >($t3, 150), AND(>=($t2, -($t1, 2)), <=($t2, +($t3, 2))), >($t4, $t2), <($t4, $t3)) selectivity computes separately
+     * for each local ref with AND selectivity adjustment. <br>
+     */
+    private static double computeSelectivity(RexCall call) {
+        ImmutableList<RexNode> operands = call.operands;
+        List<RexNode> andOperands = null;
+        List<RexNode> otherOperands = null;
+        double baseSelectivity = 0.0;
+        Map<RexNode, List<SqlKind>> processOperands = new HashMap<>();
+
+        assert !operands.isEmpty();
+
+        boolean andConsist = operands.stream().anyMatch(op -> op.isA(SqlKind.AND));
+
+        if (andConsist) {
+            for (RexNode op : operands) {
+                if (op.isA(SqlKind.AND)) {
+                    if (andOperands == null) {

Review Comment:
   I fully understand it, however, simple ArrayList has optimization for create it with default constructor and it will not allocate a new arrays, just a new ArrayList object which would be lightweight and will be collected by GC very soon -  so will not affect performance. Alsoб we removing the check  - that can be also take a little time - I thinks еhey must cancel each other out



-- 
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: notifications-unsubscribe@ignite.apache.org

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


Re: [PR] IGNITE-23969 Sql. Improve predicate selectivity estimation [ignite-3]

Posted by "zstan (via GitHub)" <gi...@apache.org>.
zstan commented on code in PR #5211:
URL: https://github.com/apache/ignite-3/pull/5211#discussion_r1959529824


##########
modules/sql-engine/src/integrationTest/java/org/apache/ignite/internal/sql/engine/ItLocksSystemViewTest.java:
##########
@@ -83,8 +83,16 @@ public void testMetadata() {
     public void testData() {
         Ignite node = CLUSTER.aliveNode();
 
-        sql("CREATE TABLE test (id INT PRIMARY KEY, val INT)");
-        sql("INSERT INTO test VALUES (0, 0), (2, 2)");
+        // Need 3 different tables here, because near sql flow: INSERT -> UPDATE -> DELETE leads to dead lock

Review Comment:
   test was reworked.



-- 
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: notifications-unsubscribe@ignite.apache.org

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


Re: [PR] IGNITE-23969 Sql. Improve predicate selectivity estimation [ignite-3]

Posted by "zstan (via GitHub)" <gi...@apache.org>.
zstan commented on code in PR #5211:
URL: https://github.com/apache/ignite-3/pull/5211#discussion_r1954222142


##########
modules/sql-engine/src/main/java/org/apache/ignite/internal/sql/engine/metadata/IgniteMdSelectivity.java:
##########
@@ -17,49 +17,226 @@
 
 package org.apache.ignite.internal.sql.engine.metadata;
 
+import static org.apache.calcite.rex.RexUtil.expandSearch;
+
+import com.google.common.collect.ImmutableList;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import org.apache.calcite.plan.RelOptUtil;
 import org.apache.calcite.rel.metadata.ReflectiveRelMetadataProvider;
 import org.apache.calcite.rel.metadata.RelMdSelectivity;
 import org.apache.calcite.rel.metadata.RelMdUtil;
 import org.apache.calcite.rel.metadata.RelMetadataProvider;
 import org.apache.calcite.rel.metadata.RelMetadataQuery;
 import org.apache.calcite.rex.RexCall;
+import org.apache.calcite.rex.RexLocalRef;
 import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.rex.RexVisitor;
+import org.apache.calcite.rex.RexVisitorImpl;
 import org.apache.calcite.sql.SqlKind;
 import org.apache.calcite.util.BuiltInMethod;
+import org.apache.calcite.util.Util;
 import org.apache.ignite.internal.sql.engine.prepare.bounds.ExactBounds;
 import org.apache.ignite.internal.sql.engine.prepare.bounds.MultiBounds;
 import org.apache.ignite.internal.sql.engine.prepare.bounds.RangeBounds;
 import org.apache.ignite.internal.sql.engine.prepare.bounds.SearchBounds;
 import org.apache.ignite.internal.sql.engine.rel.IgniteHashIndexSpool;
 import org.apache.ignite.internal.sql.engine.rel.IgniteSortedIndexSpool;
 import org.apache.ignite.internal.sql.engine.rel.ProjectableFilterableTableScan;
+import org.apache.ignite.internal.sql.engine.util.Commons;
 import org.apache.ignite.internal.sql.engine.util.RexUtils;
+import org.checkerframework.checker.nullness.qual.Nullable;
 
 /**
- * IgniteMdSelectivity.
- * TODO Documentation https://issues.apache.org/jira/browse/IGNITE-15859
+ * IgniteMdSelectivity supplies implementation of {@link RelMetadataQuery#getSelectivity}.
  */
 public class IgniteMdSelectivity extends RelMdSelectivity {
     public static final RelMetadataProvider SOURCE =
             ReflectiveRelMetadataProvider.reflectiveSource(
                     BuiltInMethod.SELECTIVITY.method, new IgniteMdSelectivity());
 
+    private static final double EQ_SELECTIVITY = 0.333;
+
+    private static double computeOpsSelectivity(Map<RexNode, List<SqlKind>> operands, double baseSelectivity) {
+        double result = baseSelectivity;
+
+        for (Map.Entry<RexNode, List<SqlKind>> e : operands.entrySet()) {
+            int eqNum = 0;
+            double result0 = 0.0;
+
+            for (SqlKind kind : e.getValue()) {
+                switch (kind) {
+                    case IS_NOT_NULL:
+                        result0 = Math.max(result0, 0.9);
+                        break;
+                    case EQUALS:
+                        // Take into account Zipf`s distribution.
+                        result0 = Math.min(result0 + (EQ_SELECTIVITY / Math.sqrt(++eqNum)), 1.0);
+                        break;
+                    case GREATER_THAN:
+                    case LESS_THAN:
+                    case GREATER_THAN_OR_EQUAL:
+                    case LESS_THAN_OR_EQUAL:
+                        result0 = Math.min(result0 + 0.5, 1.0);
+                        break;
+                    default:
+                        // Not clear here, proceed with default.
+                        result0 += 0.05;
+                }
+            }
+
+            result = Math.max(result, result0);
+        }
+
+        return result;
+    }
+
+    /**
+     * Implements selectivity prediction algorithm. <br>
+     * Current implementation work as follows: <br><br>
+     * 1. If mixed OR-related operands are processed i.e: OR(=($t1, 'D'), =($t1, 'M'), =($t2, 'W')) selectivity computes separately
+     * for each local ref and a big one is chosen <br>
+     * 2. If mixed OR or AND related operands are processed i.e:
+     * OR(<($t3, 110), >($t3, 150), AND(>=($t2, -($t1, 2)), <=($t2, +($t3, 2))), >($t4, $t2), <($t4, $t3)) selectivity computes separately
+     * for each local ref with AND selectivity adjustment. <br>
+     */
+    private static double computeSelectivity(RexCall call) {
+        ImmutableList<RexNode> operands = call.operands;

Review Comment:
   done



##########
modules/sql-engine/src/main/java/org/apache/ignite/internal/sql/engine/metadata/IgniteMdSelectivity.java:
##########
@@ -17,49 +17,226 @@
 
 package org.apache.ignite.internal.sql.engine.metadata;
 
+import static org.apache.calcite.rex.RexUtil.expandSearch;
+
+import com.google.common.collect.ImmutableList;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import org.apache.calcite.plan.RelOptUtil;
 import org.apache.calcite.rel.metadata.ReflectiveRelMetadataProvider;
 import org.apache.calcite.rel.metadata.RelMdSelectivity;
 import org.apache.calcite.rel.metadata.RelMdUtil;
 import org.apache.calcite.rel.metadata.RelMetadataProvider;
 import org.apache.calcite.rel.metadata.RelMetadataQuery;
 import org.apache.calcite.rex.RexCall;
+import org.apache.calcite.rex.RexLocalRef;
 import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.rex.RexVisitor;
+import org.apache.calcite.rex.RexVisitorImpl;
 import org.apache.calcite.sql.SqlKind;
 import org.apache.calcite.util.BuiltInMethod;
+import org.apache.calcite.util.Util;
 import org.apache.ignite.internal.sql.engine.prepare.bounds.ExactBounds;
 import org.apache.ignite.internal.sql.engine.prepare.bounds.MultiBounds;
 import org.apache.ignite.internal.sql.engine.prepare.bounds.RangeBounds;
 import org.apache.ignite.internal.sql.engine.prepare.bounds.SearchBounds;
 import org.apache.ignite.internal.sql.engine.rel.IgniteHashIndexSpool;
 import org.apache.ignite.internal.sql.engine.rel.IgniteSortedIndexSpool;
 import org.apache.ignite.internal.sql.engine.rel.ProjectableFilterableTableScan;
+import org.apache.ignite.internal.sql.engine.util.Commons;
 import org.apache.ignite.internal.sql.engine.util.RexUtils;
+import org.checkerframework.checker.nullness.qual.Nullable;
 
 /**
- * IgniteMdSelectivity.
- * TODO Documentation https://issues.apache.org/jira/browse/IGNITE-15859
+ * IgniteMdSelectivity supplies implementation of {@link RelMetadataQuery#getSelectivity}.
  */
 public class IgniteMdSelectivity extends RelMdSelectivity {
     public static final RelMetadataProvider SOURCE =
             ReflectiveRelMetadataProvider.reflectiveSource(
                     BuiltInMethod.SELECTIVITY.method, new IgniteMdSelectivity());
 
+    private static final double EQ_SELECTIVITY = 0.333;
+
+    private static double computeOpsSelectivity(Map<RexNode, List<SqlKind>> operands, double baseSelectivity) {

Review Comment:
   done



-- 
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: notifications-unsubscribe@ignite.apache.org

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


Re: [PR] IGNITE-23969 Sql. Improve predicate selectivity estimation [ignite-3]

Posted by "lowka (via GitHub)" <gi...@apache.org>.
lowka commented on code in PR #5211:
URL: https://github.com/apache/ignite-3/pull/5211#discussion_r1960999007


##########
modules/sql-engine/src/test/java/org/apache/ignite/internal/sql/engine/planner/SelectRowCountEstimationTest.java:
##########
@@ -0,0 +1,195 @@
+/*
+ * 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.
+ */
+
+package org.apache.ignite.internal.sql.engine.planner;
+
+import static org.apache.ignite.internal.sql.engine.framework.DataProvider.fromCollection;
+import static org.apache.ignite.internal.sql.engine.framework.TestBuilders.tableScan;
+import static org.apache.ignite.internal.sql.engine.metadata.IgniteMdSelectivity.COMPARISON_SELECTIVITY;
+import static org.apache.ignite.internal.sql.engine.metadata.IgniteMdSelectivity.EQ_SELECTIVITY;
+import static org.apache.ignite.internal.sql.engine.metadata.IgniteMdSelectivity.IS_NOT_NULL_SELECTIVITY;
+import static org.apache.ignite.internal.sql.engine.util.QueryChecker.nodeRowCount;
+
+import java.util.List;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+import org.apache.ignite.internal.lang.IgniteStringBuilder;
+import org.apache.ignite.internal.sql.engine.framework.TestBuilders;
+import org.apache.ignite.internal.sql.engine.framework.TestCluster;
+import org.apache.ignite.internal.sql.engine.framework.TestNode;
+import org.apache.ignite.internal.sql.engine.util.TpcTable;
+import org.apache.ignite.internal.sql.engine.util.tpcds.TpcdsTables;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+/**
+ * Tests to check row count estimation for select relation.
+ */
+public class SelectRowCountEstimationTest extends BaseRowsProcessedEstimationTest {
+    private static final int TABLE_REAL_SIZE = 73_049;
+
+    private static final TestCluster CLUSTER = TestBuilders.cluster()
+            .nodes("N1")
+            .defaultAssignmentsProvider(tableName -> (partNum, includeBackups) -> IntStream.range(0, partNum)
+                    .mapToObj(part -> List.of("N1"))
+                    .collect(Collectors.toList())
+            )
+            .defaultDataProvider(tableName -> tableScan(fromCollection(List.of())))
+            .build();
+
+    private static final TestNode NODE = CLUSTER.node("N1");
+
+    @BeforeAll
+    static void startCluster() {
+        CLUSTER.start();
+
+        for (TpcTable table : List.of(TpcdsTables.CATALOG_SALES)) {
+            NODE.initSchema(table.ddlScript());
+        }
+
+        CLUSTER.setTableSize("CATALOG_SALES", TABLE_REAL_SIZE);
+    }
+
+    @AfterAll
+    static void stopCluster() throws Exception {
+        CLUSTER.stop();
+    }
+
+    @Test
+    void testConditionWithPk() {
+        // partial pk

Review Comment:
   What is a point of not parameterising this test?



-- 
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: notifications-unsubscribe@ignite.apache.org

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


Re: [PR] IGNITE-23969 Sql. Improve predicate selectivity estimation [ignite-3]

Posted by "zstan (via GitHub)" <gi...@apache.org>.
zstan commented on code in PR #5211:
URL: https://github.com/apache/ignite-3/pull/5211#discussion_r1961022672


##########
modules/sql-engine/src/test/java/org/apache/ignite/internal/sql/engine/planner/SelectRowCountEstimationTest.java:
##########
@@ -0,0 +1,195 @@
+/*
+ * 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.
+ */
+
+package org.apache.ignite.internal.sql.engine.planner;
+
+import static org.apache.ignite.internal.sql.engine.framework.DataProvider.fromCollection;
+import static org.apache.ignite.internal.sql.engine.framework.TestBuilders.tableScan;
+import static org.apache.ignite.internal.sql.engine.metadata.IgniteMdSelectivity.COMPARISON_SELECTIVITY;
+import static org.apache.ignite.internal.sql.engine.metadata.IgniteMdSelectivity.EQ_SELECTIVITY;
+import static org.apache.ignite.internal.sql.engine.metadata.IgniteMdSelectivity.IS_NOT_NULL_SELECTIVITY;
+import static org.apache.ignite.internal.sql.engine.util.QueryChecker.nodeRowCount;
+
+import java.util.List;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+import org.apache.ignite.internal.lang.IgniteStringBuilder;
+import org.apache.ignite.internal.sql.engine.framework.TestBuilders;
+import org.apache.ignite.internal.sql.engine.framework.TestCluster;
+import org.apache.ignite.internal.sql.engine.framework.TestNode;
+import org.apache.ignite.internal.sql.engine.util.TpcTable;
+import org.apache.ignite.internal.sql.engine.util.tpcds.TpcdsTables;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+/**
+ * Tests to check row count estimation for select relation.
+ */
+public class SelectRowCountEstimationTest extends BaseRowsProcessedEstimationTest {
+    private static final int TABLE_REAL_SIZE = 73_049;
+
+    private static final TestCluster CLUSTER = TestBuilders.cluster()
+            .nodes("N1")
+            .defaultAssignmentsProvider(tableName -> (partNum, includeBackups) -> IntStream.range(0, partNum)
+                    .mapToObj(part -> List.of("N1"))
+                    .collect(Collectors.toList())
+            )
+            .defaultDataProvider(tableName -> tableScan(fromCollection(List.of())))
+            .build();
+
+    private static final TestNode NODE = CLUSTER.node("N1");
+
+    @BeforeAll
+    static void startCluster() {
+        CLUSTER.start();
+
+        for (TpcTable table : List.of(TpcdsTables.CATALOG_SALES)) {
+            NODE.initSchema(table.ddlScript());
+        }
+
+        CLUSTER.setTableSize("CATALOG_SALES", TABLE_REAL_SIZE);
+    }
+
+    @AfterAll
+    static void stopCluster() throws Exception {
+        CLUSTER.stop();
+    }
+
+    @Test
+    void testConditionWithPk() {
+        // partial pk

Review Comment:
   you right, done



##########
modules/sql-engine/src/test/java/org/apache/ignite/internal/sql/engine/planner/SelectRowCountEstimationTest.java:
##########
@@ -0,0 +1,195 @@
+/*
+ * 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.
+ */
+
+package org.apache.ignite.internal.sql.engine.planner;
+
+import static org.apache.ignite.internal.sql.engine.framework.DataProvider.fromCollection;
+import static org.apache.ignite.internal.sql.engine.framework.TestBuilders.tableScan;
+import static org.apache.ignite.internal.sql.engine.metadata.IgniteMdSelectivity.COMPARISON_SELECTIVITY;
+import static org.apache.ignite.internal.sql.engine.metadata.IgniteMdSelectivity.EQ_SELECTIVITY;
+import static org.apache.ignite.internal.sql.engine.metadata.IgniteMdSelectivity.IS_NOT_NULL_SELECTIVITY;
+import static org.apache.ignite.internal.sql.engine.util.QueryChecker.nodeRowCount;
+
+import java.util.List;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+import org.apache.ignite.internal.lang.IgniteStringBuilder;
+import org.apache.ignite.internal.sql.engine.framework.TestBuilders;
+import org.apache.ignite.internal.sql.engine.framework.TestCluster;
+import org.apache.ignite.internal.sql.engine.framework.TestNode;
+import org.apache.ignite.internal.sql.engine.util.TpcTable;
+import org.apache.ignite.internal.sql.engine.util.tpcds.TpcdsTables;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+/**
+ * Tests to check row count estimation for select relation.
+ */
+public class SelectRowCountEstimationTest extends BaseRowsProcessedEstimationTest {
+    private static final int TABLE_REAL_SIZE = 73_049;
+
+    private static final TestCluster CLUSTER = TestBuilders.cluster()
+            .nodes("N1")
+            .defaultAssignmentsProvider(tableName -> (partNum, includeBackups) -> IntStream.range(0, partNum)
+                    .mapToObj(part -> List.of("N1"))
+                    .collect(Collectors.toList())
+            )
+            .defaultDataProvider(tableName -> tableScan(fromCollection(List.of())))
+            .build();
+
+    private static final TestNode NODE = CLUSTER.node("N1");
+
+    @BeforeAll
+    static void startCluster() {
+        CLUSTER.start();
+
+        for (TpcTable table : List.of(TpcdsTables.CATALOG_SALES)) {
+            NODE.initSchema(table.ddlScript());
+        }
+
+        CLUSTER.setTableSize("CATALOG_SALES", TABLE_REAL_SIZE);
+    }
+
+    @AfterAll
+    static void stopCluster() throws Exception {
+        CLUSTER.stop();
+    }
+
+    @Test
+    void testConditionWithPk() {
+        // partial pk
+        double selectivityFactor = EQ_SELECTIVITY;
+        assertQuery(NODE, "SELECT * FROM CATALOG_SALES WHERE CS_ITEM_SK = 1")
+                .matches(nodeRowCount("TableScan", approximatelyEqual(TABLE_REAL_SIZE * selectivityFactor)))
+                .check();
+
+        // full pk, eq operations
+        selectivityFactor = 1.0 / TABLE_REAL_SIZE;
+        assertQuery(NODE, "SELECT * FROM CATALOG_SALES WHERE CS_ITEM_SK = 1 AND CS_ORDER_NUMBER = 1")
+                .disableRules("TableScanToKeyValueGetRule", "LogicalIndexScanConverterRule")
+                .matches(nodeRowCount("TableScan", approximatelyEqual(TABLE_REAL_SIZE * selectivityFactor)))
+                .check();
+
+        // full pk, comp operations
+        selectivityFactor = EQ_SELECTIVITY * COMPARISON_SELECTIVITY;
+        assertQuery(NODE, "SELECT * FROM CATALOG_SALES WHERE CS_ITEM_SK = 1 AND CS_ORDER_NUMBER > 1")
+                .disableRules("TableScanToKeyValueGetRule", "LogicalIndexScanConverterRule")
+                .matches(nodeRowCount("TableScan", approximatelyEqual(TABLE_REAL_SIZE * selectivityFactor)))
+                .check();
+
+        // full pk with OR
+        selectivityFactor = EQ_SELECTIVITY;
+        assertQuery(NODE, "SELECT * FROM CATALOG_SALES WHERE (CS_ITEM_SK = 1 AND CS_ORDER_NUMBER = 1) OR CS_ORDER_NUMBER = 2")
+                .disableRules("TableScanToKeyValueGetRule", "LogicalIndexScanConverterRule")
+                .matches(nodeRowCount("TableScan", approximatelyEqual(TABLE_REAL_SIZE * selectivityFactor)))
+                .check();
+
+        // full pk or full pk
+        selectivityFactor = 1.0 / TABLE_REAL_SIZE;
+        assertQuery(NODE, "SELECT * FROM CATALOG_SALES WHERE (CS_ITEM_SK = 1 AND CS_ORDER_NUMBER = 1) "
+                + "OR (CS_ITEM_SK = 3 AND CS_ORDER_NUMBER = 3)")
+                .disableRules("TableScanToKeyValueGetRule", "LogicalIndexScanConverterRule")
+                .matches(nodeRowCount("TableScan", approximatelyEqual(TABLE_REAL_SIZE * selectivityFactor)))
+                .check();
+
+        // full pk with computation, not covered by now
+        selectivityFactor = EQ_SELECTIVITY;
+        assertQuery(NODE, "SELECT * FROM CATALOG_SALES WHERE CS_ORDER_NUMBER + CS_ITEM_SK = 1")
+                .matches(nodeRowCount("TableScan", approximatelyEqual(TABLE_REAL_SIZE * selectivityFactor)))
+                .check();
+    }
+
+    @Test
+    void testPredicatesSelectivity() {

Review Comment:
   done



-- 
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: notifications-unsubscribe@ignite.apache.org

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


Re: [PR] IGNITE-23969 Sql. Improve predicate selectivity estimation [ignite-3]

Posted by "zstan (via GitHub)" <gi...@apache.org>.
zstan merged PR #5211:
URL: https://github.com/apache/ignite-3/pull/5211


-- 
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: notifications-unsubscribe@ignite.apache.org

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


Re: [PR] IGNITE-23969 Sql. Improve predicate selectivity estimation [ignite-3]

Posted by "ygerzhedovich (via GitHub)" <gi...@apache.org>.
ygerzhedovich commented on code in PR #5211:
URL: https://github.com/apache/ignite-3/pull/5211#discussion_r1952814262


##########
modules/sql-engine/src/main/java/org/apache/ignite/internal/sql/engine/metadata/IgniteMdSelectivity.java:
##########
@@ -17,49 +17,226 @@
 
 package org.apache.ignite.internal.sql.engine.metadata;
 
+import static org.apache.calcite.rex.RexUtil.expandSearch;
+
+import com.google.common.collect.ImmutableList;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import org.apache.calcite.plan.RelOptUtil;
 import org.apache.calcite.rel.metadata.ReflectiveRelMetadataProvider;
 import org.apache.calcite.rel.metadata.RelMdSelectivity;
 import org.apache.calcite.rel.metadata.RelMdUtil;
 import org.apache.calcite.rel.metadata.RelMetadataProvider;
 import org.apache.calcite.rel.metadata.RelMetadataQuery;
 import org.apache.calcite.rex.RexCall;
+import org.apache.calcite.rex.RexLocalRef;
 import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.rex.RexVisitor;
+import org.apache.calcite.rex.RexVisitorImpl;
 import org.apache.calcite.sql.SqlKind;
 import org.apache.calcite.util.BuiltInMethod;
+import org.apache.calcite.util.Util;
 import org.apache.ignite.internal.sql.engine.prepare.bounds.ExactBounds;
 import org.apache.ignite.internal.sql.engine.prepare.bounds.MultiBounds;
 import org.apache.ignite.internal.sql.engine.prepare.bounds.RangeBounds;
 import org.apache.ignite.internal.sql.engine.prepare.bounds.SearchBounds;
 import org.apache.ignite.internal.sql.engine.rel.IgniteHashIndexSpool;
 import org.apache.ignite.internal.sql.engine.rel.IgniteSortedIndexSpool;
 import org.apache.ignite.internal.sql.engine.rel.ProjectableFilterableTableScan;
+import org.apache.ignite.internal.sql.engine.util.Commons;
 import org.apache.ignite.internal.sql.engine.util.RexUtils;
+import org.checkerframework.checker.nullness.qual.Nullable;
 
 /**
- * IgniteMdSelectivity.
- * TODO Documentation https://issues.apache.org/jira/browse/IGNITE-15859
+ * IgniteMdSelectivity supplies implementation of {@link RelMetadataQuery#getSelectivity}.
  */
 public class IgniteMdSelectivity extends RelMdSelectivity {
     public static final RelMetadataProvider SOURCE =
             ReflectiveRelMetadataProvider.reflectiveSource(
                     BuiltInMethod.SELECTIVITY.method, new IgniteMdSelectivity());
 
+    private static final double EQ_SELECTIVITY = 0.333;
+
+    private static double computeOpsSelectivity(Map<RexNode, List<SqlKind>> operands, double baseSelectivity) {

Review Comment:
   let's extract these magic numbers into constants, like :
   ```
   private static final double IS_NOT_NULL_SELECTIVITY = 0.9;
   private static final double COMPARISON_SELECTIVITY = 0.5;
   private static final double DEFAULT_SELECTIVITY_INCREMENT = 0.05;
   ```



##########
modules/sql-engine/src/main/java/org/apache/ignite/internal/sql/engine/metadata/IgniteMdSelectivity.java:
##########
@@ -17,49 +17,226 @@
 
 package org.apache.ignite.internal.sql.engine.metadata;
 
+import static org.apache.calcite.rex.RexUtil.expandSearch;
+
+import com.google.common.collect.ImmutableList;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import org.apache.calcite.plan.RelOptUtil;
 import org.apache.calcite.rel.metadata.ReflectiveRelMetadataProvider;
 import org.apache.calcite.rel.metadata.RelMdSelectivity;
 import org.apache.calcite.rel.metadata.RelMdUtil;
 import org.apache.calcite.rel.metadata.RelMetadataProvider;
 import org.apache.calcite.rel.metadata.RelMetadataQuery;
 import org.apache.calcite.rex.RexCall;
+import org.apache.calcite.rex.RexLocalRef;
 import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.rex.RexVisitor;
+import org.apache.calcite.rex.RexVisitorImpl;
 import org.apache.calcite.sql.SqlKind;
 import org.apache.calcite.util.BuiltInMethod;
+import org.apache.calcite.util.Util;
 import org.apache.ignite.internal.sql.engine.prepare.bounds.ExactBounds;
 import org.apache.ignite.internal.sql.engine.prepare.bounds.MultiBounds;
 import org.apache.ignite.internal.sql.engine.prepare.bounds.RangeBounds;
 import org.apache.ignite.internal.sql.engine.prepare.bounds.SearchBounds;
 import org.apache.ignite.internal.sql.engine.rel.IgniteHashIndexSpool;
 import org.apache.ignite.internal.sql.engine.rel.IgniteSortedIndexSpool;
 import org.apache.ignite.internal.sql.engine.rel.ProjectableFilterableTableScan;
+import org.apache.ignite.internal.sql.engine.util.Commons;
 import org.apache.ignite.internal.sql.engine.util.RexUtils;
+import org.checkerframework.checker.nullness.qual.Nullable;
 
 /**
- * IgniteMdSelectivity.
- * TODO Documentation https://issues.apache.org/jira/browse/IGNITE-15859
+ * IgniteMdSelectivity supplies implementation of {@link RelMetadataQuery#getSelectivity}.
  */
 public class IgniteMdSelectivity extends RelMdSelectivity {
     public static final RelMetadataProvider SOURCE =
             ReflectiveRelMetadataProvider.reflectiveSource(
                     BuiltInMethod.SELECTIVITY.method, new IgniteMdSelectivity());
 
+    private static final double EQ_SELECTIVITY = 0.333;
+
+    private static double computeOpsSelectivity(Map<RexNode, List<SqlKind>> operands, double baseSelectivity) {
+        double result = baseSelectivity;
+
+        for (Map.Entry<RexNode, List<SqlKind>> e : operands.entrySet()) {
+            int eqNum = 0;
+            double result0 = 0.0;
+
+            for (SqlKind kind : e.getValue()) {
+                switch (kind) {
+                    case IS_NOT_NULL:
+                        result0 = Math.max(result0, 0.9);
+                        break;
+                    case EQUALS:
+                        // Take into account Zipf`s distribution.
+                        result0 = Math.min(result0 + (EQ_SELECTIVITY / Math.sqrt(++eqNum)), 1.0);
+                        break;
+                    case GREATER_THAN:
+                    case LESS_THAN:
+                    case GREATER_THAN_OR_EQUAL:
+                    case LESS_THAN_OR_EQUAL:
+                        result0 = Math.min(result0 + 0.5, 1.0);
+                        break;
+                    default:
+                        // Not clear here, proceed with default.
+                        result0 += 0.05;
+                }
+            }
+
+            result = Math.max(result, result0);
+        }
+
+        return result;
+    }
+
+    /**
+     * Implements selectivity prediction algorithm. <br>
+     * Current implementation work as follows: <br><br>
+     * 1. If mixed OR-related operands are processed i.e: OR(=($t1, 'D'), =($t1, 'M'), =($t2, 'W')) selectivity computes separately
+     * for each local ref and a big one is chosen <br>
+     * 2. If mixed OR or AND related operands are processed i.e:
+     * OR(<($t3, 110), >($t3, 150), AND(>=($t2, -($t1, 2)), <=($t2, +($t3, 2))), >($t4, $t2), <($t4, $t3)) selectivity computes separately
+     * for each local ref with AND selectivity adjustment. <br>
+     */
+    private static double computeSelectivity(RexCall call) {
+        ImmutableList<RexNode> operands = call.operands;
+        List<RexNode> andOperands = null;
+        List<RexNode> otherOperands = null;
+        double baseSelectivity = 0.0;
+        Map<RexNode, List<SqlKind>> processOperands = new HashMap<>();
+
+        assert !operands.isEmpty();
+
+        boolean andConsist = operands.stream().anyMatch(op -> op.isA(SqlKind.AND));
+
+        if (andConsist) {
+            for (RexNode op : operands) {
+                if (op.isA(SqlKind.AND)) {
+                    if (andOperands == null) {

Review Comment:
   it will be more readable if we initialize `andOperands` and `otherOperands` in the beginning and avoid this check everytime.



##########
modules/sql-engine/src/main/java/org/apache/ignite/internal/sql/engine/metadata/IgniteMdSelectivity.java:
##########
@@ -17,49 +17,226 @@
 
 package org.apache.ignite.internal.sql.engine.metadata;
 
+import static org.apache.calcite.rex.RexUtil.expandSearch;
+
+import com.google.common.collect.ImmutableList;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import org.apache.calcite.plan.RelOptUtil;
 import org.apache.calcite.rel.metadata.ReflectiveRelMetadataProvider;
 import org.apache.calcite.rel.metadata.RelMdSelectivity;
 import org.apache.calcite.rel.metadata.RelMdUtil;
 import org.apache.calcite.rel.metadata.RelMetadataProvider;
 import org.apache.calcite.rel.metadata.RelMetadataQuery;
 import org.apache.calcite.rex.RexCall;
+import org.apache.calcite.rex.RexLocalRef;
 import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.rex.RexVisitor;
+import org.apache.calcite.rex.RexVisitorImpl;
 import org.apache.calcite.sql.SqlKind;
 import org.apache.calcite.util.BuiltInMethod;
+import org.apache.calcite.util.Util;
 import org.apache.ignite.internal.sql.engine.prepare.bounds.ExactBounds;
 import org.apache.ignite.internal.sql.engine.prepare.bounds.MultiBounds;
 import org.apache.ignite.internal.sql.engine.prepare.bounds.RangeBounds;
 import org.apache.ignite.internal.sql.engine.prepare.bounds.SearchBounds;
 import org.apache.ignite.internal.sql.engine.rel.IgniteHashIndexSpool;
 import org.apache.ignite.internal.sql.engine.rel.IgniteSortedIndexSpool;
 import org.apache.ignite.internal.sql.engine.rel.ProjectableFilterableTableScan;
+import org.apache.ignite.internal.sql.engine.util.Commons;
 import org.apache.ignite.internal.sql.engine.util.RexUtils;
+import org.checkerframework.checker.nullness.qual.Nullable;
 
 /**
- * IgniteMdSelectivity.
- * TODO Documentation https://issues.apache.org/jira/browse/IGNITE-15859
+ * IgniteMdSelectivity supplies implementation of {@link RelMetadataQuery#getSelectivity}.
  */
 public class IgniteMdSelectivity extends RelMdSelectivity {
     public static final RelMetadataProvider SOURCE =
             ReflectiveRelMetadataProvider.reflectiveSource(
                     BuiltInMethod.SELECTIVITY.method, new IgniteMdSelectivity());
 
+    private static final double EQ_SELECTIVITY = 0.333;
+
+    private static double computeOpsSelectivity(Map<RexNode, List<SqlKind>> operands, double baseSelectivity) {
+        double result = baseSelectivity;
+
+        for (Map.Entry<RexNode, List<SqlKind>> e : operands.entrySet()) {
+            int eqNum = 0;
+            double result0 = 0.0;
+
+            for (SqlKind kind : e.getValue()) {
+                switch (kind) {
+                    case IS_NOT_NULL:
+                        result0 = Math.max(result0, 0.9);
+                        break;
+                    case EQUALS:
+                        // Take into account Zipf`s distribution.
+                        result0 = Math.min(result0 + (EQ_SELECTIVITY / Math.sqrt(++eqNum)), 1.0);
+                        break;
+                    case GREATER_THAN:
+                    case LESS_THAN:
+                    case GREATER_THAN_OR_EQUAL:
+                    case LESS_THAN_OR_EQUAL:
+                        result0 = Math.min(result0 + 0.5, 1.0);
+                        break;
+                    default:
+                        // Not clear here, proceed with default.
+                        result0 += 0.05;
+                }
+            }
+
+            result = Math.max(result, result0);
+        }
+
+        return result;
+    }
+
+    /**
+     * Implements selectivity prediction algorithm. <br>
+     * Current implementation work as follows: <br><br>
+     * 1. If mixed OR-related operands are processed i.e: OR(=($t1, 'D'), =($t1, 'M'), =($t2, 'W')) selectivity computes separately
+     * for each local ref and a big one is chosen <br>
+     * 2. If mixed OR or AND related operands are processed i.e:
+     * OR(<($t3, 110), >($t3, 150), AND(>=($t2, -($t1, 2)), <=($t2, +($t3, 2))), >($t4, $t2), <($t4, $t3)) selectivity computes separately
+     * for each local ref with AND selectivity adjustment. <br>
+     */
+    private static double computeSelectivity(RexCall call) {
+        ImmutableList<RexNode> operands = call.operands;
+        List<RexNode> andOperands = null;
+        List<RexNode> otherOperands = null;
+        double baseSelectivity = 0.0;
+        Map<RexNode, List<SqlKind>> processOperands = new HashMap<>();
+
+        assert !operands.isEmpty();
+
+        boolean andConsist = operands.stream().anyMatch(op -> op.isA(SqlKind.AND));
+
+        if (andConsist) {
+            for (RexNode op : operands) {
+                if (op.isA(SqlKind.AND)) {
+                    if (andOperands == null) {
+                        andOperands = new ArrayList<>();
+                    }
+
+                    andOperands.add(op);
+                } else {
+                    if (otherOperands == null) {
+                        otherOperands = new ArrayList<>();
+                    }
+
+                    otherOperands.add(op);
+                }
+            }
+        }
+
+        // AND inside OR
+        if (andOperands != null) {
+            for (RexNode andOp : andOperands) {
+                baseSelectivity = Math.max(baseSelectivity, RelMdUtil.guessSelectivity(andOp));
+            }
+        }
+
+        List<RexNode> operandsToProcess = otherOperands == null ? call.getOperands() : otherOperands;
+
+        for (RexNode node : operandsToProcess) {
+            RexNode res = getLocalRef(node);
+
+            // It can be null for case with expression for example: LENGTH('abc') = 3
+            if (res != null) {
+                List<SqlKind> vals = processOperands.computeIfAbsent(res, (k) -> new ArrayList<>());
+
+                vals.add(node.getKind());
+            } else {
+                baseSelectivity = Math.max(baseSelectivity, nonColumnRefSelectivity(call));
+            }
+        }
+
+        return computeOpsSelectivity(processOperands, baseSelectivity);
+    }
+
+    private static double nonColumnRefSelectivity(RexCall call) {
+        if (call.isA(SqlKind.EQUALS)) {
+            return EQ_SELECTIVITY;
+        } else if (call.isA(SqlKind.COMPARISON)) {
+            return 0.5;
+        } else {
+            // different OTHER_FUNCTION and other uncovered cases
+            return 0;
+        }
+    }
+
+    private static RexLocalRef getLocalRef(RexNode node) {
+        RexVisitor<Void> v = new RexVisitorImpl<>(true) {
+            @Override
+            public Void visitLocalRef(RexLocalRef locRef) {
+                throw new Util.FoundOne(locRef);
+            }
+        };
+
+        try {
+            node.accept(v);
+
+            return null;
+        } catch (Util.FoundOne e) {
+            return (RexLocalRef) e.getNode();
+        }
+    }
+
+    private static double guessSelectivity(@Nullable RexNode predicate) {
+        double sel = 1.0;
+        if ((predicate == null) || predicate.isAlwaysTrue()) {
+            return sel;
+        }
+
+        double artificialSel = 1.0;
+
+        // make set of AND ... AND calls
+        List<RexNode> conjunctions = RelOptUtil.conjunctions(predicate);
+
+        for (RexNode pred : conjunctions) {
+            // Expand sarg`s
+            RexNode predicateExpanded = expandSearch(Commons.rexBuilder(), null, pred);
+
+            if (predicateExpanded.isA(SqlKind.OR)) {
+                double processed = computeSelectivity((RexCall) predicateExpanded);
+                sel *= processed;
+            } else if (predicateExpanded.getKind() == SqlKind.IS_NOT_NULL) {
+                sel *= 0.9;
+            } else if (
+                    (predicateExpanded instanceof RexCall)
+                            && (((RexCall) predicateExpanded).getOperator()
+                            == RelMdUtil.ARTIFICIAL_SELECTIVITY_FUNC)) {
+                artificialSel *= RelMdUtil.getSelectivityValue(predicateExpanded);
+            } else if (predicateExpanded.isA(SqlKind.EQUALS)) {
+                sel *= 0.15;
+            } else if (predicateExpanded.isA(SqlKind.COMPARISON)) {
+                sel *= 0.5;
+            } else {
+                sel *= 0.25;
+            }
+        }
+
+        return sel * artificialSel;
+    }
+
     /**
      * GetSelectivity.
      * TODO Documentation https://issues.apache.org/jira/browse/IGNITE-15859

Review Comment:
   we have a few documentation TODO in the class - will be great to fix it.



##########
modules/sql-engine/src/main/java/org/apache/ignite/internal/sql/engine/metadata/IgniteMdSelectivity.java:
##########
@@ -17,49 +17,226 @@
 
 package org.apache.ignite.internal.sql.engine.metadata;
 
+import static org.apache.calcite.rex.RexUtil.expandSearch;
+
+import com.google.common.collect.ImmutableList;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import org.apache.calcite.plan.RelOptUtil;
 import org.apache.calcite.rel.metadata.ReflectiveRelMetadataProvider;
 import org.apache.calcite.rel.metadata.RelMdSelectivity;
 import org.apache.calcite.rel.metadata.RelMdUtil;
 import org.apache.calcite.rel.metadata.RelMetadataProvider;
 import org.apache.calcite.rel.metadata.RelMetadataQuery;
 import org.apache.calcite.rex.RexCall;
+import org.apache.calcite.rex.RexLocalRef;
 import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.rex.RexVisitor;
+import org.apache.calcite.rex.RexVisitorImpl;
 import org.apache.calcite.sql.SqlKind;
 import org.apache.calcite.util.BuiltInMethod;
+import org.apache.calcite.util.Util;
 import org.apache.ignite.internal.sql.engine.prepare.bounds.ExactBounds;
 import org.apache.ignite.internal.sql.engine.prepare.bounds.MultiBounds;
 import org.apache.ignite.internal.sql.engine.prepare.bounds.RangeBounds;
 import org.apache.ignite.internal.sql.engine.prepare.bounds.SearchBounds;
 import org.apache.ignite.internal.sql.engine.rel.IgniteHashIndexSpool;
 import org.apache.ignite.internal.sql.engine.rel.IgniteSortedIndexSpool;
 import org.apache.ignite.internal.sql.engine.rel.ProjectableFilterableTableScan;
+import org.apache.ignite.internal.sql.engine.util.Commons;
 import org.apache.ignite.internal.sql.engine.util.RexUtils;
+import org.checkerframework.checker.nullness.qual.Nullable;
 
 /**
- * IgniteMdSelectivity.
- * TODO Documentation https://issues.apache.org/jira/browse/IGNITE-15859
+ * IgniteMdSelectivity supplies implementation of {@link RelMetadataQuery#getSelectivity}.
  */
 public class IgniteMdSelectivity extends RelMdSelectivity {
     public static final RelMetadataProvider SOURCE =
             ReflectiveRelMetadataProvider.reflectiveSource(
                     BuiltInMethod.SELECTIVITY.method, new IgniteMdSelectivity());
 
+    private static final double EQ_SELECTIVITY = 0.333;
+
+    private static double computeOpsSelectivity(Map<RexNode, List<SqlKind>> operands, double baseSelectivity) {
+        double result = baseSelectivity;
+
+        for (Map.Entry<RexNode, List<SqlKind>> e : operands.entrySet()) {
+            int eqNum = 0;
+            double result0 = 0.0;
+
+            for (SqlKind kind : e.getValue()) {
+                switch (kind) {
+                    case IS_NOT_NULL:
+                        result0 = Math.max(result0, 0.9);
+                        break;
+                    case EQUALS:
+                        // Take into account Zipf`s distribution.
+                        result0 = Math.min(result0 + (EQ_SELECTIVITY / Math.sqrt(++eqNum)), 1.0);
+                        break;
+                    case GREATER_THAN:
+                    case LESS_THAN:
+                    case GREATER_THAN_OR_EQUAL:
+                    case LESS_THAN_OR_EQUAL:
+                        result0 = Math.min(result0 + 0.5, 1.0);
+                        break;
+                    default:
+                        // Not clear here, proceed with default.
+                        result0 += 0.05;
+                }
+            }
+
+            result = Math.max(result, result0);
+        }
+
+        return result;
+    }
+
+    /**
+     * Implements selectivity prediction algorithm. <br>
+     * Current implementation work as follows: <br><br>
+     * 1. If mixed OR-related operands are processed i.e: OR(=($t1, 'D'), =($t1, 'M'), =($t2, 'W')) selectivity computes separately
+     * for each local ref and a big one is chosen <br>
+     * 2. If mixed OR or AND related operands are processed i.e:
+     * OR(<($t3, 110), >($t3, 150), AND(>=($t2, -($t1, 2)), <=($t2, +($t3, 2))), >($t4, $t2), <($t4, $t3)) selectivity computes separately
+     * for each local ref with AND selectivity adjustment. <br>
+     */
+    private static double computeSelectivity(RexCall call) {
+        ImmutableList<RexNode> operands = call.operands;

Review Comment:
   Let's avoid use guava classes, just simple List<RexNode>



-- 
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: notifications-unsubscribe@ignite.apache.org

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


Re: [PR] IGNITE-23969 Sql. Improve predicate selectivity estimation [ignite-3]

Posted by "lowka (via GitHub)" <gi...@apache.org>.
lowka commented on code in PR #5211:
URL: https://github.com/apache/ignite-3/pull/5211#discussion_r1960999771


##########
modules/sql-engine/src/test/java/org/apache/ignite/internal/sql/engine/planner/SelectRowCountEstimationTest.java:
##########
@@ -0,0 +1,195 @@
+/*
+ * 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.
+ */
+
+package org.apache.ignite.internal.sql.engine.planner;
+
+import static org.apache.ignite.internal.sql.engine.framework.DataProvider.fromCollection;
+import static org.apache.ignite.internal.sql.engine.framework.TestBuilders.tableScan;
+import static org.apache.ignite.internal.sql.engine.metadata.IgniteMdSelectivity.COMPARISON_SELECTIVITY;
+import static org.apache.ignite.internal.sql.engine.metadata.IgniteMdSelectivity.EQ_SELECTIVITY;
+import static org.apache.ignite.internal.sql.engine.metadata.IgniteMdSelectivity.IS_NOT_NULL_SELECTIVITY;
+import static org.apache.ignite.internal.sql.engine.util.QueryChecker.nodeRowCount;
+
+import java.util.List;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+import org.apache.ignite.internal.lang.IgniteStringBuilder;
+import org.apache.ignite.internal.sql.engine.framework.TestBuilders;
+import org.apache.ignite.internal.sql.engine.framework.TestCluster;
+import org.apache.ignite.internal.sql.engine.framework.TestNode;
+import org.apache.ignite.internal.sql.engine.util.TpcTable;
+import org.apache.ignite.internal.sql.engine.util.tpcds.TpcdsTables;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+/**
+ * Tests to check row count estimation for select relation.
+ */
+public class SelectRowCountEstimationTest extends BaseRowsProcessedEstimationTest {
+    private static final int TABLE_REAL_SIZE = 73_049;
+
+    private static final TestCluster CLUSTER = TestBuilders.cluster()
+            .nodes("N1")
+            .defaultAssignmentsProvider(tableName -> (partNum, includeBackups) -> IntStream.range(0, partNum)
+                    .mapToObj(part -> List.of("N1"))
+                    .collect(Collectors.toList())
+            )
+            .defaultDataProvider(tableName -> tableScan(fromCollection(List.of())))
+            .build();
+
+    private static final TestNode NODE = CLUSTER.node("N1");
+
+    @BeforeAll
+    static void startCluster() {
+        CLUSTER.start();
+
+        for (TpcTable table : List.of(TpcdsTables.CATALOG_SALES)) {
+            NODE.initSchema(table.ddlScript());
+        }
+
+        CLUSTER.setTableSize("CATALOG_SALES", TABLE_REAL_SIZE);
+    }
+
+    @AfterAll
+    static void stopCluster() throws Exception {
+        CLUSTER.stop();
+    }
+
+    @Test
+    void testConditionWithPk() {
+        // partial pk
+        double selectivityFactor = EQ_SELECTIVITY;
+        assertQuery(NODE, "SELECT * FROM CATALOG_SALES WHERE CS_ITEM_SK = 1")
+                .matches(nodeRowCount("TableScan", approximatelyEqual(TABLE_REAL_SIZE * selectivityFactor)))
+                .check();
+
+        // full pk, eq operations
+        selectivityFactor = 1.0 / TABLE_REAL_SIZE;
+        assertQuery(NODE, "SELECT * FROM CATALOG_SALES WHERE CS_ITEM_SK = 1 AND CS_ORDER_NUMBER = 1")
+                .disableRules("TableScanToKeyValueGetRule", "LogicalIndexScanConverterRule")
+                .matches(nodeRowCount("TableScan", approximatelyEqual(TABLE_REAL_SIZE * selectivityFactor)))
+                .check();
+
+        // full pk, comp operations
+        selectivityFactor = EQ_SELECTIVITY * COMPARISON_SELECTIVITY;
+        assertQuery(NODE, "SELECT * FROM CATALOG_SALES WHERE CS_ITEM_SK = 1 AND CS_ORDER_NUMBER > 1")
+                .disableRules("TableScanToKeyValueGetRule", "LogicalIndexScanConverterRule")
+                .matches(nodeRowCount("TableScan", approximatelyEqual(TABLE_REAL_SIZE * selectivityFactor)))
+                .check();
+
+        // full pk with OR
+        selectivityFactor = EQ_SELECTIVITY;
+        assertQuery(NODE, "SELECT * FROM CATALOG_SALES WHERE (CS_ITEM_SK = 1 AND CS_ORDER_NUMBER = 1) OR CS_ORDER_NUMBER = 2")
+                .disableRules("TableScanToKeyValueGetRule", "LogicalIndexScanConverterRule")
+                .matches(nodeRowCount("TableScan", approximatelyEqual(TABLE_REAL_SIZE * selectivityFactor)))
+                .check();
+
+        // full pk or full pk
+        selectivityFactor = 1.0 / TABLE_REAL_SIZE;
+        assertQuery(NODE, "SELECT * FROM CATALOG_SALES WHERE (CS_ITEM_SK = 1 AND CS_ORDER_NUMBER = 1) "
+                + "OR (CS_ITEM_SK = 3 AND CS_ORDER_NUMBER = 3)")
+                .disableRules("TableScanToKeyValueGetRule", "LogicalIndexScanConverterRule")
+                .matches(nodeRowCount("TableScan", approximatelyEqual(TABLE_REAL_SIZE * selectivityFactor)))
+                .check();
+
+        // full pk with computation, not covered by now
+        selectivityFactor = EQ_SELECTIVITY;
+        assertQuery(NODE, "SELECT * FROM CATALOG_SALES WHERE CS_ORDER_NUMBER + CS_ITEM_SK = 1")
+                .matches(nodeRowCount("TableScan", approximatelyEqual(TABLE_REAL_SIZE * selectivityFactor)))
+                .check();
+    }
+
+    @Test
+    void testPredicatesSelectivity() {

Review Comment:
   The same as `testConditionWithPk`



-- 
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: notifications-unsubscribe@ignite.apache.org

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


Re: [PR] IGNITE-23969 Sql. Improve predicate selectivity estimation [ignite-3]

Posted by "zstan (via GitHub)" <gi...@apache.org>.
zstan commented on code in PR #5211:
URL: https://github.com/apache/ignite-3/pull/5211#discussion_r1954584039


##########
modules/sql-engine/src/main/java/org/apache/ignite/internal/sql/engine/metadata/IgniteMdSelectivity.java:
##########
@@ -17,49 +17,226 @@
 
 package org.apache.ignite.internal.sql.engine.metadata;
 
+import static org.apache.calcite.rex.RexUtil.expandSearch;
+
+import com.google.common.collect.ImmutableList;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import org.apache.calcite.plan.RelOptUtil;
 import org.apache.calcite.rel.metadata.ReflectiveRelMetadataProvider;
 import org.apache.calcite.rel.metadata.RelMdSelectivity;
 import org.apache.calcite.rel.metadata.RelMdUtil;
 import org.apache.calcite.rel.metadata.RelMetadataProvider;
 import org.apache.calcite.rel.metadata.RelMetadataQuery;
 import org.apache.calcite.rex.RexCall;
+import org.apache.calcite.rex.RexLocalRef;
 import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.rex.RexVisitor;
+import org.apache.calcite.rex.RexVisitorImpl;
 import org.apache.calcite.sql.SqlKind;
 import org.apache.calcite.util.BuiltInMethod;
+import org.apache.calcite.util.Util;
 import org.apache.ignite.internal.sql.engine.prepare.bounds.ExactBounds;
 import org.apache.ignite.internal.sql.engine.prepare.bounds.MultiBounds;
 import org.apache.ignite.internal.sql.engine.prepare.bounds.RangeBounds;
 import org.apache.ignite.internal.sql.engine.prepare.bounds.SearchBounds;
 import org.apache.ignite.internal.sql.engine.rel.IgniteHashIndexSpool;
 import org.apache.ignite.internal.sql.engine.rel.IgniteSortedIndexSpool;
 import org.apache.ignite.internal.sql.engine.rel.ProjectableFilterableTableScan;
+import org.apache.ignite.internal.sql.engine.util.Commons;
 import org.apache.ignite.internal.sql.engine.util.RexUtils;
+import org.checkerframework.checker.nullness.qual.Nullable;
 
 /**
- * IgniteMdSelectivity.
- * TODO Documentation https://issues.apache.org/jira/browse/IGNITE-15859
+ * IgniteMdSelectivity supplies implementation of {@link RelMetadataQuery#getSelectivity}.
  */
 public class IgniteMdSelectivity extends RelMdSelectivity {
     public static final RelMetadataProvider SOURCE =
             ReflectiveRelMetadataProvider.reflectiveSource(
                     BuiltInMethod.SELECTIVITY.method, new IgniteMdSelectivity());
 
+    private static final double EQ_SELECTIVITY = 0.333;
+
+    private static double computeOpsSelectivity(Map<RexNode, List<SqlKind>> operands, double baseSelectivity) {
+        double result = baseSelectivity;
+
+        for (Map.Entry<RexNode, List<SqlKind>> e : operands.entrySet()) {
+            int eqNum = 0;
+            double result0 = 0.0;
+
+            for (SqlKind kind : e.getValue()) {
+                switch (kind) {
+                    case IS_NOT_NULL:
+                        result0 = Math.max(result0, 0.9);
+                        break;
+                    case EQUALS:
+                        // Take into account Zipf`s distribution.
+                        result0 = Math.min(result0 + (EQ_SELECTIVITY / Math.sqrt(++eqNum)), 1.0);
+                        break;
+                    case GREATER_THAN:
+                    case LESS_THAN:
+                    case GREATER_THAN_OR_EQUAL:
+                    case LESS_THAN_OR_EQUAL:
+                        result0 = Math.min(result0 + 0.5, 1.0);
+                        break;
+                    default:
+                        // Not clear here, proceed with default.
+                        result0 += 0.05;
+                }
+            }
+
+            result = Math.max(result, result0);
+        }
+
+        return result;
+    }
+
+    /**
+     * Implements selectivity prediction algorithm. <br>
+     * Current implementation work as follows: <br><br>
+     * 1. If mixed OR-related operands are processed i.e: OR(=($t1, 'D'), =($t1, 'M'), =($t2, 'W')) selectivity computes separately
+     * for each local ref and a big one is chosen <br>
+     * 2. If mixed OR or AND related operands are processed i.e:
+     * OR(<($t3, 110), >($t3, 150), AND(>=($t2, -($t1, 2)), <=($t2, +($t3, 2))), >($t4, $t2), <($t4, $t3)) selectivity computes separately
+     * for each local ref with AND selectivity adjustment. <br>
+     */
+    private static double computeSelectivity(RexCall call) {
+        ImmutableList<RexNode> operands = call.operands;
+        List<RexNode> andOperands = null;
+        List<RexNode> otherOperands = null;
+        double baseSelectivity = 0.0;
+        Map<RexNode, List<SqlKind>> processOperands = new HashMap<>();
+
+        assert !operands.isEmpty();
+
+        boolean andConsist = operands.stream().anyMatch(op -> op.isA(SqlKind.AND));
+
+        if (andConsist) {
+            for (RexNode op : operands) {
+                if (op.isA(SqlKind.AND)) {
+                    if (andOperands == null) {

Review Comment:
   ok, i change it



-- 
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: notifications-unsubscribe@ignite.apache.org

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