Thoroughly refactor query API based on materialized views.