refactor query and add a trait so it is reusable