Refactor some search stuff

you could wrap this whole block with `if data.get('sort')`