Refactor query builder.

Refactor the query builder.