apache / apache/datafusion

`select count(distinct ..)` query doesn't go to the specialized distinct accumulator

Open
#15,850 2 comments 0 reactions 0 assignees View on GitHub
enhancement performance
Dominant language
Rust
Stars
9.3k
Forks
2.4k
Avg merge
3d 7h
Merged PRs (30d)
344

Description

### Is your feature request related to a problem or challenge?

```
statement count 0
create table t(a int) as values (1), (2);

query I
select count(distinct a) from t;
----
2

query TT
explain
select count(distinct a) from t;
----
logical_plan
01)Projection: count(alias1) AS count(DISTINCT t.a)
02)--Aggregate: groupBy=[[]], aggr=[[count(alias1)]]
03)----Aggregate: groupBy=[[t.a AS alias1]], aggr=[[]]
04)------TableScan: t projection=[a]
physical_plan
01)ProjectionExec: expr=[count(alias1)@0 as count(DISTINCT t.a)]
02)--AggregateExec: mode=Final, gby=[], aggr=[count(alias1)]
03)----CoalescePartitionsExec
04)------AggregateExec: mode=Partial, gby=[], aggr=[count(alias1)]
05)--------AggregateExec: mode=FinalPartitioned, gby=[alias1@0 as alias1], aggr=[]
06)----------CoalesceBatchesExec: target_batch_size=8192
07)------------RepartitionExec: partitioning=Hash([alias1@0], 4), input_partitions=4
08)--------------RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1
09)----------------AggregateExec: mode=Partial, gby=[a@0 as alias1], aggr=[]
10)------------------DataSourceExec: partitions=1, partition_sizes=[1]

```

I think we should execute with the specialized count distinct accumualator like `PrimitiveDistinctCountAccumulator`, `BytesDistinctCountAccumulator`, `FloatDistinctCountAccumulator`. Current execution path looks quite complex and probably not that optimized.

I expect specialized count distinct would be faster than two aggregate exec combined

### Describe the solution you'd like

Investigate why distinct count accumulator is not called and whether switching to it improves the code.

ClickBench has query like count(distinct), so we could benchmark against it to see if the improvement works

### Describe alternatives you've considered

_No response_

### Additional context

_No response_

Contributor guide

Open the contributing guide

Research direction

Start with the count(distinct a) SQL and its logical and physical plans in the issue, then inspect the named PrimitiveDistinctCountAccumulator, BytesDistinctCountAccumulator, and FloatDistinctCountAccumulator implementations and their call paths. Compare the current two-aggregate execution with the specialized accumulator, and use a ClickBench count(distinct) query to determine whether switching improves performance.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
data-engineering, performance
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.