Refactor query function

Refactor query function