Refactor the code to works with query
Tested the examples.