refactor search query code