Dandandan commented on issue #7149: URL: https://github.com/apache/arrow-datafusion/issues/7149#issuecomment-1660450287
> > why bother with materializing the record batches from the [input stream](https://github.com/apache/arrow-datafusion/blob/main/datafusion/core/src/physical_plan/sorts/sort.rs#L611) and potentially spilling them to the disk at this point, only for them to be [streamed back](https://github.com/apache/arrow-datafusion/blob/main/datafusion/core/src/physical_plan/sorts/sort.rs#L174-L193) into streaming_merge function again? > > Oh, to answer my own question it's because `streaming_merge` assumes the input is sorted, and to do that we need to materialize the original stream, which also involves disk spill over, got it. > > One partial improvement would be something like concatenating and sorting the incoming batches into a single batch inside `insert_batch`, and then optionally spilling that over to disk; still, this results in a trade-off between time and memory efficiency of such cases, since it would require sorting of each intermediate batch (albeit partially sorted already). > > I guess the real solution would be something like an external top-k algorithm which would work on the original input stream and use a min/max heap with spillover in case `fetch` is some value (actually it was my impression this was already implemented). Not sure how viable is that though. Yes it only concatenates them once the limit has been (almost) reached, but avoids spilling the data. Potentially this could be done at an earlier stage (say after processing 1/10 of the memory limit) to keep memory usage down during processing (while also avoiding too much overhead in terms of copying). As well there is indeed no real TopK implementation yet, so as @alamb suggests a `SortExec(fetch=1)` could also be faster / more efficient with a real TopK (min/max heap) implementation. -- 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: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
