Apply filters when writing index

This adds a test to #2607, and refactors a little bit to avoid copying buffers around.