Implement the Query->iterate method which will return an IteratableResultSet as per the ORM.
I am surprised it isn't there already. I keep hitting memory limits whenever I have to rebuild my elasticsearch index from the database. Surprisingly detaching while iterating during a foreach doesn't free up memory.
you are welcome to do a PR to implement the feature ;-)
detach should free the memory normally. are you sure you don't keep any references elsewhere?
you could try to call $dm->clear() to wipe the whole document manager when you are doing batch processing. maybe we have an issue with the detach that we don't free everything. does clear work better?
if $dm->clear does not help then i strongly suspect that you keep references to the objects somewhere else in your code that prevent garbage collection from working.