Rework of search query to be optimized to work with Postgres