Simplified Query.build_lookup()

Splitted Query.build_lookup() to two parts, and added some clarifying comments.

Please merge after sanity check.