Fixed build_nested_query to handle empty arrays and hashes