refactor and explain build_query_factor