-
Notifications
You must be signed in to change notification settings - Fork 2.3k
feat: derive a distinct count from primary key and unique constraints #24520
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Dandandan
merged 7 commits into
apache:main
from
Dandandan:feat/pk-cardinality-estimation
Aug 22, 2026
+315
−3
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
32d17cb
feat: derive a distinct count from primary key and unique constraints
Dandandan d723f9e
Store the derived distinct counts instead of deriving them on every read
Dandandan 867aae3
Honour the declared constraint: the derived count is as exact as the …
Dandandan b3c76d3
feat: an equality on a unique column matches one row at most
Dandandan d16d257
Extend it to an IN list: one row per value asked for
Dandandan 15acadf
Improve clarity
Dandandan a2a557c
Move equality column collection documentation
Dandandan File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -63,7 +63,7 @@ use datafusion_execution::TaskContext; | |
| use datafusion_expr::Operator; | ||
| use datafusion_physical_expr::equivalence::ProjectionMapping; | ||
| use datafusion_physical_expr::expressions::{ | ||
| BinaryExpr, Column, IsNotNullExpr, Literal, lit, | ||
| BinaryExpr, Column, InListExpr, IsNotNullExpr, Literal, lit, | ||
| }; | ||
| use datafusion_physical_expr::intervals::utils::check_support; | ||
| use datafusion_physical_expr::utils::{collect_columns, reassign_expr_columns}; | ||
|
|
@@ -343,6 +343,11 @@ impl FilterExec { | |
| let input_num_rows = input_stats.num_rows; | ||
| let input_total_byte_size = input_stats.total_byte_size; | ||
|
|
||
| // A column holding each of its values once, as a primary key or unique | ||
| // constraint says, matches one row per value asked for. No selectivity | ||
| // expresses that. | ||
| let match_limit = unique_match_limit(predicate, &input_stats); | ||
|
|
||
| let (selectivity, num_rows, column_statistics) = if is_infeasible { | ||
| // Contradictory predicate: no rows survive. Row-bounded counts are | ||
| // zero; value statistics are undefined on an empty column. | ||
|
|
@@ -406,6 +411,10 @@ impl FilterExec { | |
| } | ||
| }; | ||
|
|
||
| let num_rows = match (match_limit, num_rows.get_value()) { | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think we should rescale accordingly |
||
| (Some(limit), Some(rows)) if *rows > limit => Precision::Inexact(limit), | ||
| _ => num_rows, | ||
| }; | ||
| let total_byte_size = | ||
| scale_byte_size_at_rows(input_total_byte_size, selectivity, num_rows); | ||
|
|
||
|
|
@@ -948,6 +957,76 @@ impl EmbeddedProjection for FilterExec { | |
| } | ||
| } | ||
|
|
||
| /// The most rows a filter can match, when it restricts a column holding each value | ||
| /// once to a fixed set of values: one row per value. | ||
| fn unique_match_limit( | ||
| predicate: &Arc<dyn PhysicalExpr>, | ||
| statistics: &Statistics, | ||
| ) -> Option<usize> { | ||
| let mut limit: Option<usize> = None; | ||
| for expr in split_conjunction(predicate) { | ||
| let Some((index, values)) = restricted_column(expr) else { | ||
| continue; | ||
| }; | ||
| let holds_once = statistics | ||
| .column_statistics | ||
| .get(index) | ||
| .is_some_and(|column| holds_each_value_once(column, &statistics.num_rows)); | ||
| if !holds_once { | ||
| continue; | ||
| } | ||
| limit = Some(limit.map_or(values, |limit: usize| limit.min(values))); | ||
| } | ||
| limit | ||
| } | ||
|
|
||
| /// The column an expression restricts to a fixed set of values, and how many values | ||
| /// that is. NULL is never one of them: it matches nothing. | ||
| fn restricted_column(expr: &Arc<dyn PhysicalExpr>) -> Option<(usize, usize)> { | ||
| if let Some(in_list) = expr.downcast_ref::<InListExpr>() { | ||
| if in_list.negated() { | ||
| return None; | ||
| } | ||
| let column = in_list.expr().downcast_ref::<Column>()?; | ||
| let mut values: Vec<&ScalarValue> = vec![]; | ||
| for expr in in_list.list() { | ||
| let value = expr.downcast_ref::<Literal>()?.value(); | ||
| if !value.is_null() && !values.contains(&value) { | ||
| values.push(value); | ||
| } | ||
| } | ||
| return Some((column.index(), values.len())); | ||
| } | ||
|
|
||
| let binary = expr.downcast_ref::<BinaryExpr>()?; | ||
| if *binary.op() != Operator::Eq { | ||
| return None; | ||
| } | ||
| let (column, literal) = match ( | ||
| binary.left().downcast_ref::<Column>(), | ||
| binary.right().downcast_ref::<Column>(), | ||
| ) { | ||
| (Some(column), None) => (column, binary.right()), | ||
| (None, Some(column)) => (column, binary.left()), | ||
| _ => return None, | ||
| }; | ||
| let value = literal.downcast_ref::<Literal>()?.value(); | ||
| (!value.is_null()).then_some((column.index(), 1)) | ||
| } | ||
|
|
||
| /// Whether the column has as many distinct values as it has non-null rows, so each | ||
| /// value appears once. | ||
| fn holds_each_value_once(column: &ColumnStatistics, num_rows: &Precision<usize>) -> bool { | ||
| let (Some(rows), Some(distinct), Some(nulls)) = ( | ||
| num_rows.get_value(), | ||
| column.distinct_count.get_value(), | ||
| column.null_count.get_value(), | ||
| ) else { | ||
| return false; | ||
| }; | ||
| distinct.saturating_add(*nulls) >= *rows | ||
| } | ||
|
|
||
| /// Collects column equality information from `col = literal` predicates in a | ||
| /// conjunction. | ||
| /// | ||
|
|
@@ -1462,6 +1541,100 @@ mod tests { | |
| Ok(()) | ||
| } | ||
|
|
||
| /// An equality on a column that holds each value once matches one row at most, | ||
| /// including on a type interval analysis cannot read, where the default | ||
| /// selectivity would otherwise apply. | ||
| #[tokio::test] | ||
| async fn test_filter_statistics_equality_on_a_unique_column() -> Result<()> { | ||
| let schema = Schema::new(vec![Field::new("id", DataType::Utf8, true)]); | ||
| let unique = ColumnStatistics { | ||
| null_count: Precision::Exact(0), | ||
| distinct_count: Precision::Exact(100), | ||
| ..Default::default() | ||
| }; | ||
| let rows = |column: ColumnStatistics| -> Result<Precision<usize>> { | ||
| let input = Arc::new(StatisticsExec::new( | ||
| Statistics { | ||
| num_rows: Precision::Exact(100), | ||
| total_byte_size: Precision::Exact(800), | ||
| column_statistics: vec![column], | ||
| }, | ||
| schema.clone(), | ||
| )); | ||
| let predicate = | ||
| binary(col("id", &schema)?, Operator::Eq, lit("seven"), &schema)?; | ||
| let filter: Arc<dyn ExecutionPlan> = | ||
| Arc::new(FilterExec::try_new(predicate, input)?); | ||
| Ok(StatisticsContext::new() | ||
| .compute(filter.as_ref(), &StatisticsArgs::new())? | ||
| .num_rows) | ||
| }; | ||
|
|
||
| assert_eq!(rows(unique.clone())?, Precision::Inexact(1)); | ||
|
|
||
| // The nulls a unique column may repeat do not make it hold a value twice. | ||
| assert_eq!( | ||
| rows(ColumnStatistics { | ||
| null_count: Precision::Exact(10), | ||
| distinct_count: Precision::Exact(90), | ||
| ..unique.clone() | ||
| })?, | ||
| Precision::Inexact(1) | ||
| ); | ||
|
|
||
| // Without a distinct count, the default selectivity applies as before. | ||
| assert_eq!( | ||
| rows(ColumnStatistics { | ||
| distinct_count: Precision::Absent, | ||
| ..unique | ||
| })?, | ||
| Precision::Inexact(20) | ||
| ); | ||
|
|
||
| Ok(()) | ||
| } | ||
|
|
||
| /// Asking a unique column for three values matches three rows at most. | ||
| #[tokio::test] | ||
| async fn test_filter_statistics_in_list_on_a_unique_column() -> Result<()> { | ||
| use datafusion_physical_expr::expressions::in_list; | ||
|
|
||
| let schema = Schema::new(vec![Field::new("id", DataType::Utf8, true)]); | ||
| let rows = |list: Vec<&str>, negated: bool| -> Result<Precision<usize>> { | ||
| let input = Arc::new(StatisticsExec::new( | ||
| Statistics { | ||
| num_rows: Precision::Exact(100), | ||
| total_byte_size: Precision::Exact(800), | ||
| column_statistics: vec![ColumnStatistics { | ||
| null_count: Precision::Exact(0), | ||
| distinct_count: Precision::Exact(100), | ||
| ..Default::default() | ||
| }], | ||
| }, | ||
| schema.clone(), | ||
| )); | ||
| let predicate = in_list( | ||
| col("id", &schema)?, | ||
| list.into_iter().map(|value| lit(value) as _).collect(), | ||
| &negated, | ||
| &schema, | ||
| )?; | ||
| let filter: Arc<dyn ExecutionPlan> = | ||
| Arc::new(FilterExec::try_new(predicate, input)?); | ||
| Ok(StatisticsContext::new() | ||
| .compute(filter.as_ref(), &StatisticsArgs::new())? | ||
| .num_rows) | ||
| }; | ||
|
|
||
| assert_eq!(rows(vec!["a", "b", "c"], false)?, Precision::Inexact(3)); | ||
| // Repeats ask for the same row twice. | ||
| assert_eq!(rows(vec!["a", "b", "a"], false)?, Precision::Inexact(2)); | ||
| // `NOT IN` selects nearly everything, so the default applies. | ||
| assert_eq!(rows(vec!["a", "b", "c"], true)?, Precision::Inexact(20)); | ||
|
|
||
| Ok(()) | ||
| } | ||
|
|
||
| #[tokio::test] | ||
| async fn test_filter_statistics_basic_expr() -> Result<()> { | ||
| // Table: | ||
|
|
||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Minor: I guess this would be applicable as-is to more table providers, it's fine to do as follow-up but maybe we could move the function somewhere else higher up in
datasource?