[kv] Support distinct elements in last_n aggregation
Search before asking
Related issue: #4569 introduces last_n aggregation. This proposal extends it with optional deduplication. I searched the existing issues and found no separate request for this extension.
Motivation
The last_n aggregation retains the last N array elements, including duplicates. For use cases such as recently viewed products, users need the last N distinct elements so repeated values do not consume multiple slots.
Deduplicating the result of the existing last_n aggregation can return fewer than N elements, because earlier distinct values have already been discarded.
Solution
Add an optional distinct parameter to last_n, defaulting to false to preserve existing behavior:
'fields.recent_items.agg' = 'last_n',
'fields.recent_items.last_n.size' = '3',
'fields.recent_items.last_n.distinct' = 'true'
When enabled, deduplicate elements before retaining the last N distinct values. Retain the last occurrence of each value, preserving their relative order. Repeated values move to the end.
For size=3:
| Input sequence | Result |
|---|---|
| A, B, C, C | [A, B, C] |
| A, B, C, B | [A, C, B] |
| A, B, C, B, D | [C, B, D] |
Apply the same semantics to duplicates within an input array and across successive writes.
Use the existing collect(distinct) element-equality rules: top-level byte arrays compare by content; other values retain their current element equality, including representation-sensitive nested values. Keep collect(distinct) behavior unchanged.
A null input leaves the stored array unchanged. Null elements count as one distinct value.
Anything else?
Ordering continues to follow the order writes reach the server, consistent with the existing last_n behavior.
Willingness to contribute
- [x] I'm willing to submit a PR!